blob: f70c06377e2d881de9549a5426f9f68e9cd6f0af [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"
Alexey Bataev1a3320e2015-08-25 14:24:04 +000024#include "clang/AST/ExprOpenMP.h"
Mike Stump0c2ec772010-01-21 03:59:47 +000025#include "clang/AST/StmtCXX.h"
26#include "clang/AST/StmtObjC.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000027#include "clang/Analysis/Analyses/FormatString.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000028#include "clang/Basic/CharInfo.h"
Eric Christopher8d0c6212010-04-17 02:26:23 +000029#include "clang/Basic/TargetBuiltins.h"
Nate Begeman4904e322010-06-08 02:47:44 +000030#include "clang/Basic/TargetInfo.h"
Alp Tokerb6cc5922014-05-03 03:45:55 +000031#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
Chandler Carruth3a022472012-12-04 09:13:33 +000032#include "clang/Sema/Initialization.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000033#include "clang/Sema/Lookup.h"
34#include "clang/Sema/ScopeInfo.h"
35#include "clang/Sema/Sema.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000036#include "llvm/ADT/STLExtras.h"
Richard Smithd7293d72013-08-05 18:49:43 +000037#include "llvm/ADT/SmallBitVector.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000038#include "llvm/ADT/SmallString.h"
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +000039#include "llvm/Support/Format.h"
40#include "llvm/Support/Locale.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000041#include "llvm/Support/ConvertUTF.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000042#include "llvm/Support/raw_ostream.h"
Zhongxing Xu050379b2009-05-20 01:55:10 +000043#include <limits>
Eugene Zelenko1ced5092016-02-12 22:53:10 +000044
Chris Lattnerb87b1b32007-08-10 20:18:51 +000045using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000046using namespace sema;
Chris Lattnerb87b1b32007-08-10 20:18:51 +000047
Chris Lattnera26fb342009-02-18 17:49:48 +000048SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
49 unsigned ByteNo) const {
Alp Tokerb6cc5922014-05-03 03:45:55 +000050 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
51 Context.getTargetInfo());
Chris Lattnera26fb342009-02-18 17:49:48 +000052}
53
John McCallbebede42011-02-26 05:39:39 +000054/// Checks that a call expression's argument count is the desired number.
55/// This is useful when doing custom type-checking. Returns true on error.
56static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
57 unsigned argCount = call->getNumArgs();
58 if (argCount == desiredArgCount) return false;
59
60 if (argCount < desiredArgCount)
61 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
62 << 0 /*function call*/ << desiredArgCount << argCount
63 << call->getSourceRange();
64
65 // Highlight all the excess arguments.
66 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
67 call->getArg(argCount - 1)->getLocEnd());
68
69 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
70 << 0 /*function call*/ << desiredArgCount << argCount
71 << call->getArg(1)->getSourceRange();
72}
73
Julien Lerouge4a5b4442012-04-28 17:39:16 +000074/// Check that the first argument to __builtin_annotation is an integer
75/// and the second argument is a non-wide string literal.
76static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
77 if (checkArgCount(S, TheCall, 2))
78 return true;
79
80 // First argument should be an integer.
81 Expr *ValArg = TheCall->getArg(0);
82 QualType Ty = ValArg->getType();
83 if (!Ty->isIntegerType()) {
84 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
85 << ValArg->getSourceRange();
Julien Lerouge5a6b6982011-09-09 22:41:49 +000086 return true;
87 }
Julien Lerouge4a5b4442012-04-28 17:39:16 +000088
89 // Second argument should be a constant string.
90 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
91 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
92 if (!Literal || !Literal->isAscii()) {
93 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
94 << StrArg->getSourceRange();
95 return true;
96 }
97
98 TheCall->setType(Ty);
Julien Lerouge5a6b6982011-09-09 22:41:49 +000099 return false;
100}
101
Richard Smith6cbd65d2013-07-11 02:27:57 +0000102/// Check that the argument to __builtin_addressof is a glvalue, and set the
103/// result type to the corresponding pointer type.
104static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
105 if (checkArgCount(S, TheCall, 1))
106 return true;
107
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000108 ExprResult Arg(TheCall->getArg(0));
Richard Smith6cbd65d2013-07-11 02:27:57 +0000109 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
110 if (ResultType.isNull())
111 return true;
112
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000113 TheCall->setArg(0, Arg.get());
Richard Smith6cbd65d2013-07-11 02:27:57 +0000114 TheCall->setType(ResultType);
115 return false;
116}
117
John McCall03107a42015-10-29 20:48:01 +0000118static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
119 if (checkArgCount(S, TheCall, 3))
120 return true;
121
122 // First two arguments should be integers.
123 for (unsigned I = 0; I < 2; ++I) {
124 Expr *Arg = TheCall->getArg(I);
125 QualType Ty = Arg->getType();
126 if (!Ty->isIntegerType()) {
127 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_int)
128 << Ty << Arg->getSourceRange();
129 return true;
130 }
131 }
132
133 // Third argument should be a pointer to a non-const integer.
134 // IRGen correctly handles volatile, restrict, and address spaces, and
135 // the other qualifiers aren't possible.
136 {
137 Expr *Arg = TheCall->getArg(2);
138 QualType Ty = Arg->getType();
139 const auto *PtrTy = Ty->getAs<PointerType>();
140 if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
141 !PtrTy->getPointeeType().isConstQualified())) {
142 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_ptr_int)
143 << Ty << Arg->getSourceRange();
144 return true;
145 }
146 }
147
148 return false;
149}
150
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000151static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
152 CallExpr *TheCall, unsigned SizeIdx,
153 unsigned DstSizeIdx) {
154 if (TheCall->getNumArgs() <= SizeIdx ||
155 TheCall->getNumArgs() <= DstSizeIdx)
156 return;
157
158 const Expr *SizeArg = TheCall->getArg(SizeIdx);
159 const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
160
161 llvm::APSInt Size, DstSize;
162
163 // find out if both sizes are known at compile time
164 if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
165 !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
166 return;
167
168 if (Size.ule(DstSize))
169 return;
170
171 // confirmed overflow so generate the diagnostic.
172 IdentifierInfo *FnName = FDecl->getIdentifier();
173 SourceLocation SL = TheCall->getLocStart();
174 SourceRange SR = TheCall->getSourceRange();
175
176 S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
177}
178
Peter Collingbournef7706832014-12-12 23:41:25 +0000179static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
180 if (checkArgCount(S, BuiltinCall, 2))
181 return true;
182
183 SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
184 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
185 Expr *Call = BuiltinCall->getArg(0);
186 Expr *Chain = BuiltinCall->getArg(1);
187
188 if (Call->getStmtClass() != Stmt::CallExprClass) {
189 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
190 << Call->getSourceRange();
191 return true;
192 }
193
194 auto CE = cast<CallExpr>(Call);
195 if (CE->getCallee()->getType()->isBlockPointerType()) {
196 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
197 << Call->getSourceRange();
198 return true;
199 }
200
201 const Decl *TargetDecl = CE->getCalleeDecl();
202 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
203 if (FD->getBuiltinID()) {
204 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
205 << Call->getSourceRange();
206 return true;
207 }
208
209 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
210 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
211 << Call->getSourceRange();
212 return true;
213 }
214
215 ExprResult ChainResult = S.UsualUnaryConversions(Chain);
216 if (ChainResult.isInvalid())
217 return true;
218 if (!ChainResult.get()->getType()->isPointerType()) {
219 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
220 << Chain->getSourceRange();
221 return true;
222 }
223
David Majnemerced8bdf2015-02-25 17:36:15 +0000224 QualType ReturnTy = CE->getCallReturnType(S.Context);
Peter Collingbournef7706832014-12-12 23:41:25 +0000225 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
226 QualType BuiltinTy = S.Context.getFunctionType(
227 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
228 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
229
230 Builtin =
231 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
232
233 BuiltinCall->setType(CE->getType());
234 BuiltinCall->setValueKind(CE->getValueKind());
235 BuiltinCall->setObjectKind(CE->getObjectKind());
236 BuiltinCall->setCallee(Builtin);
237 BuiltinCall->setArg(1, ChainResult.get());
238
239 return false;
240}
241
Reid Kleckner1d59f992015-01-22 01:36:17 +0000242static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
243 Scope::ScopeFlags NeededScopeFlags,
244 unsigned DiagID) {
245 // Scopes aren't available during instantiation. Fortunately, builtin
246 // functions cannot be template args so they cannot be formed through template
247 // instantiation. Therefore checking once during the parse is sufficient.
248 if (!SemaRef.ActiveTemplateInstantiations.empty())
249 return false;
250
251 Scope *S = SemaRef.getCurScope();
252 while (S && !S->isSEHExceptScope())
253 S = S->getParent();
254 if (!S || !(S->getFlags() & NeededScopeFlags)) {
255 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
256 SemaRef.Diag(TheCall->getExprLoc(), DiagID)
257 << DRE->getDecl()->getIdentifier();
258 return true;
259 }
260
261 return false;
262}
263
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000264/// Returns OpenCL access qual.
Xiuli Pan11e13f62016-02-26 03:13:03 +0000265static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
Xiuli Pan11e13f62016-02-26 03:13:03 +0000266 return D->getAttr<OpenCLAccessAttr>();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000267}
268
269/// Returns true if pipe element type is different from the pointer.
270static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
271 const Expr *Arg0 = Call->getArg(0);
272 // First argument type should always be pipe.
273 if (!Arg0->getType()->isPipeType()) {
274 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000275 << Call->getDirectCallee() << Arg0->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000276 return true;
277 }
Xiuli Pan11e13f62016-02-26 03:13:03 +0000278 OpenCLAccessAttr *AccessQual =
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000279 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
280 // Validates the access qualifier is compatible with the call.
281 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
282 // read_only and write_only, and assumed to be read_only if no qualifier is
283 // specified.
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000284 switch (Call->getDirectCallee()->getBuiltinID()) {
285 case Builtin::BIread_pipe:
286 case Builtin::BIreserve_read_pipe:
287 case Builtin::BIcommit_read_pipe:
288 case Builtin::BIwork_group_reserve_read_pipe:
289 case Builtin::BIsub_group_reserve_read_pipe:
290 case Builtin::BIwork_group_commit_read_pipe:
291 case Builtin::BIsub_group_commit_read_pipe:
292 if (!(!AccessQual || AccessQual->isReadOnly())) {
293 S.Diag(Arg0->getLocStart(),
294 diag::err_opencl_builtin_pipe_invalid_access_modifier)
295 << "read_only" << Arg0->getSourceRange();
296 return true;
297 }
298 break;
299 case Builtin::BIwrite_pipe:
300 case Builtin::BIreserve_write_pipe:
301 case Builtin::BIcommit_write_pipe:
302 case Builtin::BIwork_group_reserve_write_pipe:
303 case Builtin::BIsub_group_reserve_write_pipe:
304 case Builtin::BIwork_group_commit_write_pipe:
305 case Builtin::BIsub_group_commit_write_pipe:
306 if (!(AccessQual && AccessQual->isWriteOnly())) {
307 S.Diag(Arg0->getLocStart(),
308 diag::err_opencl_builtin_pipe_invalid_access_modifier)
309 << "write_only" << Arg0->getSourceRange();
310 return true;
311 }
312 break;
313 default:
314 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000315 }
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000316 return false;
317}
318
319/// Returns true if pipe element type is different from the pointer.
320static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
321 const Expr *Arg0 = Call->getArg(0);
322 const Expr *ArgIdx = Call->getArg(Idx);
323 const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000324 const QualType EltTy = PipeTy->getElementType();
325 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000326 // The Idx argument should be a pointer and the type of the pointer and
327 // the type of pipe element should also be the same.
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000328 if (!ArgTy ||
329 !S.Context.hasSameType(
330 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000331 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000332 << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000333 << ArgIdx->getType() << ArgIdx->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000334 return true;
335 }
336 return false;
337}
338
339// \brief Performs semantic analysis for the read/write_pipe call.
340// \param S Reference to the semantic analyzer.
341// \param Call A pointer to the builtin call.
342// \return True if a semantic error has been found, false otherwise.
343static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000344 // OpenCL v2.0 s6.13.16.2 - The built-in read/write
345 // functions have two forms.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000346 switch (Call->getNumArgs()) {
347 case 2: {
348 if (checkOpenCLPipeArg(S, Call))
349 return true;
350 // The call with 2 arguments should be
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000351 // read/write_pipe(pipe T, T*).
352 // Check packet type T.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000353 if (checkOpenCLPipePacketType(S, Call, 1))
354 return true;
355 } break;
356
357 case 4: {
358 if (checkOpenCLPipeArg(S, Call))
359 return true;
360 // The call with 4 arguments should be
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000361 // read/write_pipe(pipe T, reserve_id_t, uint, T*).
362 // Check reserve_id_t.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000363 if (!Call->getArg(1)->getType()->isReserveIDT()) {
364 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000365 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000366 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000367 return true;
368 }
369
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000370 // Check the index.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000371 const Expr *Arg2 = Call->getArg(2);
372 if (!Arg2->getType()->isIntegerType() &&
373 !Arg2->getType()->isUnsignedIntegerType()) {
374 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000375 << Call->getDirectCallee() << S.Context.UnsignedIntTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000376 << Arg2->getType() << Arg2->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000377 return true;
378 }
379
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000380 // Check packet type T.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000381 if (checkOpenCLPipePacketType(S, Call, 3))
382 return true;
383 } break;
384 default:
385 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000386 << Call->getDirectCallee() << Call->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000387 return true;
388 }
389
390 return false;
391}
392
393// \brief Performs a semantic analysis on the {work_group_/sub_group_
394// /_}reserve_{read/write}_pipe
395// \param S Reference to the semantic analyzer.
396// \param Call The call to the builtin function to be analyzed.
397// \return True if a semantic error was found, false otherwise.
398static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
399 if (checkArgCount(S, Call, 2))
400 return true;
401
402 if (checkOpenCLPipeArg(S, Call))
403 return true;
404
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000405 // Check the reserve size.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000406 if (!Call->getArg(1)->getType()->isIntegerType() &&
407 !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
408 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000409 << Call->getDirectCallee() << S.Context.UnsignedIntTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000410 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000411 return true;
412 }
413
414 return false;
415}
416
417// \brief Performs a semantic analysis on {work_group_/sub_group_
418// /_}commit_{read/write}_pipe
419// \param S Reference to the semantic analyzer.
420// \param Call The call to the builtin function to be analyzed.
421// \return True if a semantic error was found, false otherwise.
422static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
423 if (checkArgCount(S, Call, 2))
424 return true;
425
426 if (checkOpenCLPipeArg(S, Call))
427 return true;
428
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000429 // Check reserve_id_t.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000430 if (!Call->getArg(1)->getType()->isReserveIDT()) {
431 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000432 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000433 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000434 return true;
435 }
436
437 return false;
438}
439
440// \brief Performs a semantic analysis on the call to built-in Pipe
441// Query Functions.
442// \param S Reference to the semantic analyzer.
443// \param Call The call to the builtin function to be analyzed.
444// \return True if a semantic error was found, false otherwise.
445static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
446 if (checkArgCount(S, Call, 1))
447 return true;
448
449 if (!Call->getArg(0)->getType()->isPipeType()) {
450 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000451 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000452 return true;
453 }
454
455 return false;
456}
457
John McCalldadc5752010-08-24 06:29:42 +0000458ExprResult
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000459Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
460 CallExpr *TheCall) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000461 ExprResult TheCallResult(TheCall);
Douglas Gregorae2fbad2008-11-17 20:34:05 +0000462
Chris Lattner3be167f2010-10-01 23:23:24 +0000463 // Find out if any arguments are required to be integer constant expressions.
464 unsigned ICEArguments = 0;
465 ASTContext::GetBuiltinTypeError Error;
466 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
467 if (Error != ASTContext::GE_None)
468 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
469
470 // If any arguments are required to be ICE's, check and diagnose.
471 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
472 // Skip arguments not required to be ICE's.
473 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
474
475 llvm::APSInt Result;
476 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
477 return true;
478 ICEArguments &= ~(1 << ArgNo);
479 }
480
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000481 switch (BuiltinID) {
Chris Lattner43be2e62007-12-19 23:59:04 +0000482 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner08464942007-12-28 05:29:59 +0000483 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner2da14fb2007-12-20 00:26:33 +0000484 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner6436fb62009-02-18 06:01:06 +0000485 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000486 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000487 break;
Ted Kremeneka174c522008-07-09 17:58:53 +0000488 case Builtin::BI__builtin_stdarg_start:
Chris Lattner43be2e62007-12-19 23:59:04 +0000489 case Builtin::BI__builtin_va_start:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000490 if (SemaBuiltinVAStart(TheCall))
491 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000492 break;
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000493 case Builtin::BI__va_start: {
494 switch (Context.getTargetInfo().getTriple().getArch()) {
495 case llvm::Triple::arm:
496 case llvm::Triple::thumb:
497 if (SemaBuiltinVAStartARM(TheCall))
498 return ExprError();
499 break;
500 default:
501 if (SemaBuiltinVAStart(TheCall))
502 return ExprError();
503 break;
504 }
505 break;
506 }
Chris Lattner2da14fb2007-12-20 00:26:33 +0000507 case Builtin::BI__builtin_isgreater:
508 case Builtin::BI__builtin_isgreaterequal:
509 case Builtin::BI__builtin_isless:
510 case Builtin::BI__builtin_islessequal:
511 case Builtin::BI__builtin_islessgreater:
512 case Builtin::BI__builtin_isunordered:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000513 if (SemaBuiltinUnorderedCompare(TheCall))
514 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000515 break;
Benjamin Kramer634fc102010-02-15 22:42:31 +0000516 case Builtin::BI__builtin_fpclassify:
517 if (SemaBuiltinFPClassification(TheCall, 6))
518 return ExprError();
519 break;
Eli Friedman7e4faac2009-08-31 20:06:00 +0000520 case Builtin::BI__builtin_isfinite:
521 case Builtin::BI__builtin_isinf:
522 case Builtin::BI__builtin_isinf_sign:
523 case Builtin::BI__builtin_isnan:
524 case Builtin::BI__builtin_isnormal:
Benjamin Kramer64aae502010-02-16 10:07:31 +0000525 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman7e4faac2009-08-31 20:06:00 +0000526 return ExprError();
527 break;
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000528 case Builtin::BI__builtin_shufflevector:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000529 return SemaBuiltinShuffleVector(TheCall);
530 // TheCall will be freed by the smart pointer here, but that's fine, since
531 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbarb7257262008-07-21 22:59:13 +0000532 case Builtin::BI__builtin_prefetch:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000533 if (SemaBuiltinPrefetch(TheCall))
534 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000535 break;
Hal Finkelf0417332014-07-17 14:25:55 +0000536 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +0000537 case Builtin::BI__builtin_assume:
Hal Finkelf0417332014-07-17 14:25:55 +0000538 if (SemaBuiltinAssume(TheCall))
539 return ExprError();
540 break;
Hal Finkelbcc06082014-09-07 22:58:14 +0000541 case Builtin::BI__builtin_assume_aligned:
542 if (SemaBuiltinAssumeAligned(TheCall))
543 return ExprError();
544 break;
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000545 case Builtin::BI__builtin_object_size:
Richard Sandiford28940af2014-04-16 08:47:51 +0000546 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000547 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000548 break;
Eli Friedmaneed8ad22009-05-03 04:46:36 +0000549 case Builtin::BI__builtin_longjmp:
550 if (SemaBuiltinLongjmp(TheCall))
551 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000552 break;
Joerg Sonnenberger27173282015-03-11 23:46:32 +0000553 case Builtin::BI__builtin_setjmp:
554 if (SemaBuiltinSetjmp(TheCall))
555 return ExprError();
556 break;
David Majnemerc403a1c2015-03-20 17:03:35 +0000557 case Builtin::BI_setjmp:
558 case Builtin::BI_setjmpex:
559 if (checkArgCount(*this, TheCall, 1))
560 return true;
561 break;
John McCallbebede42011-02-26 05:39:39 +0000562
563 case Builtin::BI__builtin_classify_type:
564 if (checkArgCount(*this, TheCall, 1)) return true;
565 TheCall->setType(Context.IntTy);
566 break;
Chris Lattner17c0eac2010-10-12 17:47:42 +0000567 case Builtin::BI__builtin_constant_p:
John McCallbebede42011-02-26 05:39:39 +0000568 if (checkArgCount(*this, TheCall, 1)) return true;
569 TheCall->setType(Context.IntTy);
Chris Lattner17c0eac2010-10-12 17:47:42 +0000570 break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000571 case Builtin::BI__sync_fetch_and_add:
Douglas Gregor73722482011-11-28 16:30:08 +0000572 case Builtin::BI__sync_fetch_and_add_1:
573 case Builtin::BI__sync_fetch_and_add_2:
574 case Builtin::BI__sync_fetch_and_add_4:
575 case Builtin::BI__sync_fetch_and_add_8:
576 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000577 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregor73722482011-11-28 16:30:08 +0000578 case Builtin::BI__sync_fetch_and_sub_1:
579 case Builtin::BI__sync_fetch_and_sub_2:
580 case Builtin::BI__sync_fetch_and_sub_4:
581 case Builtin::BI__sync_fetch_and_sub_8:
582 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000583 case Builtin::BI__sync_fetch_and_or:
Douglas Gregor73722482011-11-28 16:30:08 +0000584 case Builtin::BI__sync_fetch_and_or_1:
585 case Builtin::BI__sync_fetch_and_or_2:
586 case Builtin::BI__sync_fetch_and_or_4:
587 case Builtin::BI__sync_fetch_and_or_8:
588 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000589 case Builtin::BI__sync_fetch_and_and:
Douglas Gregor73722482011-11-28 16:30:08 +0000590 case Builtin::BI__sync_fetch_and_and_1:
591 case Builtin::BI__sync_fetch_and_and_2:
592 case Builtin::BI__sync_fetch_and_and_4:
593 case Builtin::BI__sync_fetch_and_and_8:
594 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000595 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregor73722482011-11-28 16:30:08 +0000596 case Builtin::BI__sync_fetch_and_xor_1:
597 case Builtin::BI__sync_fetch_and_xor_2:
598 case Builtin::BI__sync_fetch_and_xor_4:
599 case Builtin::BI__sync_fetch_and_xor_8:
600 case Builtin::BI__sync_fetch_and_xor_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000601 case Builtin::BI__sync_fetch_and_nand:
602 case Builtin::BI__sync_fetch_and_nand_1:
603 case Builtin::BI__sync_fetch_and_nand_2:
604 case Builtin::BI__sync_fetch_and_nand_4:
605 case Builtin::BI__sync_fetch_and_nand_8:
606 case Builtin::BI__sync_fetch_and_nand_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000607 case Builtin::BI__sync_add_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000608 case Builtin::BI__sync_add_and_fetch_1:
609 case Builtin::BI__sync_add_and_fetch_2:
610 case Builtin::BI__sync_add_and_fetch_4:
611 case Builtin::BI__sync_add_and_fetch_8:
612 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000613 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000614 case Builtin::BI__sync_sub_and_fetch_1:
615 case Builtin::BI__sync_sub_and_fetch_2:
616 case Builtin::BI__sync_sub_and_fetch_4:
617 case Builtin::BI__sync_sub_and_fetch_8:
618 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000619 case Builtin::BI__sync_and_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000620 case Builtin::BI__sync_and_and_fetch_1:
621 case Builtin::BI__sync_and_and_fetch_2:
622 case Builtin::BI__sync_and_and_fetch_4:
623 case Builtin::BI__sync_and_and_fetch_8:
624 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000625 case Builtin::BI__sync_or_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000626 case Builtin::BI__sync_or_and_fetch_1:
627 case Builtin::BI__sync_or_and_fetch_2:
628 case Builtin::BI__sync_or_and_fetch_4:
629 case Builtin::BI__sync_or_and_fetch_8:
630 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000631 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000632 case Builtin::BI__sync_xor_and_fetch_1:
633 case Builtin::BI__sync_xor_and_fetch_2:
634 case Builtin::BI__sync_xor_and_fetch_4:
635 case Builtin::BI__sync_xor_and_fetch_8:
636 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000637 case Builtin::BI__sync_nand_and_fetch:
638 case Builtin::BI__sync_nand_and_fetch_1:
639 case Builtin::BI__sync_nand_and_fetch_2:
640 case Builtin::BI__sync_nand_and_fetch_4:
641 case Builtin::BI__sync_nand_and_fetch_8:
642 case Builtin::BI__sync_nand_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000643 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000644 case Builtin::BI__sync_val_compare_and_swap_1:
645 case Builtin::BI__sync_val_compare_and_swap_2:
646 case Builtin::BI__sync_val_compare_and_swap_4:
647 case Builtin::BI__sync_val_compare_and_swap_8:
648 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000649 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000650 case Builtin::BI__sync_bool_compare_and_swap_1:
651 case Builtin::BI__sync_bool_compare_and_swap_2:
652 case Builtin::BI__sync_bool_compare_and_swap_4:
653 case Builtin::BI__sync_bool_compare_and_swap_8:
654 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000655 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +0000656 case Builtin::BI__sync_lock_test_and_set_1:
657 case Builtin::BI__sync_lock_test_and_set_2:
658 case Builtin::BI__sync_lock_test_and_set_4:
659 case Builtin::BI__sync_lock_test_and_set_8:
660 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000661 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +0000662 case Builtin::BI__sync_lock_release_1:
663 case Builtin::BI__sync_lock_release_2:
664 case Builtin::BI__sync_lock_release_4:
665 case Builtin::BI__sync_lock_release_8:
666 case Builtin::BI__sync_lock_release_16:
Chris Lattner9cb59fa2011-04-09 03:57:26 +0000667 case Builtin::BI__sync_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000668 case Builtin::BI__sync_swap_1:
669 case Builtin::BI__sync_swap_2:
670 case Builtin::BI__sync_swap_4:
671 case Builtin::BI__sync_swap_8:
672 case Builtin::BI__sync_swap_16:
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000673 return SemaBuiltinAtomicOverloaded(TheCallResult);
Michael Zolotukhin84df1232015-09-08 23:52:33 +0000674 case Builtin::BI__builtin_nontemporal_load:
675 case Builtin::BI__builtin_nontemporal_store:
676 return SemaBuiltinNontemporalOverloaded(TheCallResult);
Richard Smithfeea8832012-04-12 05:08:17 +0000677#define BUILTIN(ID, TYPE, ATTRS)
678#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
679 case Builtin::BI##ID: \
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000680 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithfeea8832012-04-12 05:08:17 +0000681#include "clang/Basic/Builtins.def"
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000682 case Builtin::BI__builtin_annotation:
Julien Lerouge4a5b4442012-04-28 17:39:16 +0000683 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000684 return ExprError();
685 break;
Richard Smith6cbd65d2013-07-11 02:27:57 +0000686 case Builtin::BI__builtin_addressof:
687 if (SemaBuiltinAddressof(*this, TheCall))
688 return ExprError();
689 break;
John McCall03107a42015-10-29 20:48:01 +0000690 case Builtin::BI__builtin_add_overflow:
691 case Builtin::BI__builtin_sub_overflow:
692 case Builtin::BI__builtin_mul_overflow:
Craig Toppera86e70d2015-11-07 06:16:14 +0000693 if (SemaBuiltinOverflow(*this, TheCall))
694 return ExprError();
695 break;
Richard Smith760520b2014-06-03 23:27:44 +0000696 case Builtin::BI__builtin_operator_new:
697 case Builtin::BI__builtin_operator_delete:
698 if (!getLangOpts().CPlusPlus) {
699 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
700 << (BuiltinID == Builtin::BI__builtin_operator_new
701 ? "__builtin_operator_new"
702 : "__builtin_operator_delete")
703 << "C++";
704 return ExprError();
705 }
706 // CodeGen assumes it can find the global new and delete to call,
707 // so ensure that they are declared.
708 DeclareGlobalNewDelete();
709 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000710
711 // check secure string manipulation functions where overflows
712 // are detectable at compile time
713 case Builtin::BI__builtin___memcpy_chk:
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000714 case Builtin::BI__builtin___memmove_chk:
715 case Builtin::BI__builtin___memset_chk:
716 case Builtin::BI__builtin___strlcat_chk:
717 case Builtin::BI__builtin___strlcpy_chk:
718 case Builtin::BI__builtin___strncat_chk:
719 case Builtin::BI__builtin___strncpy_chk:
720 case Builtin::BI__builtin___stpncpy_chk:
721 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
722 break;
Steven Wu566c14e2014-09-24 04:37:33 +0000723 case Builtin::BI__builtin___memccpy_chk:
724 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
725 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000726 case Builtin::BI__builtin___snprintf_chk:
727 case Builtin::BI__builtin___vsnprintf_chk:
728 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
729 break;
Peter Collingbournef7706832014-12-12 23:41:25 +0000730 case Builtin::BI__builtin_call_with_static_chain:
731 if (SemaBuiltinCallWithStaticChain(*this, TheCall))
732 return ExprError();
733 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +0000734 case Builtin::BI__exception_code:
Eugene Zelenko1ced5092016-02-12 22:53:10 +0000735 case Builtin::BI_exception_code:
Reid Kleckner1d59f992015-01-22 01:36:17 +0000736 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
737 diag::err_seh___except_block))
738 return ExprError();
739 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +0000740 case Builtin::BI__exception_info:
Eugene Zelenko1ced5092016-02-12 22:53:10 +0000741 case Builtin::BI_exception_info:
Reid Kleckner1d59f992015-01-22 01:36:17 +0000742 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
743 diag::err_seh___except_filter))
744 return ExprError();
745 break;
David Majnemerba3e5ec2015-03-13 18:26:17 +0000746 case Builtin::BI__GetExceptionInfo:
747 if (checkArgCount(*this, TheCall, 1))
748 return ExprError();
749
750 if (CheckCXXThrowOperand(
751 TheCall->getLocStart(),
752 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
753 TheCall))
754 return ExprError();
755
756 TheCall->setType(Context.VoidPtrTy);
757 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000758 case Builtin::BIread_pipe:
759 case Builtin::BIwrite_pipe:
760 // Since those two functions are declared with var args, we need a semantic
761 // check for the argument.
762 if (SemaBuiltinRWPipe(*this, TheCall))
763 return ExprError();
764 break;
765 case Builtin::BIreserve_read_pipe:
766 case Builtin::BIreserve_write_pipe:
767 case Builtin::BIwork_group_reserve_read_pipe:
768 case Builtin::BIwork_group_reserve_write_pipe:
769 case Builtin::BIsub_group_reserve_read_pipe:
770 case Builtin::BIsub_group_reserve_write_pipe:
771 if (SemaBuiltinReserveRWPipe(*this, TheCall))
772 return ExprError();
773 // Since return type of reserve_read/write_pipe built-in function is
774 // reserve_id_t, which is not defined in the builtin def file , we used int
775 // as return type and need to override the return type of these functions.
776 TheCall->setType(Context.OCLReserveIDTy);
777 break;
778 case Builtin::BIcommit_read_pipe:
779 case Builtin::BIcommit_write_pipe:
780 case Builtin::BIwork_group_commit_read_pipe:
781 case Builtin::BIwork_group_commit_write_pipe:
782 case Builtin::BIsub_group_commit_read_pipe:
783 case Builtin::BIsub_group_commit_write_pipe:
784 if (SemaBuiltinCommitRWPipe(*this, TheCall))
785 return ExprError();
786 break;
787 case Builtin::BIget_pipe_num_packets:
788 case Builtin::BIget_pipe_max_packets:
789 if (SemaBuiltinPipePackets(*this, TheCall))
790 return ExprError();
791 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000792 }
Richard Smith760520b2014-06-03 23:27:44 +0000793
Nate Begeman4904e322010-06-08 02:47:44 +0000794 // Since the target specific builtins for each arch overlap, only check those
795 // of the arch we are compiling for.
Artem Belevich9674a642015-09-22 17:23:05 +0000796 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000797 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +0000798 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +0000799 case llvm::Triple::armeb:
Nate Begeman4904e322010-06-08 02:47:44 +0000800 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +0000801 case llvm::Triple::thumbeb:
Nate Begeman4904e322010-06-08 02:47:44 +0000802 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
803 return ExprError();
804 break;
Tim Northover25e8a672014-05-24 12:51:25 +0000805 case llvm::Triple::aarch64:
806 case llvm::Triple::aarch64_be:
Tim Northover573cbee2014-05-24 12:52:07 +0000807 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
Tim Northovera2ee4332014-03-29 15:09:45 +0000808 return ExprError();
809 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000810 case llvm::Triple::mips:
811 case llvm::Triple::mipsel:
812 case llvm::Triple::mips64:
813 case llvm::Triple::mips64el:
814 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
815 return ExprError();
816 break;
Ulrich Weigand3a610eb2015-04-01 12:54:25 +0000817 case llvm::Triple::systemz:
818 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
819 return ExprError();
820 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000821 case llvm::Triple::x86:
822 case llvm::Triple::x86_64:
823 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
824 return ExprError();
825 break;
Kit Bartone50adcb2015-03-30 19:40:59 +0000826 case llvm::Triple::ppc:
827 case llvm::Triple::ppc64:
828 case llvm::Triple::ppc64le:
829 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
830 return ExprError();
831 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000832 default:
833 break;
834 }
835 }
836
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000837 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +0000838}
839
Nate Begeman91e1fea2010-06-14 05:21:25 +0000840// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +0000841static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +0000842 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +0000843 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +0000844 switch (Type.getEltType()) {
845 case NeonTypeFlags::Int8:
846 case NeonTypeFlags::Poly8:
847 return shift ? 7 : (8 << IsQuad) - 1;
848 case NeonTypeFlags::Int16:
849 case NeonTypeFlags::Poly16:
850 return shift ? 15 : (4 << IsQuad) - 1;
851 case NeonTypeFlags::Int32:
852 return shift ? 31 : (2 << IsQuad) - 1;
853 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +0000854 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +0000855 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000856 case NeonTypeFlags::Poly128:
857 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +0000858 case NeonTypeFlags::Float16:
859 assert(!shift && "cannot shift float types!");
860 return (4 << IsQuad) - 1;
861 case NeonTypeFlags::Float32:
862 assert(!shift && "cannot shift float types!");
863 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000864 case NeonTypeFlags::Float64:
865 assert(!shift && "cannot shift float types!");
866 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000867 }
David Blaikie8a40f702012-01-17 06:56:22 +0000868 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +0000869}
870
Bob Wilsone4d77232011-11-08 05:04:11 +0000871/// getNeonEltType - Return the QualType corresponding to the elements of
872/// the vector type specified by the NeonTypeFlags. This is used to check
873/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +0000874static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Tim Northovera2ee4332014-03-29 15:09:45 +0000875 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilsone4d77232011-11-08 05:04:11 +0000876 switch (Flags.getEltType()) {
877 case NeonTypeFlags::Int8:
878 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
879 case NeonTypeFlags::Int16:
880 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
881 case NeonTypeFlags::Int32:
882 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
883 case NeonTypeFlags::Int64:
Tim Northovera2ee4332014-03-29 15:09:45 +0000884 if (IsInt64Long)
Kevin Qinad64f6d2014-02-24 02:45:03 +0000885 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
886 else
887 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
888 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000889 case NeonTypeFlags::Poly8:
Tim Northovera2ee4332014-03-29 15:09:45 +0000890 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000891 case NeonTypeFlags::Poly16:
Tim Northovera2ee4332014-03-29 15:09:45 +0000892 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qincaac85e2013-11-14 03:29:16 +0000893 case NeonTypeFlags::Poly64:
Kevin Qin78b86532015-05-14 08:18:05 +0000894 if (IsInt64Long)
895 return Context.UnsignedLongTy;
896 else
897 return Context.UnsignedLongLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000898 case NeonTypeFlags::Poly128:
899 break;
Bob Wilsone4d77232011-11-08 05:04:11 +0000900 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +0000901 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000902 case NeonTypeFlags::Float32:
903 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +0000904 case NeonTypeFlags::Float64:
905 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000906 }
David Blaikie8a40f702012-01-17 06:56:22 +0000907 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +0000908}
909
Tim Northover12670412014-02-19 10:37:05 +0000910bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +0000911 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +0000912 uint64_t mask = 0;
913 unsigned TV = 0;
914 int PtrArgNum = -1;
915 bool HasConstPtr = false;
916 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +0000917#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000918#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000919#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000920 }
921
922 // For NEON intrinsics which are overloaded on vector element type, validate
923 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +0000924 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000925 if (mask) {
926 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
927 return true;
928
929 TV = Result.getLimitedValue(64);
930 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
931 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Tim Northover12670412014-02-19 10:37:05 +0000932 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +0000933 }
934
935 if (PtrArgNum >= 0) {
936 // Check that pointer arguments have the specified type.
937 Expr *Arg = TheCall->getArg(PtrArgNum);
938 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
939 Arg = ICE->getSubExpr();
940 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
941 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +0000942
Tim Northovera2ee4332014-03-29 15:09:45 +0000943 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Tim Northover40956e62014-07-23 12:32:58 +0000944 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64;
Tim Northovera2ee4332014-03-29 15:09:45 +0000945 bool IsInt64Long =
946 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
947 QualType EltTy =
948 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northover2fe823a2013-08-01 09:23:19 +0000949 if (HasConstPtr)
950 EltTy = EltTy.withConst();
951 QualType LHSTy = Context.getPointerType(EltTy);
952 AssignConvertType ConvTy;
953 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
954 if (RHS.isInvalid())
955 return true;
956 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
957 RHS.get(), AA_Assigning))
958 return true;
959 }
960
961 // For NEON intrinsics which take an immediate value as part of the
962 // instruction, range check them here.
963 unsigned i = 0, l = 0, u = 0;
964 switch (BuiltinID) {
965 default:
966 return false;
Tim Northover12670412014-02-19 10:37:05 +0000967#define GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000968#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000969#undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000970 }
Tim Northover2fe823a2013-08-01 09:23:19 +0000971
Richard Sandiford28940af2014-04-16 08:47:51 +0000972 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northover2fe823a2013-08-01 09:23:19 +0000973}
974
Tim Northovera2ee4332014-03-29 15:09:45 +0000975bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
976 unsigned MaxWidth) {
Tim Northover6aacd492013-07-16 09:47:53 +0000977 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000978 BuiltinID == ARM::BI__builtin_arm_ldaex ||
Tim Northovera2ee4332014-03-29 15:09:45 +0000979 BuiltinID == ARM::BI__builtin_arm_strex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000980 BuiltinID == ARM::BI__builtin_arm_stlex ||
Tim Northover573cbee2014-05-24 12:52:07 +0000981 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000982 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
983 BuiltinID == AArch64::BI__builtin_arm_strex ||
984 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
Tim Northover6aacd492013-07-16 09:47:53 +0000985 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +0000986 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000987 BuiltinID == ARM::BI__builtin_arm_ldaex ||
988 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
989 BuiltinID == AArch64::BI__builtin_arm_ldaex;
Tim Northover6aacd492013-07-16 09:47:53 +0000990
991 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
992
993 // Ensure that we have the proper number of arguments.
994 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
995 return true;
996
997 // Inspect the pointer argument of the atomic builtin. This should always be
998 // a pointer type, whose element is an integral scalar or pointer type.
999 // Because it is a pointer type, we don't have to worry about any implicit
1000 // casts here.
1001 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1002 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1003 if (PointerArgRes.isInvalid())
1004 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001005 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001006
1007 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1008 if (!pointerType) {
1009 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1010 << PointerArg->getType() << PointerArg->getSourceRange();
1011 return true;
1012 }
1013
1014 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1015 // task is to insert the appropriate casts into the AST. First work out just
1016 // what the appropriate type is.
1017 QualType ValType = pointerType->getPointeeType();
1018 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1019 if (IsLdrex)
1020 AddrType.addConst();
1021
1022 // Issue a warning if the cast is dodgy.
1023 CastKind CastNeeded = CK_NoOp;
1024 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1025 CastNeeded = CK_BitCast;
1026 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
1027 << PointerArg->getType()
1028 << Context.getPointerType(AddrType)
1029 << AA_Passing << PointerArg->getSourceRange();
1030 }
1031
1032 // Finally, do the cast and replace the argument with the corrected version.
1033 AddrType = Context.getPointerType(AddrType);
1034 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1035 if (PointerArgRes.isInvalid())
1036 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001037 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001038
1039 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1040
1041 // In general, we allow ints, floats and pointers to be loaded and stored.
1042 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1043 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1044 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1045 << PointerArg->getType() << PointerArg->getSourceRange();
1046 return true;
1047 }
1048
1049 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +00001050 if (Context.getTypeSize(ValType) > MaxWidth) {
1051 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover6aacd492013-07-16 09:47:53 +00001052 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
1053 << PointerArg->getType() << PointerArg->getSourceRange();
1054 return true;
1055 }
1056
1057 switch (ValType.getObjCLifetime()) {
1058 case Qualifiers::OCL_None:
1059 case Qualifiers::OCL_ExplicitNone:
1060 // okay
1061 break;
1062
1063 case Qualifiers::OCL_Weak:
1064 case Qualifiers::OCL_Strong:
1065 case Qualifiers::OCL_Autoreleasing:
1066 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1067 << ValType << PointerArg->getSourceRange();
1068 return true;
1069 }
1070
Tim Northover6aacd492013-07-16 09:47:53 +00001071 if (IsLdrex) {
1072 TheCall->setType(ValType);
1073 return false;
1074 }
1075
1076 // Initialize the argument to be stored.
1077 ExprResult ValArg = TheCall->getArg(0);
1078 InitializedEntity Entity = InitializedEntity::InitializeParameter(
1079 Context, ValType, /*consume*/ false);
1080 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1081 if (ValArg.isInvalid())
1082 return true;
Tim Northover6aacd492013-07-16 09:47:53 +00001083 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +00001084
1085 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1086 // but the custom checker bypasses all default analysis.
1087 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +00001088 return false;
1089}
1090
Nate Begeman4904e322010-06-08 02:47:44 +00001091bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman55483092010-06-09 01:10:23 +00001092 llvm::APSInt Result;
1093
Tim Northover6aacd492013-07-16 09:47:53 +00001094 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001095 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1096 BuiltinID == ARM::BI__builtin_arm_strex ||
1097 BuiltinID == ARM::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001098 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +00001099 }
1100
Yi Kong26d104a2014-08-13 19:18:14 +00001101 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1102 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1103 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1104 }
1105
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001106 if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1107 BuiltinID == ARM::BI__builtin_arm_wsr64)
1108 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1109
1110 if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1111 BuiltinID == ARM::BI__builtin_arm_rsrp ||
1112 BuiltinID == ARM::BI__builtin_arm_wsr ||
1113 BuiltinID == ARM::BI__builtin_arm_wsrp)
1114 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1115
Tim Northover12670412014-02-19 10:37:05 +00001116 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1117 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +00001118
Yi Kong4efadfb2014-07-03 16:01:25 +00001119 // For intrinsics which take an immediate value as part of the instruction,
1120 // range check them here.
Nate Begeman91e1fea2010-06-14 05:21:25 +00001121 unsigned i = 0, l = 0, u = 0;
Nate Begemand773fe62010-06-13 04:47:52 +00001122 switch (BuiltinID) {
1123 default: return false;
Nate Begeman1194bd22010-07-29 22:48:34 +00001124 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
1125 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begemanf568b072010-08-03 21:32:34 +00001126 case ARM::BI__builtin_arm_vcvtr_f:
1127 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Weiming Zhao87bb4922013-11-12 21:42:50 +00001128 case ARM::BI__builtin_arm_dmb:
Yi Kong4efadfb2014-07-03 16:01:25 +00001129 case ARM::BI__builtin_arm_dsb:
Yi Kong1d268af2014-08-26 12:48:06 +00001130 case ARM::BI__builtin_arm_isb:
1131 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00001132 }
Nate Begemand773fe62010-06-13 04:47:52 +00001133
Nate Begemanf568b072010-08-03 21:32:34 +00001134 // FIXME: VFP Intrinsics should error if VFP not present.
Richard Sandiford28940af2014-04-16 08:47:51 +00001135 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001136}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001137
Tim Northover573cbee2014-05-24 12:52:07 +00001138bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +00001139 CallExpr *TheCall) {
1140 llvm::APSInt Result;
1141
Tim Northover573cbee2014-05-24 12:52:07 +00001142 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001143 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1144 BuiltinID == AArch64::BI__builtin_arm_strex ||
1145 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001146 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1147 }
1148
Yi Konga5548432014-08-13 19:18:20 +00001149 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1150 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1151 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1152 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1153 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1154 }
1155
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001156 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1157 BuiltinID == AArch64::BI__builtin_arm_wsr64)
Tim Northover54e50002016-04-13 17:08:55 +00001158 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001159
1160 if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1161 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1162 BuiltinID == AArch64::BI__builtin_arm_wsr ||
1163 BuiltinID == AArch64::BI__builtin_arm_wsrp)
1164 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1165
Tim Northovera2ee4332014-03-29 15:09:45 +00001166 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1167 return true;
1168
Yi Kong19a29ac2014-07-17 10:52:06 +00001169 // For intrinsics which take an immediate value as part of the instruction,
1170 // range check them here.
1171 unsigned i = 0, l = 0, u = 0;
1172 switch (BuiltinID) {
1173 default: return false;
1174 case AArch64::BI__builtin_arm_dmb:
1175 case AArch64::BI__builtin_arm_dsb:
1176 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1177 }
1178
Yi Kong19a29ac2014-07-17 10:52:06 +00001179 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northovera2ee4332014-03-29 15:09:45 +00001180}
1181
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001182bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1183 unsigned i = 0, l = 0, u = 0;
1184 switch (BuiltinID) {
1185 default: return false;
1186 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
1187 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +00001188 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
1189 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
1190 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
1191 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
1192 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00001193 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001194
Richard Sandiford28940af2014-04-16 08:47:51 +00001195 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001196}
1197
Kit Bartone50adcb2015-03-30 19:40:59 +00001198bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1199 unsigned i = 0, l = 0, u = 0;
Nemanja Ivanovic239eec72015-04-09 23:58:16 +00001200 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
1201 BuiltinID == PPC::BI__builtin_divdeu ||
1202 BuiltinID == PPC::BI__builtin_bpermd;
1203 bool IsTarget64Bit = Context.getTargetInfo()
1204 .getTypeWidth(Context
1205 .getTargetInfo()
1206 .getIntPtrType()) == 64;
1207 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
1208 BuiltinID == PPC::BI__builtin_divweu ||
1209 BuiltinID == PPC::BI__builtin_divde ||
1210 BuiltinID == PPC::BI__builtin_divdeu;
1211
1212 if (Is64BitBltin && !IsTarget64Bit)
1213 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
1214 << TheCall->getSourceRange();
1215
1216 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
1217 (BuiltinID == PPC::BI__builtin_bpermd &&
1218 !Context.getTargetInfo().hasFeature("bpermd")))
1219 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
1220 << TheCall->getSourceRange();
1221
Kit Bartone50adcb2015-03-30 19:40:59 +00001222 switch (BuiltinID) {
1223 default: return false;
1224 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
1225 case PPC::BI__builtin_altivec_crypto_vshasigmad:
1226 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1227 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1228 case PPC::BI__builtin_tbegin:
1229 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
1230 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
1231 case PPC::BI__builtin_tabortwc:
1232 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
1233 case PPC::BI__builtin_tabortwci:
1234 case PPC::BI__builtin_tabortdci:
1235 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
1236 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
1237 }
1238 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1239}
1240
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001241bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
1242 CallExpr *TheCall) {
1243 if (BuiltinID == SystemZ::BI__builtin_tabort) {
1244 Expr *Arg = TheCall->getArg(0);
1245 llvm::APSInt AbortCode(32);
1246 if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
1247 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
1248 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
1249 << Arg->getSourceRange();
1250 }
1251
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001252 // For intrinsics which take an immediate value as part of the instruction,
1253 // range check them here.
1254 unsigned i = 0, l = 0, u = 0;
1255 switch (BuiltinID) {
1256 default: return false;
1257 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
1258 case SystemZ::BI__builtin_s390_verimb:
1259 case SystemZ::BI__builtin_s390_verimh:
1260 case SystemZ::BI__builtin_s390_verimf:
1261 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
1262 case SystemZ::BI__builtin_s390_vfaeb:
1263 case SystemZ::BI__builtin_s390_vfaeh:
1264 case SystemZ::BI__builtin_s390_vfaef:
1265 case SystemZ::BI__builtin_s390_vfaebs:
1266 case SystemZ::BI__builtin_s390_vfaehs:
1267 case SystemZ::BI__builtin_s390_vfaefs:
1268 case SystemZ::BI__builtin_s390_vfaezb:
1269 case SystemZ::BI__builtin_s390_vfaezh:
1270 case SystemZ::BI__builtin_s390_vfaezf:
1271 case SystemZ::BI__builtin_s390_vfaezbs:
1272 case SystemZ::BI__builtin_s390_vfaezhs:
1273 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
1274 case SystemZ::BI__builtin_s390_vfidb:
1275 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1276 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1277 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
1278 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
1279 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
1280 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
1281 case SystemZ::BI__builtin_s390_vstrcb:
1282 case SystemZ::BI__builtin_s390_vstrch:
1283 case SystemZ::BI__builtin_s390_vstrcf:
1284 case SystemZ::BI__builtin_s390_vstrczb:
1285 case SystemZ::BI__builtin_s390_vstrczh:
1286 case SystemZ::BI__builtin_s390_vstrczf:
1287 case SystemZ::BI__builtin_s390_vstrcbs:
1288 case SystemZ::BI__builtin_s390_vstrchs:
1289 case SystemZ::BI__builtin_s390_vstrcfs:
1290 case SystemZ::BI__builtin_s390_vstrczbs:
1291 case SystemZ::BI__builtin_s390_vstrczhs:
1292 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
1293 }
1294 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001295}
1296
Craig Topper5ba2c502015-11-07 08:08:31 +00001297/// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
1298/// This checks that the target supports __builtin_cpu_supports and
1299/// that the string argument is constant and valid.
1300static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
1301 Expr *Arg = TheCall->getArg(0);
1302
1303 // Check if the argument is a string literal.
1304 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1305 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1306 << Arg->getSourceRange();
1307
1308 // Check the contents of the string.
1309 StringRef Feature =
1310 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1311 if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
1312 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
1313 << Arg->getSourceRange();
1314 return false;
1315}
1316
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001317bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Craig Topperdd84ec52014-12-27 07:00:08 +00001318 unsigned i = 0, l = 0, u = 0;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001319 switch (BuiltinID) {
Richard Trieucc3949d2016-02-18 22:34:54 +00001320 default:
1321 return false;
Eric Christopherd9832702015-06-29 21:00:05 +00001322 case X86::BI__builtin_cpu_supports:
Craig Topper5ba2c502015-11-07 08:08:31 +00001323 return SemaBuiltinCpuSupports(*this, TheCall);
Charles Davisc7d5c942015-09-17 20:55:33 +00001324 case X86::BI__builtin_ms_va_start:
1325 return SemaBuiltinMSVAStart(TheCall);
Richard Trieucc3949d2016-02-18 22:34:54 +00001326 case X86::BI_mm_prefetch:
1327 i = 1;
1328 l = 0;
1329 u = 3;
1330 break;
1331 case X86::BI__builtin_ia32_sha1rnds4:
1332 i = 2;
1333 l = 0;
1334 u = 3;
1335 break;
Craig Topper1a8b0472015-01-31 08:57:52 +00001336 case X86::BI__builtin_ia32_vpermil2pd:
1337 case X86::BI__builtin_ia32_vpermil2pd256:
1338 case X86::BI__builtin_ia32_vpermil2ps:
Richard Trieucc3949d2016-02-18 22:34:54 +00001339 case X86::BI__builtin_ia32_vpermil2ps256:
1340 i = 3;
1341 l = 0;
1342 u = 3;
1343 break;
Craig Topper95b0d732015-01-25 23:30:05 +00001344 case X86::BI__builtin_ia32_cmpb128_mask:
1345 case X86::BI__builtin_ia32_cmpw128_mask:
1346 case X86::BI__builtin_ia32_cmpd128_mask:
1347 case X86::BI__builtin_ia32_cmpq128_mask:
1348 case X86::BI__builtin_ia32_cmpb256_mask:
1349 case X86::BI__builtin_ia32_cmpw256_mask:
1350 case X86::BI__builtin_ia32_cmpd256_mask:
1351 case X86::BI__builtin_ia32_cmpq256_mask:
1352 case X86::BI__builtin_ia32_cmpb512_mask:
1353 case X86::BI__builtin_ia32_cmpw512_mask:
1354 case X86::BI__builtin_ia32_cmpd512_mask:
1355 case X86::BI__builtin_ia32_cmpq512_mask:
1356 case X86::BI__builtin_ia32_ucmpb128_mask:
1357 case X86::BI__builtin_ia32_ucmpw128_mask:
1358 case X86::BI__builtin_ia32_ucmpd128_mask:
1359 case X86::BI__builtin_ia32_ucmpq128_mask:
1360 case X86::BI__builtin_ia32_ucmpb256_mask:
1361 case X86::BI__builtin_ia32_ucmpw256_mask:
1362 case X86::BI__builtin_ia32_ucmpd256_mask:
1363 case X86::BI__builtin_ia32_ucmpq256_mask:
1364 case X86::BI__builtin_ia32_ucmpb512_mask:
1365 case X86::BI__builtin_ia32_ucmpw512_mask:
1366 case X86::BI__builtin_ia32_ucmpd512_mask:
Richard Trieucc3949d2016-02-18 22:34:54 +00001367 case X86::BI__builtin_ia32_ucmpq512_mask:
1368 i = 2;
1369 l = 0;
1370 u = 7;
1371 break;
Craig Topper16015252015-01-31 06:31:23 +00001372 case X86::BI__builtin_ia32_roundps:
1373 case X86::BI__builtin_ia32_roundpd:
1374 case X86::BI__builtin_ia32_roundps256:
Richard Trieucc3949d2016-02-18 22:34:54 +00001375 case X86::BI__builtin_ia32_roundpd256:
1376 i = 1;
1377 l = 0;
1378 u = 15;
1379 break;
Craig Topper16015252015-01-31 06:31:23 +00001380 case X86::BI__builtin_ia32_roundss:
Richard Trieucc3949d2016-02-18 22:34:54 +00001381 case X86::BI__builtin_ia32_roundsd:
1382 i = 2;
1383 l = 0;
1384 u = 15;
1385 break;
Craig Topper16015252015-01-31 06:31:23 +00001386 case X86::BI__builtin_ia32_cmpps:
1387 case X86::BI__builtin_ia32_cmpss:
1388 case X86::BI__builtin_ia32_cmppd:
1389 case X86::BI__builtin_ia32_cmpsd:
1390 case X86::BI__builtin_ia32_cmpps256:
1391 case X86::BI__builtin_ia32_cmppd256:
1392 case X86::BI__builtin_ia32_cmpps512_mask:
Richard Trieucc3949d2016-02-18 22:34:54 +00001393 case X86::BI__builtin_ia32_cmppd512_mask:
1394 i = 2;
1395 l = 0;
1396 u = 31;
1397 break;
Craig Topper8dd7d0d2015-02-13 06:04:48 +00001398 case X86::BI__builtin_ia32_vpcomub:
1399 case X86::BI__builtin_ia32_vpcomuw:
1400 case X86::BI__builtin_ia32_vpcomud:
1401 case X86::BI__builtin_ia32_vpcomuq:
1402 case X86::BI__builtin_ia32_vpcomb:
1403 case X86::BI__builtin_ia32_vpcomw:
1404 case X86::BI__builtin_ia32_vpcomd:
Richard Trieucc3949d2016-02-18 22:34:54 +00001405 case X86::BI__builtin_ia32_vpcomq:
1406 i = 2;
1407 l = 0;
1408 u = 7;
1409 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001410 }
Craig Topperdd84ec52014-12-27 07:00:08 +00001411 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001412}
1413
Richard Smith55ce3522012-06-25 20:30:08 +00001414/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
1415/// parameter with the FormatAttr's correct format_idx and firstDataArg.
1416/// Returns true when the format fits the function and the FormatStringInfo has
1417/// been populated.
1418bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
1419 FormatStringInfo *FSI) {
1420 FSI->HasVAListArg = Format->getFirstArg() == 0;
1421 FSI->FormatIdx = Format->getFormatIdx() - 1;
1422 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001423
Richard Smith55ce3522012-06-25 20:30:08 +00001424 // The way the format attribute works in GCC, the implicit this argument
1425 // of member functions is counted. However, it doesn't appear in our own
1426 // lists, so decrement format_idx in that case.
1427 if (IsCXXMember) {
1428 if(FSI->FormatIdx == 0)
1429 return false;
1430 --FSI->FormatIdx;
1431 if (FSI->FirstDataArg != 0)
1432 --FSI->FirstDataArg;
1433 }
1434 return true;
1435}
Mike Stump11289f42009-09-09 15:08:12 +00001436
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001437/// Checks if a the given expression evaluates to null.
1438///
1439/// \brief Returns true if the value evaluates to null.
George Burgess IV850269a2015-12-08 22:02:00 +00001440static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00001441 // If the expression has non-null type, it doesn't evaluate to null.
1442 if (auto nullability
1443 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
1444 if (*nullability == NullabilityKind::NonNull)
1445 return false;
1446 }
1447
Ted Kremeneka146db32014-01-17 06:24:47 +00001448 // As a special case, transparent unions initialized with zero are
1449 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001450 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +00001451 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
1452 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001453 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +00001454 if (const InitListExpr *ILE =
1455 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001456 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +00001457 }
1458
1459 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +00001460 return (!Expr->isValueDependent() &&
1461 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
1462 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001463}
1464
1465static void CheckNonNullArgument(Sema &S,
1466 const Expr *ArgExpr,
1467 SourceLocation CallSiteLoc) {
1468 if (CheckNonNullExpr(S, ArgExpr))
Eric Fiselier18677d52015-10-09 00:17:57 +00001469 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
1470 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
Ted Kremeneka146db32014-01-17 06:24:47 +00001471}
1472
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001473bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
1474 FormatStringInfo FSI;
1475 if ((GetFormatStringType(Format) == FST_NSString) &&
1476 getFormatStringInfo(Format, false, &FSI)) {
1477 Idx = FSI.FormatIdx;
1478 return true;
1479 }
1480 return false;
1481}
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001482/// \brief Diagnose use of %s directive in an NSString which is being passed
1483/// as formatting string to formatting method.
1484static void
1485DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
1486 const NamedDecl *FDecl,
1487 Expr **Args,
1488 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001489 unsigned Idx = 0;
1490 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001491 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
1492 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001493 Idx = 2;
1494 Format = true;
1495 }
1496 else
1497 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
1498 if (S.GetFormatNSStringIdx(I, Idx)) {
1499 Format = true;
1500 break;
1501 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001502 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001503 if (!Format || NumArgs <= Idx)
1504 return;
1505 const Expr *FormatExpr = Args[Idx];
1506 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
1507 FormatExpr = CSCE->getSubExpr();
1508 const StringLiteral *FormatString;
1509 if (const ObjCStringLiteral *OSL =
1510 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
1511 FormatString = OSL->getString();
1512 else
1513 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
1514 if (!FormatString)
1515 return;
1516 if (S.FormatStringHasSArg(FormatString)) {
1517 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
1518 << "%s" << 1 << 1;
1519 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
1520 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001521 }
1522}
1523
Douglas Gregorb4866e82015-06-19 18:13:19 +00001524/// Determine whether the given type has a non-null nullability annotation.
1525static bool isNonNullType(ASTContext &ctx, QualType type) {
1526 if (auto nullability = type->getNullability(ctx))
1527 return *nullability == NullabilityKind::NonNull;
1528
1529 return false;
1530}
1531
Ted Kremenek2bc73332014-01-17 06:24:43 +00001532static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00001533 const NamedDecl *FDecl,
Douglas Gregorb4866e82015-06-19 18:13:19 +00001534 const FunctionProtoType *Proto,
Richard Smith588bd9b2014-08-27 04:59:42 +00001535 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00001536 SourceLocation CallSiteLoc) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00001537 assert((FDecl || Proto) && "Need a function declaration or prototype");
1538
Ted Kremenek9aedc152014-01-17 06:24:56 +00001539 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00001540 llvm::SmallBitVector NonNullArgs;
Douglas Gregorb4866e82015-06-19 18:13:19 +00001541 if (FDecl) {
1542 // Handle the nonnull attribute on the function/method declaration itself.
1543 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
1544 if (!NonNull->args_size()) {
1545 // Easy case: all pointer arguments are nonnull.
1546 for (const auto *Arg : Args)
1547 if (S.isValidPointerAttrType(Arg->getType()))
1548 CheckNonNullArgument(S, Arg, CallSiteLoc);
1549 return;
1550 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001551
Douglas Gregorb4866e82015-06-19 18:13:19 +00001552 for (unsigned Val : NonNull->args()) {
1553 if (Val >= Args.size())
1554 continue;
1555 if (NonNullArgs.empty())
1556 NonNullArgs.resize(Args.size());
1557 NonNullArgs.set(Val);
1558 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001559 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00001560 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00001561
Douglas Gregorb4866e82015-06-19 18:13:19 +00001562 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
1563 // Handle the nonnull attribute on the parameters of the
1564 // function/method.
1565 ArrayRef<ParmVarDecl*> parms;
1566 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
1567 parms = FD->parameters();
1568 else
1569 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
1570
1571 unsigned ParamIndex = 0;
1572 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
1573 I != E; ++I, ++ParamIndex) {
1574 const ParmVarDecl *PVD = *I;
1575 if (PVD->hasAttr<NonNullAttr>() ||
1576 isNonNullType(S.Context, PVD->getType())) {
1577 if (NonNullArgs.empty())
1578 NonNullArgs.resize(Args.size());
Ted Kremenek9aedc152014-01-17 06:24:56 +00001579
Douglas Gregorb4866e82015-06-19 18:13:19 +00001580 NonNullArgs.set(ParamIndex);
1581 }
1582 }
1583 } else {
1584 // If we have a non-function, non-method declaration but no
1585 // function prototype, try to dig out the function prototype.
1586 if (!Proto) {
1587 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
1588 QualType type = VD->getType().getNonReferenceType();
1589 if (auto pointerType = type->getAs<PointerType>())
1590 type = pointerType->getPointeeType();
1591 else if (auto blockType = type->getAs<BlockPointerType>())
1592 type = blockType->getPointeeType();
1593 // FIXME: data member pointers?
1594
1595 // Dig out the function prototype, if there is one.
1596 Proto = type->getAs<FunctionProtoType>();
1597 }
1598 }
1599
1600 // Fill in non-null argument information from the nullability
1601 // information on the parameter types (if we have them).
1602 if (Proto) {
1603 unsigned Index = 0;
1604 for (auto paramType : Proto->getParamTypes()) {
1605 if (isNonNullType(S.Context, paramType)) {
1606 if (NonNullArgs.empty())
1607 NonNullArgs.resize(Args.size());
1608
1609 NonNullArgs.set(Index);
1610 }
1611
1612 ++Index;
1613 }
1614 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00001615 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001616
Douglas Gregorb4866e82015-06-19 18:13:19 +00001617 // Check for non-null arguments.
1618 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
1619 ArgIndex != ArgIndexEnd; ++ArgIndex) {
Richard Smith588bd9b2014-08-27 04:59:42 +00001620 if (NonNullArgs[ArgIndex])
1621 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00001622 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00001623}
1624
Richard Smith55ce3522012-06-25 20:30:08 +00001625/// Handles the checks for format strings, non-POD arguments to vararg
1626/// functions, and NULL arguments passed to non-NULL parameters.
Douglas Gregorb4866e82015-06-19 18:13:19 +00001627void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
1628 ArrayRef<const Expr *> Args, bool IsMemberFunction,
Alp Toker9cacbab2014-01-20 20:26:09 +00001629 SourceLocation Loc, SourceRange Range,
Richard Smith55ce3522012-06-25 20:30:08 +00001630 VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00001631 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00001632 if (CurContext->isDependentContext())
1633 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001634
Ted Kremenekb8176da2010-09-09 04:33:05 +00001635 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00001636 llvm::SmallBitVector CheckedVarArgs;
1637 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001638 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00001639 // Only create vector if there are format attributes.
1640 CheckedVarArgs.resize(Args.size());
1641
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001642 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00001643 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00001644 }
Richard Smithd7293d72013-08-05 18:49:43 +00001645 }
Richard Smith55ce3522012-06-25 20:30:08 +00001646
1647 // Refuse POD arguments that weren't caught by the format string
1648 // checks above.
Richard Smithd7293d72013-08-05 18:49:43 +00001649 if (CallType != VariadicDoesNotApply) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00001650 unsigned NumParams = Proto ? Proto->getNumParams()
1651 : FDecl && isa<FunctionDecl>(FDecl)
1652 ? cast<FunctionDecl>(FDecl)->getNumParams()
1653 : FDecl && isa<ObjCMethodDecl>(FDecl)
1654 ? cast<ObjCMethodDecl>(FDecl)->param_size()
1655 : 0;
1656
Alp Toker9cacbab2014-01-20 20:26:09 +00001657 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00001658 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00001659 if (const Expr *Arg = Args[ArgIdx]) {
1660 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
1661 checkVariadicArgument(Arg, CallType);
1662 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00001663 }
Richard Smithd7293d72013-08-05 18:49:43 +00001664 }
Mike Stump11289f42009-09-09 15:08:12 +00001665
Douglas Gregorb4866e82015-06-19 18:13:19 +00001666 if (FDecl || Proto) {
1667 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001668
Richard Trieu41bc0992013-06-22 00:20:41 +00001669 // Type safety checking.
Douglas Gregorb4866e82015-06-19 18:13:19 +00001670 if (FDecl) {
1671 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
1672 CheckArgumentWithTypeTag(I, Args.data());
1673 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001674 }
Richard Smith55ce3522012-06-25 20:30:08 +00001675}
1676
1677/// CheckConstructorCall - Check a constructor call for correctness and safety
1678/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00001679void Sema::CheckConstructorCall(FunctionDecl *FDecl,
1680 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00001681 const FunctionProtoType *Proto,
1682 SourceLocation Loc) {
1683 VariadicCallType CallType =
1684 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Douglas Gregorb4866e82015-06-19 18:13:19 +00001685 checkCall(FDecl, Proto, Args, /*IsMemberFunction=*/true, Loc, SourceRange(),
1686 CallType);
Richard Smith55ce3522012-06-25 20:30:08 +00001687}
1688
1689/// CheckFunctionCall - Check a direct function call for various correctness
1690/// and safety properties not strictly enforced by the C type system.
1691bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
1692 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00001693 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
1694 isa<CXXMethodDecl>(FDecl);
1695 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
1696 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00001697 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
1698 TheCall->getCallee());
Eli Friedman726d11c2012-10-11 00:30:58 +00001699 Expr** Args = TheCall->getArgs();
1700 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmanadf42182012-10-11 00:34:15 +00001701 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00001702 // If this is a call to a member operator, hide the first argument
1703 // from checkCall.
1704 // FIXME: Our choice of AST representation here is less than ideal.
1705 ++Args;
1706 --NumArgs;
1707 }
Douglas Gregorb4866e82015-06-19 18:13:19 +00001708 checkCall(FDecl, Proto, llvm::makeArrayRef(Args, NumArgs),
Richard Smith55ce3522012-06-25 20:30:08 +00001709 IsMemberFunction, TheCall->getRParenLoc(),
1710 TheCall->getCallee()->getSourceRange(), CallType);
1711
1712 IdentifierInfo *FnInfo = FDecl->getIdentifier();
1713 // None of the checks below are needed for functions that don't have
1714 // simple names (e.g., C++ conversion functions).
1715 if (!FnInfo)
1716 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001717
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00001718 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001719 if (getLangOpts().ObjC1)
1720 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00001721
Anna Zaks22122702012-01-17 00:37:07 +00001722 unsigned CMId = FDecl->getMemoryFunctionKind();
1723 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00001724 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00001725
Anna Zaks201d4892012-01-13 21:52:01 +00001726 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00001727 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00001728 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00001729 else if (CMId == Builtin::BIstrncat)
1730 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00001731 else
Anna Zaks22122702012-01-17 00:37:07 +00001732 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00001733
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001734 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00001735}
1736
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001737bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00001738 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00001739 VariadicCallType CallType =
1740 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001741
Douglas Gregorb4866e82015-06-19 18:13:19 +00001742 checkCall(Method, nullptr, Args,
1743 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
1744 CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001745
1746 return false;
1747}
1748
Richard Trieu664c4c62013-06-20 21:03:13 +00001749bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
1750 const FunctionProtoType *Proto) {
Aaron Ballmanb673c652015-04-23 16:14:19 +00001751 QualType Ty;
1752 if (const auto *V = dyn_cast<VarDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00001753 Ty = V->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00001754 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00001755 Ty = F->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00001756 else
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001757 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001758
Douglas Gregorb4866e82015-06-19 18:13:19 +00001759 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
1760 !Ty->isFunctionProtoType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001761 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001762
Richard Trieu664c4c62013-06-20 21:03:13 +00001763 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00001764 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00001765 CallType = VariadicDoesNotApply;
1766 } else if (Ty->isBlockPointerType()) {
1767 CallType = VariadicBlock;
1768 } else { // Ty->isFunctionPointerType()
1769 CallType = VariadicFunction;
1770 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001771
Douglas Gregorb4866e82015-06-19 18:13:19 +00001772 checkCall(NDecl, Proto,
1773 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
1774 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00001775 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00001776
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001777 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00001778}
1779
Richard Trieu41bc0992013-06-22 00:20:41 +00001780/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
1781/// such as function pointers returned from functions.
1782bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001783 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00001784 TheCall->getCallee());
Douglas Gregorb4866e82015-06-19 18:13:19 +00001785 checkCall(/*FDecl=*/nullptr, Proto,
Craig Topper8c2a2a02014-08-30 16:55:39 +00001786 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Douglas Gregorb4866e82015-06-19 18:13:19 +00001787 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00001788 TheCall->getCallee()->getSourceRange(), CallType);
1789
1790 return false;
1791}
1792
Tim Northovere94a34c2014-03-11 10:49:14 +00001793static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
JF Bastiendda2cb12016-04-18 18:01:49 +00001794 if (!llvm::isValidAtomicOrderingCABI(Ordering))
Tim Northovere94a34c2014-03-11 10:49:14 +00001795 return false;
1796
JF Bastiendda2cb12016-04-18 18:01:49 +00001797 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
Tim Northovere94a34c2014-03-11 10:49:14 +00001798 switch (Op) {
1799 case AtomicExpr::AO__c11_atomic_init:
1800 llvm_unreachable("There is no ordering argument for an init");
1801
1802 case AtomicExpr::AO__c11_atomic_load:
1803 case AtomicExpr::AO__atomic_load_n:
1804 case AtomicExpr::AO__atomic_load:
JF Bastiendda2cb12016-04-18 18:01:49 +00001805 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
1806 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00001807
1808 case AtomicExpr::AO__c11_atomic_store:
1809 case AtomicExpr::AO__atomic_store:
1810 case AtomicExpr::AO__atomic_store_n:
JF Bastiendda2cb12016-04-18 18:01:49 +00001811 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
1812 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
1813 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00001814
1815 default:
1816 return true;
1817 }
1818}
1819
Richard Smithfeea8832012-04-12 05:08:17 +00001820ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
1821 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001822 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
1823 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001824
Richard Smithfeea8832012-04-12 05:08:17 +00001825 // All these operations take one of the following forms:
1826 enum {
1827 // C __c11_atomic_init(A *, C)
1828 Init,
1829 // C __c11_atomic_load(A *, int)
1830 Load,
1831 // void __atomic_load(A *, CP, int)
Eric Fiselier8d662442016-03-30 23:39:56 +00001832 LoadCopy,
1833 // void __atomic_store(A *, CP, int)
Richard Smithfeea8832012-04-12 05:08:17 +00001834 Copy,
1835 // C __c11_atomic_add(A *, M, int)
1836 Arithmetic,
1837 // C __atomic_exchange_n(A *, CP, int)
1838 Xchg,
1839 // void __atomic_exchange(A *, C *, CP, int)
1840 GNUXchg,
1841 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
1842 C11CmpXchg,
1843 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
1844 GNUCmpXchg
1845 } Form = Init;
Eric Fiselier8d662442016-03-30 23:39:56 +00001846 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
1847 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
Richard Smithfeea8832012-04-12 05:08:17 +00001848 // where:
1849 // C is an appropriate type,
1850 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
1851 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
1852 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
1853 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001854
Gabor Horvath98bd0982015-03-16 09:59:54 +00001855 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
1856 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
1857 AtomicExpr::AO__atomic_load,
1858 "need to update code for modified C11 atomics");
Richard Smithfeea8832012-04-12 05:08:17 +00001859 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
1860 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
1861 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
1862 Op == AtomicExpr::AO__atomic_store_n ||
1863 Op == AtomicExpr::AO__atomic_exchange_n ||
1864 Op == AtomicExpr::AO__atomic_compare_exchange_n;
1865 bool IsAddSub = false;
1866
1867 switch (Op) {
1868 case AtomicExpr::AO__c11_atomic_init:
1869 Form = Init;
1870 break;
1871
1872 case AtomicExpr::AO__c11_atomic_load:
1873 case AtomicExpr::AO__atomic_load_n:
1874 Form = Load;
1875 break;
1876
Richard Smithfeea8832012-04-12 05:08:17 +00001877 case AtomicExpr::AO__atomic_load:
Eric Fiselier8d662442016-03-30 23:39:56 +00001878 Form = LoadCopy;
1879 break;
1880
1881 case AtomicExpr::AO__c11_atomic_store:
Richard Smithfeea8832012-04-12 05:08:17 +00001882 case AtomicExpr::AO__atomic_store:
1883 case AtomicExpr::AO__atomic_store_n:
1884 Form = Copy;
1885 break;
1886
1887 case AtomicExpr::AO__c11_atomic_fetch_add:
1888 case AtomicExpr::AO__c11_atomic_fetch_sub:
1889 case AtomicExpr::AO__atomic_fetch_add:
1890 case AtomicExpr::AO__atomic_fetch_sub:
1891 case AtomicExpr::AO__atomic_add_fetch:
1892 case AtomicExpr::AO__atomic_sub_fetch:
1893 IsAddSub = true;
1894 // Fall through.
1895 case AtomicExpr::AO__c11_atomic_fetch_and:
1896 case AtomicExpr::AO__c11_atomic_fetch_or:
1897 case AtomicExpr::AO__c11_atomic_fetch_xor:
1898 case AtomicExpr::AO__atomic_fetch_and:
1899 case AtomicExpr::AO__atomic_fetch_or:
1900 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00001901 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00001902 case AtomicExpr::AO__atomic_and_fetch:
1903 case AtomicExpr::AO__atomic_or_fetch:
1904 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00001905 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00001906 Form = Arithmetic;
1907 break;
1908
1909 case AtomicExpr::AO__c11_atomic_exchange:
1910 case AtomicExpr::AO__atomic_exchange_n:
1911 Form = Xchg;
1912 break;
1913
1914 case AtomicExpr::AO__atomic_exchange:
1915 Form = GNUXchg;
1916 break;
1917
1918 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1919 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1920 Form = C11CmpXchg;
1921 break;
1922
1923 case AtomicExpr::AO__atomic_compare_exchange:
1924 case AtomicExpr::AO__atomic_compare_exchange_n:
1925 Form = GNUCmpXchg;
1926 break;
1927 }
1928
1929 // Check we have the right number of arguments.
1930 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001931 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001932 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001933 << TheCall->getCallee()->getSourceRange();
1934 return ExprError();
Richard Smithfeea8832012-04-12 05:08:17 +00001935 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
1936 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001937 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001938 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001939 << TheCall->getCallee()->getSourceRange();
1940 return ExprError();
1941 }
1942
Richard Smithfeea8832012-04-12 05:08:17 +00001943 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001944 Expr *Ptr = TheCall->getArg(0);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001945 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1946 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1947 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00001948 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001949 << Ptr->getType() << Ptr->getSourceRange();
1950 return ExprError();
1951 }
1952
Richard Smithfeea8832012-04-12 05:08:17 +00001953 // For a __c11 builtin, this should be a pointer to an _Atomic type.
1954 QualType AtomTy = pointerType->getPointeeType(); // 'A'
1955 QualType ValType = AtomTy; // 'C'
1956 if (IsC11) {
1957 if (!AtomTy->isAtomicType()) {
1958 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1959 << Ptr->getType() << Ptr->getSourceRange();
1960 return ExprError();
1961 }
Richard Smithe00921a2012-09-15 06:09:58 +00001962 if (AtomTy.isConstQualified()) {
1963 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1964 << Ptr->getType() << Ptr->getSourceRange();
1965 return ExprError();
1966 }
Richard Smithfeea8832012-04-12 05:08:17 +00001967 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eric Fiselier8d662442016-03-30 23:39:56 +00001968 } else if (Form != Load && Form != LoadCopy) {
Eric Fiseliera3a7c562015-10-04 00:11:02 +00001969 if (ValType.isConstQualified()) {
1970 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
1971 << Ptr->getType() << Ptr->getSourceRange();
1972 return ExprError();
1973 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001974 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001975
Richard Smithfeea8832012-04-12 05:08:17 +00001976 // For an arithmetic operation, the implied arithmetic must be well-formed.
1977 if (Form == Arithmetic) {
1978 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1979 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1980 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1981 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1982 return ExprError();
1983 }
1984 if (!IsAddSub && !ValType->isIntegerType()) {
1985 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1986 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1987 return ExprError();
1988 }
David Majnemere85cff82015-01-28 05:48:06 +00001989 if (IsC11 && ValType->isPointerType() &&
1990 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
1991 diag::err_incomplete_type)) {
1992 return ExprError();
1993 }
Richard Smithfeea8832012-04-12 05:08:17 +00001994 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1995 // For __atomic_*_n operations, the value type must be a scalar integral or
1996 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001997 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00001998 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1999 return ExprError();
2000 }
2001
Eli Friedmanaa769812013-09-11 03:49:34 +00002002 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
2003 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00002004 // For GNU atomics, require a trivially-copyable type. This is not part of
2005 // the GNU atomics specification, but we enforce it for sanity.
2006 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002007 << Ptr->getType() << Ptr->getSourceRange();
2008 return ExprError();
2009 }
2010
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002011 switch (ValType.getObjCLifetime()) {
2012 case Qualifiers::OCL_None:
2013 case Qualifiers::OCL_ExplicitNone:
2014 // okay
2015 break;
2016
2017 case Qualifiers::OCL_Weak:
2018 case Qualifiers::OCL_Strong:
2019 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00002020 // FIXME: Can this happen? By this point, ValType should be known
2021 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002022 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
2023 << ValType << Ptr->getSourceRange();
2024 return ExprError();
2025 }
2026
David Majnemerc6eb6502015-06-03 00:26:35 +00002027 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the
2028 // volatile-ness of the pointee-type inject itself into the result or the
Eric Fiselier8d662442016-03-30 23:39:56 +00002029 // other operands. Similarly atomic_load can take a pointer to a const 'A'.
David Majnemerc6eb6502015-06-03 00:26:35 +00002030 ValType.removeLocalVolatile();
Eric Fiselier8d662442016-03-30 23:39:56 +00002031 ValType.removeLocalConst();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002032 QualType ResultType = ValType;
Eric Fiselier8d662442016-03-30 23:39:56 +00002033 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002034 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00002035 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002036 ResultType = Context.BoolTy;
2037
Richard Smithfeea8832012-04-12 05:08:17 +00002038 // The type of a parameter passed 'by value'. In the GNU atomics, such
2039 // arguments are actually passed as pointers.
2040 QualType ByValType = ValType; // 'CP'
2041 if (!IsC11 && !IsN)
2042 ByValType = Ptr->getType();
2043
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002044 // The first argument --- the pointer --- has a fixed type; we
2045 // deduce the types of the rest of the arguments accordingly. Walk
2046 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00002047 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002048 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00002049 if (i < NumVals[Form] + 1) {
2050 switch (i) {
2051 case 1:
2052 // The second argument is the non-atomic operand. For arithmetic, this
2053 // is always passed by value, and for a compare_exchange it is always
2054 // passed by address. For the rest, GNU uses by-address and C11 uses
2055 // by-value.
2056 assert(Form != Load);
2057 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
2058 Ty = ValType;
2059 else if (Form == Copy || Form == Xchg)
2060 Ty = ByValType;
2061 else if (Form == Arithmetic)
2062 Ty = Context.getPointerDiffType();
Anastasia Stulova76fd1052015-12-22 15:14:54 +00002063 else {
2064 Expr *ValArg = TheCall->getArg(i);
2065 unsigned AS = 0;
2066 // Keep address space of non-atomic pointer type.
2067 if (const PointerType *PtrTy =
2068 ValArg->getType()->getAs<PointerType>()) {
2069 AS = PtrTy->getPointeeType().getAddressSpace();
2070 }
2071 Ty = Context.getPointerType(
2072 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
2073 }
Richard Smithfeea8832012-04-12 05:08:17 +00002074 break;
2075 case 2:
2076 // The third argument to compare_exchange / GNU exchange is a
2077 // (pointer to a) desired value.
2078 Ty = ByValType;
2079 break;
2080 case 3:
2081 // The fourth argument to GNU compare_exchange is a 'weak' flag.
2082 Ty = Context.BoolTy;
2083 break;
2084 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002085 } else {
2086 // The order(s) are always converted to int.
2087 Ty = Context.IntTy;
2088 }
Richard Smithfeea8832012-04-12 05:08:17 +00002089
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002090 InitializedEntity Entity =
2091 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00002092 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002093 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2094 if (Arg.isInvalid())
2095 return true;
2096 TheCall->setArg(i, Arg.get());
2097 }
2098
Richard Smithfeea8832012-04-12 05:08:17 +00002099 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002100 SmallVector<Expr*, 5> SubExprs;
2101 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00002102 switch (Form) {
2103 case Init:
2104 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00002105 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00002106 break;
2107 case Load:
2108 SubExprs.push_back(TheCall->getArg(1)); // Order
2109 break;
Eric Fiselier8d662442016-03-30 23:39:56 +00002110 case LoadCopy:
Richard Smithfeea8832012-04-12 05:08:17 +00002111 case Copy:
2112 case Arithmetic:
2113 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002114 SubExprs.push_back(TheCall->getArg(2)); // Order
2115 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00002116 break;
2117 case GNUXchg:
2118 // Note, AtomicExpr::getVal2() has a special case for this atomic.
2119 SubExprs.push_back(TheCall->getArg(3)); // Order
2120 SubExprs.push_back(TheCall->getArg(1)); // Val1
2121 SubExprs.push_back(TheCall->getArg(2)); // Val2
2122 break;
2123 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002124 SubExprs.push_back(TheCall->getArg(3)); // Order
2125 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002126 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00002127 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00002128 break;
2129 case GNUCmpXchg:
2130 SubExprs.push_back(TheCall->getArg(4)); // Order
2131 SubExprs.push_back(TheCall->getArg(1)); // Val1
2132 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
2133 SubExprs.push_back(TheCall->getArg(2)); // Val2
2134 SubExprs.push_back(TheCall->getArg(3)); // Weak
2135 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002136 }
Tim Northovere94a34c2014-03-11 10:49:14 +00002137
2138 if (SubExprs.size() >= 2 && Form != Init) {
2139 llvm::APSInt Result(32);
2140 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
2141 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00002142 Diag(SubExprs[1]->getLocStart(),
2143 diag::warn_atomic_op_has_invalid_memory_order)
2144 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00002145 }
2146
Fariborz Jahanian615de762013-05-28 17:37:39 +00002147 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
2148 SubExprs, ResultType, Op,
2149 TheCall->getRParenLoc());
2150
2151 if ((Op == AtomicExpr::AO__c11_atomic_load ||
2152 (Op == AtomicExpr::AO__c11_atomic_store)) &&
2153 Context.AtomicUsesUnsupportedLibcall(AE))
2154 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
2155 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002156
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002157 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002158}
2159
John McCall29ad95b2011-08-27 01:09:30 +00002160/// checkBuiltinArgument - Given a call to a builtin function, perform
2161/// normal type-checking on the given argument, updating the call in
2162/// place. This is useful when a builtin function requires custom
2163/// type-checking for some of its arguments but not necessarily all of
2164/// them.
2165///
2166/// Returns true on error.
2167static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
2168 FunctionDecl *Fn = E->getDirectCallee();
2169 assert(Fn && "builtin call without direct callee!");
2170
2171 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
2172 InitializedEntity Entity =
2173 InitializedEntity::InitializeParameter(S.Context, Param);
2174
2175 ExprResult Arg = E->getArg(0);
2176 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
2177 if (Arg.isInvalid())
2178 return true;
2179
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002180 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00002181 return false;
2182}
2183
Chris Lattnerdc046542009-05-08 06:58:22 +00002184/// SemaBuiltinAtomicOverloaded - We have a call to a function like
2185/// __sync_fetch_and_add, which is an overloaded function based on the pointer
2186/// type of its first argument. The main ActOnCallExpr routines have already
2187/// promoted the types of arguments because all of these calls are prototyped as
2188/// void(...).
2189///
2190/// This function goes through and does final semantic checking for these
2191/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00002192ExprResult
2193Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002194 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00002195 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2196 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2197
2198 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002199 if (TheCall->getNumArgs() < 1) {
2200 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
2201 << 0 << 1 << TheCall->getNumArgs()
2202 << TheCall->getCallee()->getSourceRange();
2203 return ExprError();
2204 }
Mike Stump11289f42009-09-09 15:08:12 +00002205
Chris Lattnerdc046542009-05-08 06:58:22 +00002206 // Inspect the first argument of the atomic builtin. This should always be
2207 // a pointer type, whose element is an integral scalar or pointer type.
2208 // Because it is a pointer type, we don't have to worry about any implicit
2209 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002210 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00002211 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00002212 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
2213 if (FirstArgResult.isInvalid())
2214 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002215 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00002216 TheCall->setArg(0, FirstArg);
2217
John McCall31168b02011-06-15 23:02:42 +00002218 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
2219 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002220 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
2221 << FirstArg->getType() << FirstArg->getSourceRange();
2222 return ExprError();
2223 }
Mike Stump11289f42009-09-09 15:08:12 +00002224
John McCall31168b02011-06-15 23:02:42 +00002225 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00002226 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002227 !ValType->isBlockPointerType()) {
2228 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
2229 << FirstArg->getType() << FirstArg->getSourceRange();
2230 return ExprError();
2231 }
Chris Lattnerdc046542009-05-08 06:58:22 +00002232
John McCall31168b02011-06-15 23:02:42 +00002233 switch (ValType.getObjCLifetime()) {
2234 case Qualifiers::OCL_None:
2235 case Qualifiers::OCL_ExplicitNone:
2236 // okay
2237 break;
2238
2239 case Qualifiers::OCL_Weak:
2240 case Qualifiers::OCL_Strong:
2241 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00002242 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00002243 << ValType << FirstArg->getSourceRange();
2244 return ExprError();
2245 }
2246
John McCallb50451a2011-10-05 07:41:44 +00002247 // Strip any qualifiers off ValType.
2248 ValType = ValType.getUnqualifiedType();
2249
Chandler Carruth3973af72010-07-18 20:54:12 +00002250 // The majority of builtins return a value, but a few have special return
2251 // types, so allow them to override appropriately below.
2252 QualType ResultType = ValType;
2253
Chris Lattnerdc046542009-05-08 06:58:22 +00002254 // We need to figure out which concrete builtin this maps onto. For example,
2255 // __sync_fetch_and_add with a 2 byte object turns into
2256 // __sync_fetch_and_add_2.
2257#define BUILTIN_ROW(x) \
2258 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
2259 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00002260
Chris Lattnerdc046542009-05-08 06:58:22 +00002261 static const unsigned BuiltinIndices[][5] = {
2262 BUILTIN_ROW(__sync_fetch_and_add),
2263 BUILTIN_ROW(__sync_fetch_and_sub),
2264 BUILTIN_ROW(__sync_fetch_and_or),
2265 BUILTIN_ROW(__sync_fetch_and_and),
2266 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00002267 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00002268
Chris Lattnerdc046542009-05-08 06:58:22 +00002269 BUILTIN_ROW(__sync_add_and_fetch),
2270 BUILTIN_ROW(__sync_sub_and_fetch),
2271 BUILTIN_ROW(__sync_and_and_fetch),
2272 BUILTIN_ROW(__sync_or_and_fetch),
2273 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00002274 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00002275
Chris Lattnerdc046542009-05-08 06:58:22 +00002276 BUILTIN_ROW(__sync_val_compare_and_swap),
2277 BUILTIN_ROW(__sync_bool_compare_and_swap),
2278 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00002279 BUILTIN_ROW(__sync_lock_release),
2280 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00002281 };
Mike Stump11289f42009-09-09 15:08:12 +00002282#undef BUILTIN_ROW
2283
Chris Lattnerdc046542009-05-08 06:58:22 +00002284 // Determine the index of the size.
2285 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00002286 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00002287 case 1: SizeIndex = 0; break;
2288 case 2: SizeIndex = 1; break;
2289 case 4: SizeIndex = 2; break;
2290 case 8: SizeIndex = 3; break;
2291 case 16: SizeIndex = 4; break;
2292 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002293 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
2294 << FirstArg->getType() << FirstArg->getSourceRange();
2295 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00002296 }
Mike Stump11289f42009-09-09 15:08:12 +00002297
Chris Lattnerdc046542009-05-08 06:58:22 +00002298 // Each of these builtins has one pointer argument, followed by some number of
2299 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
2300 // that we ignore. Find out which row of BuiltinIndices to read from as well
2301 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00002302 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00002303 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00002304 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00002305 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00002306 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00002307 case Builtin::BI__sync_fetch_and_add:
2308 case Builtin::BI__sync_fetch_and_add_1:
2309 case Builtin::BI__sync_fetch_and_add_2:
2310 case Builtin::BI__sync_fetch_and_add_4:
2311 case Builtin::BI__sync_fetch_and_add_8:
2312 case Builtin::BI__sync_fetch_and_add_16:
2313 BuiltinIndex = 0;
2314 break;
2315
2316 case Builtin::BI__sync_fetch_and_sub:
2317 case Builtin::BI__sync_fetch_and_sub_1:
2318 case Builtin::BI__sync_fetch_and_sub_2:
2319 case Builtin::BI__sync_fetch_and_sub_4:
2320 case Builtin::BI__sync_fetch_and_sub_8:
2321 case Builtin::BI__sync_fetch_and_sub_16:
2322 BuiltinIndex = 1;
2323 break;
2324
2325 case Builtin::BI__sync_fetch_and_or:
2326 case Builtin::BI__sync_fetch_and_or_1:
2327 case Builtin::BI__sync_fetch_and_or_2:
2328 case Builtin::BI__sync_fetch_and_or_4:
2329 case Builtin::BI__sync_fetch_and_or_8:
2330 case Builtin::BI__sync_fetch_and_or_16:
2331 BuiltinIndex = 2;
2332 break;
2333
2334 case Builtin::BI__sync_fetch_and_and:
2335 case Builtin::BI__sync_fetch_and_and_1:
2336 case Builtin::BI__sync_fetch_and_and_2:
2337 case Builtin::BI__sync_fetch_and_and_4:
2338 case Builtin::BI__sync_fetch_and_and_8:
2339 case Builtin::BI__sync_fetch_and_and_16:
2340 BuiltinIndex = 3;
2341 break;
Mike Stump11289f42009-09-09 15:08:12 +00002342
Douglas Gregor73722482011-11-28 16:30:08 +00002343 case Builtin::BI__sync_fetch_and_xor:
2344 case Builtin::BI__sync_fetch_and_xor_1:
2345 case Builtin::BI__sync_fetch_and_xor_2:
2346 case Builtin::BI__sync_fetch_and_xor_4:
2347 case Builtin::BI__sync_fetch_and_xor_8:
2348 case Builtin::BI__sync_fetch_and_xor_16:
2349 BuiltinIndex = 4;
2350 break;
2351
Hal Finkeld2208b52014-10-02 20:53:50 +00002352 case Builtin::BI__sync_fetch_and_nand:
2353 case Builtin::BI__sync_fetch_and_nand_1:
2354 case Builtin::BI__sync_fetch_and_nand_2:
2355 case Builtin::BI__sync_fetch_and_nand_4:
2356 case Builtin::BI__sync_fetch_and_nand_8:
2357 case Builtin::BI__sync_fetch_and_nand_16:
2358 BuiltinIndex = 5;
2359 WarnAboutSemanticsChange = true;
2360 break;
2361
Douglas Gregor73722482011-11-28 16:30:08 +00002362 case Builtin::BI__sync_add_and_fetch:
2363 case Builtin::BI__sync_add_and_fetch_1:
2364 case Builtin::BI__sync_add_and_fetch_2:
2365 case Builtin::BI__sync_add_and_fetch_4:
2366 case Builtin::BI__sync_add_and_fetch_8:
2367 case Builtin::BI__sync_add_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002368 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00002369 break;
2370
2371 case Builtin::BI__sync_sub_and_fetch:
2372 case Builtin::BI__sync_sub_and_fetch_1:
2373 case Builtin::BI__sync_sub_and_fetch_2:
2374 case Builtin::BI__sync_sub_and_fetch_4:
2375 case Builtin::BI__sync_sub_and_fetch_8:
2376 case Builtin::BI__sync_sub_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002377 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00002378 break;
2379
2380 case Builtin::BI__sync_and_and_fetch:
2381 case Builtin::BI__sync_and_and_fetch_1:
2382 case Builtin::BI__sync_and_and_fetch_2:
2383 case Builtin::BI__sync_and_and_fetch_4:
2384 case Builtin::BI__sync_and_and_fetch_8:
2385 case Builtin::BI__sync_and_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002386 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00002387 break;
2388
2389 case Builtin::BI__sync_or_and_fetch:
2390 case Builtin::BI__sync_or_and_fetch_1:
2391 case Builtin::BI__sync_or_and_fetch_2:
2392 case Builtin::BI__sync_or_and_fetch_4:
2393 case Builtin::BI__sync_or_and_fetch_8:
2394 case Builtin::BI__sync_or_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002395 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00002396 break;
2397
2398 case Builtin::BI__sync_xor_and_fetch:
2399 case Builtin::BI__sync_xor_and_fetch_1:
2400 case Builtin::BI__sync_xor_and_fetch_2:
2401 case Builtin::BI__sync_xor_and_fetch_4:
2402 case Builtin::BI__sync_xor_and_fetch_8:
2403 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002404 BuiltinIndex = 10;
2405 break;
2406
2407 case Builtin::BI__sync_nand_and_fetch:
2408 case Builtin::BI__sync_nand_and_fetch_1:
2409 case Builtin::BI__sync_nand_and_fetch_2:
2410 case Builtin::BI__sync_nand_and_fetch_4:
2411 case Builtin::BI__sync_nand_and_fetch_8:
2412 case Builtin::BI__sync_nand_and_fetch_16:
2413 BuiltinIndex = 11;
2414 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00002415 break;
Mike Stump11289f42009-09-09 15:08:12 +00002416
Chris Lattnerdc046542009-05-08 06:58:22 +00002417 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00002418 case Builtin::BI__sync_val_compare_and_swap_1:
2419 case Builtin::BI__sync_val_compare_and_swap_2:
2420 case Builtin::BI__sync_val_compare_and_swap_4:
2421 case Builtin::BI__sync_val_compare_and_swap_8:
2422 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002423 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00002424 NumFixed = 2;
2425 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002426
Chris Lattnerdc046542009-05-08 06:58:22 +00002427 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00002428 case Builtin::BI__sync_bool_compare_and_swap_1:
2429 case Builtin::BI__sync_bool_compare_and_swap_2:
2430 case Builtin::BI__sync_bool_compare_and_swap_4:
2431 case Builtin::BI__sync_bool_compare_and_swap_8:
2432 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002433 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00002434 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00002435 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00002436 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002437
2438 case Builtin::BI__sync_lock_test_and_set:
2439 case Builtin::BI__sync_lock_test_and_set_1:
2440 case Builtin::BI__sync_lock_test_and_set_2:
2441 case Builtin::BI__sync_lock_test_and_set_4:
2442 case Builtin::BI__sync_lock_test_and_set_8:
2443 case Builtin::BI__sync_lock_test_and_set_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002444 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00002445 break;
2446
Chris Lattnerdc046542009-05-08 06:58:22 +00002447 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00002448 case Builtin::BI__sync_lock_release_1:
2449 case Builtin::BI__sync_lock_release_2:
2450 case Builtin::BI__sync_lock_release_4:
2451 case Builtin::BI__sync_lock_release_8:
2452 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002453 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00002454 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00002455 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00002456 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002457
2458 case Builtin::BI__sync_swap:
2459 case Builtin::BI__sync_swap_1:
2460 case Builtin::BI__sync_swap_2:
2461 case Builtin::BI__sync_swap_4:
2462 case Builtin::BI__sync_swap_8:
2463 case Builtin::BI__sync_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002464 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00002465 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00002466 }
Mike Stump11289f42009-09-09 15:08:12 +00002467
Chris Lattnerdc046542009-05-08 06:58:22 +00002468 // Now that we know how many fixed arguments we expect, first check that we
2469 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002470 if (TheCall->getNumArgs() < 1+NumFixed) {
2471 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
2472 << 0 << 1+NumFixed << TheCall->getNumArgs()
2473 << TheCall->getCallee()->getSourceRange();
2474 return ExprError();
2475 }
Mike Stump11289f42009-09-09 15:08:12 +00002476
Hal Finkeld2208b52014-10-02 20:53:50 +00002477 if (WarnAboutSemanticsChange) {
2478 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
2479 << TheCall->getCallee()->getSourceRange();
2480 }
2481
Chris Lattner5b9241b2009-05-08 15:36:58 +00002482 // Get the decl for the concrete builtin from this, we can tell what the
2483 // concrete integer type we should convert to is.
2484 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
Eric Christopher02d5d862015-08-06 01:01:12 +00002485 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00002486 FunctionDecl *NewBuiltinDecl;
2487 if (NewBuiltinID == BuiltinID)
2488 NewBuiltinDecl = FDecl;
2489 else {
2490 // Perform builtin lookup to avoid redeclaring it.
2491 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
2492 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
2493 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
2494 assert(Res.getFoundDecl());
2495 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00002496 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00002497 return ExprError();
2498 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002499
John McCallcf142162010-08-07 06:22:56 +00002500 // The first argument --- the pointer --- has a fixed type; we
2501 // deduce the types of the rest of the arguments accordingly. Walk
2502 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00002503 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00002504 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00002505
Chris Lattnerdc046542009-05-08 06:58:22 +00002506 // GCC does an implicit conversion to the pointer or integer ValType. This
2507 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00002508 // Initialize the argument.
2509 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
2510 ValType, /*consume*/ false);
2511 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00002512 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002513 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002514
Chris Lattnerdc046542009-05-08 06:58:22 +00002515 // Okay, we have something that *can* be converted to the right type. Check
2516 // to see if there is a potentially weird extension going on here. This can
2517 // happen when you do an atomic operation on something like an char* and
2518 // pass in 42. The 42 gets converted to char. This is even more strange
2519 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00002520 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002521 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00002522 }
Mike Stump11289f42009-09-09 15:08:12 +00002523
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002524 ASTContext& Context = this->getASTContext();
2525
2526 // Create a new DeclRefExpr to refer to the new decl.
2527 DeclRefExpr* NewDRE = DeclRefExpr::Create(
2528 Context,
2529 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00002530 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002531 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00002532 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002533 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00002534 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002535 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00002536
Chris Lattnerdc046542009-05-08 06:58:22 +00002537 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00002538 // FIXME: This loses syntactic information.
2539 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
2540 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
2541 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002542 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00002543
Chandler Carruthbc8cab12010-07-18 07:23:17 +00002544 // Change the result type of the call to match the original value type. This
2545 // is arbitrary, but the codegen for these builtins ins design to handle it
2546 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00002547 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002548
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002549 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00002550}
2551
Michael Zolotukhin84df1232015-09-08 23:52:33 +00002552/// SemaBuiltinNontemporalOverloaded - We have a call to
2553/// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
2554/// overloaded function based on the pointer type of its last argument.
2555///
2556/// This function goes through and does final semantic checking for these
2557/// builtins.
2558ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
2559 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
2560 DeclRefExpr *DRE =
2561 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2562 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2563 unsigned BuiltinID = FDecl->getBuiltinID();
2564 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
2565 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
2566 "Unexpected nontemporal load/store builtin!");
2567 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
2568 unsigned numArgs = isStore ? 2 : 1;
2569
2570 // Ensure that we have the proper number of arguments.
2571 if (checkArgCount(*this, TheCall, numArgs))
2572 return ExprError();
2573
2574 // Inspect the last argument of the nontemporal builtin. This should always
2575 // be a pointer type, from which we imply the type of the memory access.
2576 // Because it is a pointer type, we don't have to worry about any implicit
2577 // casts here.
2578 Expr *PointerArg = TheCall->getArg(numArgs - 1);
2579 ExprResult PointerArgResult =
2580 DefaultFunctionArrayLvalueConversion(PointerArg);
2581
2582 if (PointerArgResult.isInvalid())
2583 return ExprError();
2584 PointerArg = PointerArgResult.get();
2585 TheCall->setArg(numArgs - 1, PointerArg);
2586
2587 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
2588 if (!pointerType) {
2589 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
2590 << PointerArg->getType() << PointerArg->getSourceRange();
2591 return ExprError();
2592 }
2593
2594 QualType ValType = pointerType->getPointeeType();
2595
2596 // Strip any qualifiers off ValType.
2597 ValType = ValType.getUnqualifiedType();
2598 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2599 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
2600 !ValType->isVectorType()) {
2601 Diag(DRE->getLocStart(),
2602 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
2603 << PointerArg->getType() << PointerArg->getSourceRange();
2604 return ExprError();
2605 }
2606
2607 if (!isStore) {
2608 TheCall->setType(ValType);
2609 return TheCallResult;
2610 }
2611
2612 ExprResult ValArg = TheCall->getArg(0);
2613 InitializedEntity Entity = InitializedEntity::InitializeParameter(
2614 Context, ValType, /*consume*/ false);
2615 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
2616 if (ValArg.isInvalid())
2617 return ExprError();
2618
2619 TheCall->setArg(0, ValArg.get());
2620 TheCall->setType(Context.VoidTy);
2621 return TheCallResult;
2622}
2623
Chris Lattner6436fb62009-02-18 06:01:06 +00002624/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00002625/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00002626/// Note: It might also make sense to do the UTF-16 conversion here (would
2627/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00002628bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00002629 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00002630 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
2631
Douglas Gregorfb65e592011-07-27 05:40:30 +00002632 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00002633 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
2634 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00002635 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00002636 }
Mike Stump11289f42009-09-09 15:08:12 +00002637
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002638 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002639 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002640 unsigned NumBytes = String.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002641 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divackye6377112012-09-06 15:59:27 +00002642 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002643 UTF16 *ToPtr = &ToBuf[0];
2644
2645 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
2646 &ToPtr, ToPtr + NumBytes,
2647 strictConversion);
2648 // Check for conversion failure.
2649 if (Result != conversionOK)
2650 Diag(Arg->getLocStart(),
2651 diag::warn_cfstring_truncated) << Arg->getSourceRange();
2652 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00002653 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002654}
2655
Charles Davisc7d5c942015-09-17 20:55:33 +00002656/// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
2657/// for validity. Emit an error and return true on failure; return false
2658/// on success.
2659bool Sema::SemaBuiltinVAStartImpl(CallExpr *TheCall) {
Chris Lattner08464942007-12-28 05:29:59 +00002660 Expr *Fn = TheCall->getCallee();
2661 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00002662 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002663 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002664 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2665 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00002666 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002667 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00002668 return true;
2669 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00002670
2671 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00002672 return Diag(TheCall->getLocEnd(),
2673 diag::err_typecheck_call_too_few_args_at_least)
2674 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00002675 }
2676
John McCall29ad95b2011-08-27 01:09:30 +00002677 // Type-check the first argument normally.
2678 if (checkBuiltinArgument(*this, TheCall, 0))
2679 return true;
2680
Chris Lattnere202e6a2007-12-20 00:05:45 +00002681 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +00002682 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +00002683 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +00002684 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +00002685 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +00002686 else if (FunctionDecl *FD = getCurFunctionDecl())
2687 isVariadic = FD->isVariadic();
2688 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00002689 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +00002690
Chris Lattnere202e6a2007-12-20 00:05:45 +00002691 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +00002692 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2693 return true;
2694 }
Mike Stump11289f42009-09-09 15:08:12 +00002695
Chris Lattner43be2e62007-12-19 23:59:04 +00002696 // Verify that the second argument to the builtin is the last argument of the
2697 // current function or method.
2698 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00002699 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00002700
Nico Weber9eea7642013-05-24 23:31:57 +00002701 // These are valid if SecondArgIsLastNamedArgument is false after the next
2702 // block.
2703 QualType Type;
2704 SourceLocation ParamLoc;
Aaron Ballman1de59c52016-04-24 13:30:21 +00002705 bool IsCRegister = false;
Nico Weber9eea7642013-05-24 23:31:57 +00002706
Anders Carlsson6a8350b2008-02-11 04:20:54 +00002707 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
2708 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +00002709 // FIXME: This isn't correct for methods (results in bogus warning).
2710 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +00002711 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +00002712 if (CurBlock)
2713 LastArg = *(CurBlock->TheDecl->param_end()-1);
2714 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner79413952008-12-04 23:50:19 +00002715 LastArg = *(FD->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00002716 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00002717 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00002718 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weber9eea7642013-05-24 23:31:57 +00002719
2720 Type = PV->getType();
2721 ParamLoc = PV->getLocation();
Aaron Ballman1de59c52016-04-24 13:30:21 +00002722 IsCRegister =
2723 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
Chris Lattner43be2e62007-12-19 23:59:04 +00002724 }
2725 }
Mike Stump11289f42009-09-09 15:08:12 +00002726
Chris Lattner43be2e62007-12-19 23:59:04 +00002727 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00002728 Diag(TheCall->getArg(1)->getLocStart(),
Aaron Ballman05164812016-04-18 18:10:53 +00002729 diag::warn_second_arg_of_va_start_not_last_named_param);
Aaron Ballman1de59c52016-04-24 13:30:21 +00002730 else if (IsCRegister || Type->isReferenceType() ||
2731 Type->isPromotableIntegerType() ||
2732 Type->isSpecificBuiltinType(BuiltinType::Float)) {
2733 unsigned Reason = 0;
2734 if (Type->isReferenceType()) Reason = 1;
2735 else if (IsCRegister) Reason = 2;
2736 Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
Nico Weber9eea7642013-05-24 23:31:57 +00002737 Diag(ParamLoc, diag::note_parameter_type) << Type;
2738 }
2739
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00002740 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00002741 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00002742}
Chris Lattner43be2e62007-12-19 23:59:04 +00002743
Charles Davisc7d5c942015-09-17 20:55:33 +00002744/// Check the arguments to '__builtin_va_start' for validity, and that
2745/// it was called from a function of the native ABI.
2746/// Emit an error and return true on failure; return false on success.
2747bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
2748 // On x86-64 Unix, don't allow this in Win64 ABI functions.
2749 // On x64 Windows, don't allow this in System V ABI functions.
2750 // (Yes, that means there's no corresponding way to support variadic
2751 // System V ABI functions on Windows.)
2752 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64) {
2753 unsigned OS = Context.getTargetInfo().getTriple().getOS();
2754 clang::CallingConv CC = CC_C;
2755 if (const FunctionDecl *FD = getCurFunctionDecl())
2756 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
2757 if ((OS == llvm::Triple::Win32 && CC == CC_X86_64SysV) ||
2758 (OS != llvm::Triple::Win32 && CC == CC_X86_64Win64))
2759 return Diag(TheCall->getCallee()->getLocStart(),
2760 diag::err_va_start_used_in_wrong_abi_function)
2761 << (OS != llvm::Triple::Win32);
2762 }
2763 return SemaBuiltinVAStartImpl(TheCall);
2764}
2765
2766/// Check the arguments to '__builtin_ms_va_start' for validity, and that
2767/// it was called from a Win64 ABI function.
2768/// Emit an error and return true on failure; return false on success.
2769bool Sema::SemaBuiltinMSVAStart(CallExpr *TheCall) {
2770 // This only makes sense for x86-64.
2771 const llvm::Triple &TT = Context.getTargetInfo().getTriple();
2772 Expr *Callee = TheCall->getCallee();
2773 if (TT.getArch() != llvm::Triple::x86_64)
2774 return Diag(Callee->getLocStart(), diag::err_x86_builtin_32_bit_tgt);
2775 // Don't allow this in System V ABI functions.
2776 clang::CallingConv CC = CC_C;
2777 if (const FunctionDecl *FD = getCurFunctionDecl())
2778 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
2779 if (CC == CC_X86_64SysV ||
2780 (TT.getOS() != llvm::Triple::Win32 && CC != CC_X86_64Win64))
2781 return Diag(Callee->getLocStart(),
2782 diag::err_ms_va_start_used_in_sysv_function);
2783 return SemaBuiltinVAStartImpl(TheCall);
2784}
2785
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00002786bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
2787 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
2788 // const char *named_addr);
2789
2790 Expr *Func = Call->getCallee();
2791
2792 if (Call->getNumArgs() < 3)
2793 return Diag(Call->getLocEnd(),
2794 diag::err_typecheck_call_too_few_args_at_least)
2795 << 0 /*function call*/ << 3 << Call->getNumArgs();
2796
2797 // Determine whether the current function is variadic or not.
2798 bool IsVariadic;
2799 if (BlockScopeInfo *CurBlock = getCurBlock())
2800 IsVariadic = CurBlock->TheDecl->isVariadic();
2801 else if (FunctionDecl *FD = getCurFunctionDecl())
2802 IsVariadic = FD->isVariadic();
2803 else if (ObjCMethodDecl *MD = getCurMethodDecl())
2804 IsVariadic = MD->isVariadic();
2805 else
2806 llvm_unreachable("unexpected statement type");
2807
2808 if (!IsVariadic) {
2809 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2810 return true;
2811 }
2812
2813 // Type-check the first argument normally.
2814 if (checkBuiltinArgument(*this, Call, 0))
2815 return true;
2816
Benjamin Kramere0ca6e12015-03-01 18:09:50 +00002817 const struct {
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00002818 unsigned ArgNo;
2819 QualType Type;
2820 } ArgumentTypes[] = {
2821 { 1, Context.getPointerType(Context.CharTy.withConst()) },
2822 { 2, Context.getSizeType() },
2823 };
2824
2825 for (const auto &AT : ArgumentTypes) {
2826 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
2827 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
2828 continue;
2829 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
2830 << Arg->getType() << AT.Type << 1 /* different class */
2831 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
2832 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
2833 }
2834
2835 return false;
2836}
2837
Chris Lattner2da14fb2007-12-20 00:26:33 +00002838/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
2839/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00002840bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
2841 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00002842 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00002843 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00002844 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00002845 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002846 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002847 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00002848 << SourceRange(TheCall->getArg(2)->getLocStart(),
2849 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00002850
John Wiegley01296292011-04-08 18:41:53 +00002851 ExprResult OrigArg0 = TheCall->getArg(0);
2852 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00002853
Chris Lattner2da14fb2007-12-20 00:26:33 +00002854 // Do standard promotions between the two arguments, returning their common
2855 // type.
Chris Lattner08464942007-12-28 05:29:59 +00002856 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00002857 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
2858 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00002859
2860 // Make sure any conversions are pushed back into the call; this is
2861 // type safe since unordered compare builtins are declared as "_Bool
2862 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00002863 TheCall->setArg(0, OrigArg0.get());
2864 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00002865
John Wiegley01296292011-04-08 18:41:53 +00002866 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00002867 return false;
2868
Chris Lattner2da14fb2007-12-20 00:26:33 +00002869 // If the common type isn't a real floating type, then the arguments were
2870 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00002871 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00002872 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002873 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00002874 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
2875 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00002876
Chris Lattner2da14fb2007-12-20 00:26:33 +00002877 return false;
2878}
2879
Benjamin Kramer634fc102010-02-15 22:42:31 +00002880/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
2881/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00002882/// to check everything. We expect the last argument to be a floating point
2883/// value.
2884bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
2885 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00002886 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00002887 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00002888 if (TheCall->getNumArgs() > NumArgs)
2889 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002890 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002891 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00002892 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002893 (*(TheCall->arg_end()-1))->getLocEnd());
2894
Benjamin Kramer64aae502010-02-16 10:07:31 +00002895 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00002896
Eli Friedman7e4faac2009-08-31 20:06:00 +00002897 if (OrigArg->isTypeDependent())
2898 return false;
2899
Chris Lattner68784ef2010-05-06 05:50:07 +00002900 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00002901 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00002902 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002903 diag::err_typecheck_call_invalid_unary_fp)
2904 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002905
Chris Lattner68784ef2010-05-06 05:50:07 +00002906 // If this is an implicit conversion from float -> double, remove it.
2907 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
2908 Expr *CastArg = Cast->getSubExpr();
2909 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
2910 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
2911 "promotion from float to double is the only expected cast here");
Craig Topperc3ec1492014-05-26 06:22:03 +00002912 Cast->setSubExpr(nullptr);
Chris Lattner68784ef2010-05-06 05:50:07 +00002913 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner68784ef2010-05-06 05:50:07 +00002914 }
2915 }
2916
Eli Friedman7e4faac2009-08-31 20:06:00 +00002917 return false;
2918}
2919
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002920/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
2921// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00002922ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00002923 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002924 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00002925 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00002926 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2927 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002928
Nate Begemana0110022010-06-08 00:16:34 +00002929 // Determine which of the following types of shufflevector we're checking:
2930 // 1) unary, vector mask: (lhs, mask)
2931 // 2) binary, vector mask: (lhs, rhs, mask)
2932 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
2933 QualType resType = TheCall->getArg(0)->getType();
2934 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00002935
Douglas Gregorc25f7662009-05-19 22:10:17 +00002936 if (!TheCall->getArg(0)->isTypeDependent() &&
2937 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00002938 QualType LHSType = TheCall->getArg(0)->getType();
2939 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00002940
Craig Topperbaca3892013-07-29 06:47:04 +00002941 if (!LHSType->isVectorType() || !RHSType->isVectorType())
2942 return ExprError(Diag(TheCall->getLocStart(),
2943 diag::err_shufflevector_non_vector)
2944 << SourceRange(TheCall->getArg(0)->getLocStart(),
2945 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00002946
Nate Begemana0110022010-06-08 00:16:34 +00002947 numElements = LHSType->getAs<VectorType>()->getNumElements();
2948 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00002949
Nate Begemana0110022010-06-08 00:16:34 +00002950 // Check to see if we have a call with 2 vector arguments, the unary shuffle
2951 // with mask. If so, verify that RHS is an integer vector type with the
2952 // same number of elts as lhs.
2953 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00002954 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00002955 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00002956 return ExprError(Diag(TheCall->getLocStart(),
2957 diag::err_shufflevector_incompatible_vector)
2958 << SourceRange(TheCall->getArg(1)->getLocStart(),
2959 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00002960 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00002961 return ExprError(Diag(TheCall->getLocStart(),
2962 diag::err_shufflevector_incompatible_vector)
2963 << SourceRange(TheCall->getArg(0)->getLocStart(),
2964 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00002965 } else if (numElements != numResElements) {
2966 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00002967 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002968 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00002969 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002970 }
2971
2972 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00002973 if (TheCall->getArg(i)->isTypeDependent() ||
2974 TheCall->getArg(i)->isValueDependent())
2975 continue;
2976
Nate Begemana0110022010-06-08 00:16:34 +00002977 llvm::APSInt Result(32);
2978 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
2979 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00002980 diag::err_shufflevector_nonconstant_argument)
2981 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002982
Craig Topper50ad5b72013-08-03 17:40:38 +00002983 // Allow -1 which will be translated to undef in the IR.
2984 if (Result.isSigned() && Result.isAllOnesValue())
2985 continue;
2986
Chris Lattner7ab824e2008-08-10 02:05:13 +00002987 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002988 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00002989 diag::err_shufflevector_argument_too_large)
2990 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002991 }
2992
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002993 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002994
Chris Lattner7ab824e2008-08-10 02:05:13 +00002995 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002996 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00002997 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002998 }
2999
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003000 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
3001 TheCall->getCallee()->getLocStart(),
3002 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003003}
Chris Lattner43be2e62007-12-19 23:59:04 +00003004
Hal Finkelc4d7c822013-09-18 03:29:45 +00003005/// SemaConvertVectorExpr - Handle __builtin_convertvector
3006ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
3007 SourceLocation BuiltinLoc,
3008 SourceLocation RParenLoc) {
3009 ExprValueKind VK = VK_RValue;
3010 ExprObjectKind OK = OK_Ordinary;
3011 QualType DstTy = TInfo->getType();
3012 QualType SrcTy = E->getType();
3013
3014 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
3015 return ExprError(Diag(BuiltinLoc,
3016 diag::err_convertvector_non_vector)
3017 << E->getSourceRange());
3018 if (!DstTy->isVectorType() && !DstTy->isDependentType())
3019 return ExprError(Diag(BuiltinLoc,
3020 diag::err_convertvector_non_vector_type));
3021
3022 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
3023 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
3024 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
3025 if (SrcElts != DstElts)
3026 return ExprError(Diag(BuiltinLoc,
3027 diag::err_convertvector_incompatible_vector)
3028 << E->getSourceRange());
3029 }
3030
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003031 return new (Context)
3032 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00003033}
3034
Daniel Dunbarb7257262008-07-21 22:59:13 +00003035/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
3036// This is declared to take (const void*, ...) and can take two
3037// optional constant int args.
3038bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00003039 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00003040
Chris Lattner3b054132008-11-19 05:08:23 +00003041 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003042 return Diag(TheCall->getLocEnd(),
3043 diag::err_typecheck_call_too_many_args_at_most)
3044 << 0 /*function call*/ << 3 << NumArgs
3045 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00003046
3047 // Argument 0 is checked for us and the remaining arguments must be
3048 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00003049 for (unsigned i = 1; i != NumArgs; ++i)
3050 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00003051 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003052
Warren Hunt20e4a5d2014-02-21 23:08:53 +00003053 return false;
3054}
3055
Hal Finkelf0417332014-07-17 14:25:55 +00003056/// SemaBuiltinAssume - Handle __assume (MS Extension).
3057// __assume does not evaluate its arguments, and should warn if its argument
3058// has side effects.
3059bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
3060 Expr *Arg = TheCall->getArg(0);
3061 if (Arg->isInstantiationDependent()) return false;
3062
3063 if (Arg->HasSideEffects(Context))
David Majnemer51236642015-02-26 00:57:33 +00003064 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00003065 << Arg->getSourceRange()
3066 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
3067
3068 return false;
3069}
3070
3071/// Handle __builtin_assume_aligned. This is declared
3072/// as (const void*, size_t, ...) and can take one optional constant int arg.
3073bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
3074 unsigned NumArgs = TheCall->getNumArgs();
3075
3076 if (NumArgs > 3)
3077 return Diag(TheCall->getLocEnd(),
3078 diag::err_typecheck_call_too_many_args_at_most)
3079 << 0 /*function call*/ << 3 << NumArgs
3080 << TheCall->getSourceRange();
3081
3082 // The alignment must be a constant integer.
3083 Expr *Arg = TheCall->getArg(1);
3084
3085 // We can't check the value of a dependent argument.
3086 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
3087 llvm::APSInt Result;
3088 if (SemaBuiltinConstantArg(TheCall, 1, Result))
3089 return true;
3090
3091 if (!Result.isPowerOf2())
3092 return Diag(TheCall->getLocStart(),
3093 diag::err_alignment_not_power_of_two)
3094 << Arg->getSourceRange();
3095 }
3096
3097 if (NumArgs > 2) {
3098 ExprResult Arg(TheCall->getArg(2));
3099 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3100 Context.getSizeType(), false);
3101 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3102 if (Arg.isInvalid()) return true;
3103 TheCall->setArg(2, Arg.get());
3104 }
Hal Finkelf0417332014-07-17 14:25:55 +00003105
3106 return false;
3107}
3108
Eric Christopher8d0c6212010-04-17 02:26:23 +00003109/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
3110/// TheCall is a constant expression.
3111bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
3112 llvm::APSInt &Result) {
3113 Expr *Arg = TheCall->getArg(ArgNum);
3114 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3115 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3116
3117 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
3118
3119 if (!Arg->isIntegerConstantExpr(Result, Context))
3120 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00003121 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00003122
Chris Lattnerd545ad12009-09-23 06:06:36 +00003123 return false;
3124}
3125
Richard Sandiford28940af2014-04-16 08:47:51 +00003126/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
3127/// TheCall is a constant expression in the range [Low, High].
3128bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
3129 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00003130 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00003131
3132 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00003133 Expr *Arg = TheCall->getArg(ArgNum);
3134 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00003135 return false;
3136
Eric Christopher8d0c6212010-04-17 02:26:23 +00003137 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00003138 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00003139 return true;
3140
Richard Sandiford28940af2014-04-16 08:47:51 +00003141 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00003142 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00003143 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00003144
3145 return false;
3146}
3147
Luke Cheeseman59b2d832015-06-15 17:51:01 +00003148/// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
3149/// TheCall is an ARM/AArch64 special register string literal.
3150bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
3151 int ArgNum, unsigned ExpectedFieldNum,
3152 bool AllowName) {
3153 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
3154 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
3155 BuiltinID == ARM::BI__builtin_arm_rsr ||
3156 BuiltinID == ARM::BI__builtin_arm_rsrp ||
3157 BuiltinID == ARM::BI__builtin_arm_wsr ||
3158 BuiltinID == ARM::BI__builtin_arm_wsrp;
3159 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
3160 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
3161 BuiltinID == AArch64::BI__builtin_arm_rsr ||
3162 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
3163 BuiltinID == AArch64::BI__builtin_arm_wsr ||
3164 BuiltinID == AArch64::BI__builtin_arm_wsrp;
3165 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
3166
3167 // We can't check the value of a dependent argument.
3168 Expr *Arg = TheCall->getArg(ArgNum);
3169 if (Arg->isTypeDependent() || Arg->isValueDependent())
3170 return false;
3171
3172 // Check if the argument is a string literal.
3173 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3174 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
3175 << Arg->getSourceRange();
3176
3177 // Check the type of special register given.
3178 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3179 SmallVector<StringRef, 6> Fields;
3180 Reg.split(Fields, ":");
3181
3182 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
3183 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
3184 << Arg->getSourceRange();
3185
3186 // If the string is the name of a register then we cannot check that it is
3187 // valid here but if the string is of one the forms described in ACLE then we
3188 // can check that the supplied fields are integers and within the valid
3189 // ranges.
3190 if (Fields.size() > 1) {
3191 bool FiveFields = Fields.size() == 5;
3192
3193 bool ValidString = true;
3194 if (IsARMBuiltin) {
3195 ValidString &= Fields[0].startswith_lower("cp") ||
3196 Fields[0].startswith_lower("p");
3197 if (ValidString)
3198 Fields[0] =
3199 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
3200
3201 ValidString &= Fields[2].startswith_lower("c");
3202 if (ValidString)
3203 Fields[2] = Fields[2].drop_front(1);
3204
3205 if (FiveFields) {
3206 ValidString &= Fields[3].startswith_lower("c");
3207 if (ValidString)
3208 Fields[3] = Fields[3].drop_front(1);
3209 }
3210 }
3211
3212 SmallVector<int, 5> Ranges;
3213 if (FiveFields)
3214 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 7, 15, 15});
3215 else
3216 Ranges.append({15, 7, 15});
3217
3218 for (unsigned i=0; i<Fields.size(); ++i) {
3219 int IntField;
3220 ValidString &= !Fields[i].getAsInteger(10, IntField);
3221 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
3222 }
3223
3224 if (!ValidString)
3225 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
3226 << Arg->getSourceRange();
3227
3228 } else if (IsAArch64Builtin && Fields.size() == 1) {
3229 // If the register name is one of those that appear in the condition below
3230 // and the special register builtin being used is one of the write builtins,
3231 // then we require that the argument provided for writing to the register
3232 // is an integer constant expression. This is because it will be lowered to
3233 // an MSR (immediate) instruction, so we need to know the immediate at
3234 // compile time.
3235 if (TheCall->getNumArgs() != 2)
3236 return false;
3237
3238 std::string RegLower = Reg.lower();
3239 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
3240 RegLower != "pan" && RegLower != "uao")
3241 return false;
3242
3243 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
3244 }
3245
3246 return false;
3247}
3248
Eli Friedmanc97d0142009-05-03 06:04:26 +00003249/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Joerg Sonnenberger27173282015-03-11 23:46:32 +00003250/// This checks that the target supports __builtin_longjmp and
3251/// that val is a constant 1.
Eli Friedmaneed8ad22009-05-03 04:46:36 +00003252bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Joerg Sonnenberger27173282015-03-11 23:46:32 +00003253 if (!Context.getTargetInfo().hasSjLjLowering())
3254 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
3255 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
3256
Eli Friedmaneed8ad22009-05-03 04:46:36 +00003257 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00003258 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00003259
Eric Christopher8d0c6212010-04-17 02:26:23 +00003260 // TODO: This is less than ideal. Overload this to take a value.
3261 if (SemaBuiltinConstantArg(TheCall, 1, Result))
3262 return true;
3263
3264 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00003265 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
3266 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
3267
3268 return false;
3269}
3270
Joerg Sonnenberger27173282015-03-11 23:46:32 +00003271/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
3272/// This checks that the target supports __builtin_setjmp.
3273bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
3274 if (!Context.getTargetInfo().hasSjLjLowering())
3275 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
3276 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
3277 return false;
3278}
3279
Richard Smithd7293d72013-08-05 18:49:43 +00003280namespace {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003281class UncoveredArgHandler {
3282 enum { Unknown = -1, AllCovered = -2 };
3283 signed FirstUncoveredArg;
3284 SmallVector<const Expr *, 4> DiagnosticExprs;
3285
3286public:
3287 UncoveredArgHandler() : FirstUncoveredArg(Unknown) { }
3288
3289 bool hasUncoveredArg() const {
3290 return (FirstUncoveredArg >= 0);
3291 }
3292
3293 unsigned getUncoveredArg() const {
3294 assert(hasUncoveredArg() && "no uncovered argument");
3295 return FirstUncoveredArg;
3296 }
3297
3298 void setAllCovered() {
3299 // A string has been found with all arguments covered, so clear out
3300 // the diagnostics.
3301 DiagnosticExprs.clear();
3302 FirstUncoveredArg = AllCovered;
3303 }
3304
3305 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
3306 assert(NewFirstUncoveredArg >= 0 && "Outside range");
3307
3308 // Don't update if a previous string covers all arguments.
3309 if (FirstUncoveredArg == AllCovered)
3310 return;
3311
3312 // UncoveredArgHandler tracks the highest uncovered argument index
3313 // and with it all the strings that match this index.
3314 if (NewFirstUncoveredArg == FirstUncoveredArg)
3315 DiagnosticExprs.push_back(StrExpr);
3316 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
3317 DiagnosticExprs.clear();
3318 DiagnosticExprs.push_back(StrExpr);
3319 FirstUncoveredArg = NewFirstUncoveredArg;
3320 }
3321 }
3322
3323 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
3324};
3325
Richard Smithd7293d72013-08-05 18:49:43 +00003326enum StringLiteralCheckType {
3327 SLCT_NotALiteral,
3328 SLCT_UncheckedLiteral,
3329 SLCT_CheckedLiteral
3330};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00003331} // end anonymous namespace
Richard Smithd7293d72013-08-05 18:49:43 +00003332
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00003333static void CheckFormatString(Sema &S, const StringLiteral *FExpr,
3334 const Expr *OrigFormatExpr,
3335 ArrayRef<const Expr *> Args,
3336 bool HasVAListArg, unsigned format_idx,
3337 unsigned firstDataArg,
3338 Sema::FormatStringType Type,
3339 bool inFunctionCall,
3340 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003341 llvm::SmallBitVector &CheckedVarArgs,
3342 UncoveredArgHandler &UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00003343
Richard Smith55ce3522012-06-25 20:30:08 +00003344// Determine if an expression is a string literal or constant string.
3345// If this function returns false on the arguments to a function expecting a
3346// format string, we will usually need to emit a warning.
3347// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00003348static StringLiteralCheckType
3349checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
3350 bool HasVAListArg, unsigned format_idx,
3351 unsigned firstDataArg, Sema::FormatStringType Type,
3352 Sema::VariadicCallType CallType, bool InFunctionCall,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003353 llvm::SmallBitVector &CheckedVarArgs,
3354 UncoveredArgHandler &UncoveredArg) {
Ted Kremenek808829352010-09-09 03:51:39 +00003355 tryAgain:
Douglas Gregorc25f7662009-05-19 22:10:17 +00003356 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00003357 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003358
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003359 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00003360
Richard Smithd7293d72013-08-05 18:49:43 +00003361 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00003362 // Technically -Wformat-nonliteral does not warn about this case.
3363 // The behavior of printf and friends in this case is implementation
3364 // dependent. Ideally if the format string cannot be null then
3365 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00003366 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00003367
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003368 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00003369 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003370 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00003371 // The expression is a literal if both sub-expressions were, and it was
3372 // completely checked only if both sub-expressions were checked.
3373 const AbstractConditionalOperator *C =
3374 cast<AbstractConditionalOperator>(E);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003375
3376 // Determine whether it is necessary to check both sub-expressions, for
3377 // example, because the condition expression is a constant that can be
3378 // evaluated at compile time.
3379 bool CheckLeft = true, CheckRight = true;
3380
3381 bool Cond;
3382 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
3383 if (Cond)
3384 CheckRight = false;
3385 else
3386 CheckLeft = false;
3387 }
3388
3389 StringLiteralCheckType Left;
3390 if (!CheckLeft)
3391 Left = SLCT_UncheckedLiteral;
3392 else {
3393 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
3394 HasVAListArg, format_idx, firstDataArg,
3395 Type, CallType, InFunctionCall,
3396 CheckedVarArgs, UncoveredArg);
3397 if (Left == SLCT_NotALiteral || !CheckRight)
3398 return Left;
3399 }
3400
Richard Smith55ce3522012-06-25 20:30:08 +00003401 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00003402 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003403 HasVAListArg, format_idx, firstDataArg,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003404 Type, CallType, InFunctionCall, CheckedVarArgs,
3405 UncoveredArg);
3406
3407 return (CheckLeft && Left < Right) ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003408 }
3409
3410 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00003411 E = cast<ImplicitCastExpr>(E)->getSubExpr();
3412 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003413 }
3414
John McCallc07a0c72011-02-17 10:25:35 +00003415 case Stmt::OpaqueValueExprClass:
3416 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
3417 E = src;
3418 goto tryAgain;
3419 }
Richard Smith55ce3522012-06-25 20:30:08 +00003420 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00003421
Ted Kremeneka8890832011-02-24 23:03:04 +00003422 case Stmt::PredefinedExprClass:
3423 // While __func__, etc., are technically not string literals, they
3424 // cannot contain format specifiers and thus are not a security
3425 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00003426 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00003427
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003428 case Stmt::DeclRefExprClass: {
3429 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00003430
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003431 // As an exception, do not flag errors for variables binding to
3432 // const string literals.
3433 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
3434 bool isConstant = false;
3435 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003436
Richard Smithd7293d72013-08-05 18:49:43 +00003437 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
3438 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00003439 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00003440 isConstant = T.isConstant(S.Context) &&
3441 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00003442 } else if (T->isObjCObjectPointerType()) {
3443 // In ObjC, there is usually no "const ObjectPointer" type,
3444 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00003445 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003446 }
Mike Stump11289f42009-09-09 15:08:12 +00003447
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003448 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00003449 if (const Expr *Init = VD->getAnyInitializer()) {
3450 // Look through initializers like const char c[] = { "foo" }
3451 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
3452 if (InitList->isStringLiteralInit())
3453 Init = InitList->getInit(0)->IgnoreParenImpCasts();
3454 }
Richard Smithd7293d72013-08-05 18:49:43 +00003455 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003456 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003457 firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003458 /*InFunctionCall*/false, CheckedVarArgs,
3459 UncoveredArg);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00003460 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003461 }
Mike Stump11289f42009-09-09 15:08:12 +00003462
Anders Carlssonb012ca92009-06-28 19:55:58 +00003463 // For vprintf* functions (i.e., HasVAListArg==true), we add a
3464 // special check to see if the format string is a function parameter
3465 // of the function calling the printf function. If the function
3466 // has an attribute indicating it is a printf-like function, then we
3467 // should suppress warnings concerning non-literals being used in a call
3468 // to a vprintf function. For example:
3469 //
3470 // void
3471 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
3472 // va_list ap;
3473 // va_start(ap, fmt);
3474 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
3475 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00003476 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00003477 if (HasVAListArg) {
3478 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
3479 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
3480 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00003481 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00003482 // adjust for implicit parameter
3483 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
3484 if (MD->isInstance())
3485 ++PVIndex;
3486 // We also check if the formats are compatible.
3487 // We can't pass a 'scanf' string to a 'printf' function.
3488 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00003489 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00003490 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00003491 }
3492 }
3493 }
3494 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003495 }
Mike Stump11289f42009-09-09 15:08:12 +00003496
Richard Smith55ce3522012-06-25 20:30:08 +00003497 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003498 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003499
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00003500 case Stmt::CallExprClass:
3501 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00003502 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00003503 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
3504 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
3505 unsigned ArgIndex = FA->getFormatIdx();
3506 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
3507 if (MD->isInstance())
3508 --ArgIndex;
3509 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00003510
Richard Smithd7293d72013-08-05 18:49:43 +00003511 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003512 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00003513 Type, CallType, InFunctionCall,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003514 CheckedVarArgs, UncoveredArg);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003515 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
3516 unsigned BuiltinID = FD->getBuiltinID();
3517 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
3518 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
3519 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00003520 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003521 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003522 firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003523 InFunctionCall, CheckedVarArgs,
3524 UncoveredArg);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003525 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00003526 }
3527 }
Mike Stump11289f42009-09-09 15:08:12 +00003528
Richard Smith55ce3522012-06-25 20:30:08 +00003529 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00003530 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003531 case Stmt::ObjCStringLiteralClass:
3532 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00003533 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003534
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003535 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003536 StrE = ObjCFExpr->getString();
3537 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003538 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00003539
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003540 if (StrE) {
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00003541 CheckFormatString(S, StrE, E, Args, HasVAListArg, format_idx,
3542 firstDataArg, Type, InFunctionCall, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003543 CheckedVarArgs, UncoveredArg);
Richard Smith55ce3522012-06-25 20:30:08 +00003544 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003545 }
Mike Stump11289f42009-09-09 15:08:12 +00003546
Richard Smith55ce3522012-06-25 20:30:08 +00003547 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003548 }
Mike Stump11289f42009-09-09 15:08:12 +00003549
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003550 default:
Richard Smith55ce3522012-06-25 20:30:08 +00003551 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003552 }
3553}
3554
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003555Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00003556 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003557 .Case("scanf", FST_Scanf)
3558 .Cases("printf", "printf0", FST_Printf)
3559 .Cases("NSString", "CFString", FST_NSString)
3560 .Case("strftime", FST_Strftime)
3561 .Case("strfmon", FST_Strfmon)
3562 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
Dimitry Andric6b5ed342015-02-19 22:32:33 +00003563 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00003564 .Case("os_trace", FST_OSTrace)
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003565 .Default(FST_Unknown);
3566}
3567
Jordan Rose3e0ec582012-07-19 18:10:23 +00003568/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00003569/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00003570/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003571bool Sema::CheckFormatArguments(const FormatAttr *Format,
3572 ArrayRef<const Expr *> Args,
3573 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003574 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00003575 SourceLocation Loc, SourceRange Range,
3576 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00003577 FormatStringInfo FSI;
3578 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003579 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00003580 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00003581 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00003582 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003583}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00003584
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003585bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003586 bool HasVAListArg, unsigned format_idx,
3587 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003588 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00003589 SourceLocation Loc, SourceRange Range,
3590 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00003591 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003592 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003593 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00003594 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00003595 }
Mike Stump11289f42009-09-09 15:08:12 +00003596
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003597 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00003598
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003599 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00003600 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00003601 // Dynamically generated format strings are difficult to
3602 // automatically vet at compile time. Requiring that format strings
3603 // are string literals: (1) permits the checking of format strings by
3604 // the compiler and thereby (2) can practically remove the source of
3605 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00003606
Mike Stump11289f42009-09-09 15:08:12 +00003607 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00003608 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00003609 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00003610 // the same format string checking logic for both ObjC and C strings.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003611 UncoveredArgHandler UncoveredArg;
Richard Smith55ce3522012-06-25 20:30:08 +00003612 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00003613 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
3614 format_idx, firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003615 /*IsFunctionCall*/true, CheckedVarArgs,
3616 UncoveredArg);
3617
3618 // Generate a diagnostic where an uncovered argument is detected.
3619 if (UncoveredArg.hasUncoveredArg()) {
3620 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
3621 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
3622 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
3623 }
3624
Richard Smith55ce3522012-06-25 20:30:08 +00003625 if (CT != SLCT_NotALiteral)
3626 // Literal format string found, check done!
3627 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00003628
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00003629 // Strftime is particular as it always uses a single 'time' argument,
3630 // so it is safe to pass a non-literal string.
3631 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00003632 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00003633
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00003634 // Do not emit diag when the string param is a macro expansion and the
3635 // format is either NSString or CFString. This is a hack to prevent
3636 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
3637 // which are usually used in place of NS and CF string literals.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00003638 SourceLocation FormatLoc = Args[format_idx]->getLocStart();
3639 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
Richard Smith55ce3522012-06-25 20:30:08 +00003640 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00003641
Chris Lattnercc5d1c22009-04-29 04:59:47 +00003642 // If there are no arguments specified, warn with -Wformat-security, otherwise
3643 // warn only with -Wformat-nonliteral.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00003644 if (Args.size() == firstDataArg) {
Bob Wilson57819fc2016-03-15 20:56:38 +00003645 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
3646 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00003647 switch (Type) {
3648 default:
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00003649 break;
3650 case FST_Kprintf:
3651 case FST_FreeBSDKPrintf:
3652 case FST_Printf:
Bob Wilson57819fc2016-03-15 20:56:38 +00003653 Diag(FormatLoc, diag::note_format_security_fixit)
3654 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00003655 break;
3656 case FST_NSString:
Bob Wilson57819fc2016-03-15 20:56:38 +00003657 Diag(FormatLoc, diag::note_format_security_fixit)
3658 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00003659 break;
3660 }
3661 } else {
3662 Diag(FormatLoc, diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00003663 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00003664 }
Richard Smith55ce3522012-06-25 20:30:08 +00003665 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003666}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00003667
Ted Kremenekab278de2010-01-28 23:39:18 +00003668namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00003669class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
3670protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00003671 Sema &S;
3672 const StringLiteral *FExpr;
3673 const Expr *OrigFormatExpr;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00003674 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00003675 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00003676 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00003677 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003678 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00003679 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00003680 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00003681 bool usesPositionalArgs;
3682 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00003683 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00003684 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00003685 llvm::SmallBitVector &CheckedVarArgs;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003686 UncoveredArgHandler &UncoveredArg;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00003687
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003688public:
Ted Kremenek02087932010-07-16 02:11:22 +00003689 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek4d745dd2010-03-25 03:59:12 +00003690 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003691 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003692 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003693 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003694 Sema::VariadicCallType callType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003695 llvm::SmallBitVector &CheckedVarArgs,
3696 UncoveredArgHandler &UncoveredArg)
Ted Kremenekab278de2010-01-28 23:39:18 +00003697 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003698 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
3699 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003700 Args(Args), FormatIdx(formatIdx),
Richard Trieu03cf7b72011-10-28 00:41:25 +00003701 usesPositionalArgs(false), atFirstArg(true),
Richard Smithd7293d72013-08-05 18:49:43 +00003702 inFunctionCall(inFunctionCall), CallType(callType),
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003703 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
Richard Smithd7293d72013-08-05 18:49:43 +00003704 CoveredArgs.resize(numDataArgs);
3705 CoveredArgs.reset();
3706 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003707
Ted Kremenek019d2242010-01-29 01:50:07 +00003708 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003709
Ted Kremenek02087932010-07-16 02:11:22 +00003710 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003711 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003712
Jordan Rose92303592012-09-08 04:00:03 +00003713 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00003714 const analyze_format_string::FormatSpecifier &FS,
3715 const analyze_format_string::ConversionSpecifier &CS,
3716 const char *startSpecifier, unsigned specifierLen,
3717 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00003718
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003719 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00003720 const analyze_format_string::FormatSpecifier &FS,
3721 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003722
3723 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00003724 const analyze_format_string::ConversionSpecifier &CS,
3725 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003726
Craig Toppere14c0f82014-03-12 04:55:44 +00003727 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00003728
Craig Toppere14c0f82014-03-12 04:55:44 +00003729 void HandleInvalidPosition(const char *startSpecifier,
3730 unsigned specifierLen,
3731 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00003732
Craig Toppere14c0f82014-03-12 04:55:44 +00003733 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00003734
Craig Toppere14c0f82014-03-12 04:55:44 +00003735 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003736
Richard Trieu03cf7b72011-10-28 00:41:25 +00003737 template <typename Range>
3738 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
3739 const Expr *ArgumentExpr,
3740 PartialDiagnostic PDiag,
3741 SourceLocation StringLoc,
3742 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00003743 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00003744
Ted Kremenek02087932010-07-16 02:11:22 +00003745protected:
Ted Kremenekce815422010-07-19 21:25:57 +00003746 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
3747 const char *startSpec,
3748 unsigned specifierLen,
3749 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00003750
3751 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
3752 const char *startSpec,
3753 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00003754
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003755 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00003756 CharSourceRange getSpecifierRange(const char *startSpecifier,
3757 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00003758 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003759
Ted Kremenek5739de72010-01-29 01:06:55 +00003760 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003761
3762 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
3763 const analyze_format_string::ConversionSpecifier &CS,
3764 const char *startSpecifier, unsigned specifierLen,
3765 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00003766
3767 template <typename Range>
3768 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
3769 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00003770 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00003771};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00003772} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00003773
Ted Kremenek02087932010-07-16 02:11:22 +00003774SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00003775 return OrigFormatExpr->getSourceRange();
3776}
3777
Ted Kremenek02087932010-07-16 02:11:22 +00003778CharSourceRange CheckFormatHandler::
3779getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00003780 SourceLocation Start = getLocationOfByte(startSpecifier);
3781 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
3782
3783 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003784 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00003785
3786 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003787}
3788
Ted Kremenek02087932010-07-16 02:11:22 +00003789SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003790 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremenekab278de2010-01-28 23:39:18 +00003791}
3792
Ted Kremenek02087932010-07-16 02:11:22 +00003793void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
3794 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00003795 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
3796 getLocationOfByte(startSpecifier),
3797 /*IsStringLocation*/true,
3798 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00003799}
3800
Jordan Rose92303592012-09-08 04:00:03 +00003801void CheckFormatHandler::HandleInvalidLengthModifier(
3802 const analyze_format_string::FormatSpecifier &FS,
3803 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00003804 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00003805 using namespace analyze_format_string;
3806
3807 const LengthModifier &LM = FS.getLengthModifier();
3808 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
3809
3810 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00003811 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00003812 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00003813 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00003814 getLocationOfByte(LM.getStart()),
3815 /*IsStringLocation*/true,
3816 getSpecifierRange(startSpecifier, specifierLen));
3817
3818 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
3819 << FixedLM->toString()
3820 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
3821
3822 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00003823 FixItHint Hint;
3824 if (DiagID == diag::warn_format_nonsensical_length)
3825 Hint = FixItHint::CreateRemoval(LMRange);
3826
3827 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00003828 getLocationOfByte(LM.getStart()),
3829 /*IsStringLocation*/true,
3830 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00003831 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00003832 }
3833}
3834
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003835void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00003836 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003837 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00003838 using namespace analyze_format_string;
3839
3840 const LengthModifier &LM = FS.getLengthModifier();
3841 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
3842
3843 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00003844 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00003845 if (FixedLM) {
3846 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3847 << LM.toString() << 0,
3848 getLocationOfByte(LM.getStart()),
3849 /*IsStringLocation*/true,
3850 getSpecifierRange(startSpecifier, specifierLen));
3851
3852 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
3853 << FixedLM->toString()
3854 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
3855
3856 } else {
3857 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3858 << LM.toString() << 0,
3859 getLocationOfByte(LM.getStart()),
3860 /*IsStringLocation*/true,
3861 getSpecifierRange(startSpecifier, specifierLen));
3862 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003863}
3864
3865void CheckFormatHandler::HandleNonStandardConversionSpecifier(
3866 const analyze_format_string::ConversionSpecifier &CS,
3867 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00003868 using namespace analyze_format_string;
3869
3870 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00003871 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00003872 if (FixedCS) {
3873 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3874 << CS.toString() << /*conversion specifier*/1,
3875 getLocationOfByte(CS.getStart()),
3876 /*IsStringLocation*/true,
3877 getSpecifierRange(startSpecifier, specifierLen));
3878
3879 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
3880 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
3881 << FixedCS->toString()
3882 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
3883 } else {
3884 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3885 << CS.toString() << /*conversion specifier*/1,
3886 getLocationOfByte(CS.getStart()),
3887 /*IsStringLocation*/true,
3888 getSpecifierRange(startSpecifier, specifierLen));
3889 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003890}
3891
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00003892void CheckFormatHandler::HandlePosition(const char *startPos,
3893 unsigned posLen) {
3894 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
3895 getLocationOfByte(startPos),
3896 /*IsStringLocation*/true,
3897 getSpecifierRange(startPos, posLen));
3898}
3899
Ted Kremenekd1668192010-02-27 01:41:03 +00003900void
Ted Kremenek02087932010-07-16 02:11:22 +00003901CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
3902 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003903 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
3904 << (unsigned) p,
3905 getLocationOfByte(startPos), /*IsStringLocation*/true,
3906 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00003907}
3908
Ted Kremenek02087932010-07-16 02:11:22 +00003909void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00003910 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003911 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
3912 getLocationOfByte(startPos),
3913 /*IsStringLocation*/true,
3914 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00003915}
3916
Ted Kremenek02087932010-07-16 02:11:22 +00003917void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003918 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00003919 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003920 EmitFormatDiagnostic(
3921 S.PDiag(diag::warn_printf_format_string_contains_null_char),
3922 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
3923 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00003924 }
Ted Kremenek02087932010-07-16 02:11:22 +00003925}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003926
Jordan Rose58bbe422012-07-19 18:10:08 +00003927// Note that this may return NULL if there was an error parsing or building
3928// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00003929const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003930 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00003931}
3932
3933void CheckFormatHandler::DoneProcessing() {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003934 // Does the number of data arguments exceed the number of
3935 // format conversions in the format string?
Ted Kremenek02087932010-07-16 02:11:22 +00003936 if (!HasVAListArg) {
3937 // Find any arguments that weren't covered.
3938 CoveredArgs.flip();
3939 signed notCoveredArg = CoveredArgs.find_first();
3940 if (notCoveredArg >= 0) {
3941 assert((unsigned)notCoveredArg < NumDataArgs);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003942 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
3943 } else {
3944 UncoveredArg.setAllCovered();
Ted Kremenek02087932010-07-16 02:11:22 +00003945 }
3946 }
3947}
3948
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003949void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
3950 const Expr *ArgExpr) {
3951 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
3952 "Invalid state");
3953
3954 if (!ArgExpr)
3955 return;
3956
3957 SourceLocation Loc = ArgExpr->getLocStart();
3958
3959 if (S.getSourceManager().isInSystemMacro(Loc))
3960 return;
3961
3962 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
3963 for (auto E : DiagnosticExprs)
3964 PDiag << E->getSourceRange();
3965
3966 CheckFormatHandler::EmitFormatDiagnostic(
3967 S, IsFunctionCall, DiagnosticExprs[0],
3968 PDiag, Loc, /*IsStringLocation*/false,
3969 DiagnosticExprs[0]->getSourceRange());
3970}
3971
Ted Kremenekce815422010-07-19 21:25:57 +00003972bool
3973CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
3974 SourceLocation Loc,
3975 const char *startSpec,
3976 unsigned specifierLen,
3977 const char *csStart,
3978 unsigned csLen) {
Ted Kremenekce815422010-07-19 21:25:57 +00003979 bool keepGoing = true;
3980 if (argIndex < NumDataArgs) {
3981 // Consider the argument coverered, even though the specifier doesn't
3982 // make sense.
3983 CoveredArgs.set(argIndex);
3984 }
3985 else {
3986 // If argIndex exceeds the number of data arguments we
3987 // don't issue a warning because that is just a cascade of warnings (and
3988 // they may have intended '%%' anyway). We don't want to continue processing
3989 // the format string after this point, however, as we will like just get
3990 // gibberish when trying to match arguments.
3991 keepGoing = false;
3992 }
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00003993
3994 StringRef Specifier(csStart, csLen);
3995
3996 // If the specifier in non-printable, it could be the first byte of a UTF-8
3997 // sequence. In that case, print the UTF-8 code point. If not, print the byte
3998 // hex value.
3999 std::string CodePointStr;
4000 if (!llvm::sys::locale::isPrint(*csStart)) {
4001 UTF32 CodePoint;
4002 const UTF8 **B = reinterpret_cast<const UTF8 **>(&csStart);
4003 const UTF8 *E =
4004 reinterpret_cast<const UTF8 *>(csStart + csLen);
4005 ConversionResult Result =
4006 llvm::convertUTF8Sequence(B, E, &CodePoint, strictConversion);
4007
4008 if (Result != conversionOK) {
4009 unsigned char FirstChar = *csStart;
4010 CodePoint = (UTF32)FirstChar;
4011 }
4012
4013 llvm::raw_string_ostream OS(CodePointStr);
4014 if (CodePoint < 256)
4015 OS << "\\x" << llvm::format("%02x", CodePoint);
4016 else if (CodePoint <= 0xFFFF)
4017 OS << "\\u" << llvm::format("%04x", CodePoint);
4018 else
4019 OS << "\\U" << llvm::format("%08x", CodePoint);
4020 OS.flush();
4021 Specifier = CodePointStr;
4022 }
4023
4024 EmitFormatDiagnostic(
4025 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
4026 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
4027
Ted Kremenekce815422010-07-19 21:25:57 +00004028 return keepGoing;
4029}
4030
Richard Trieu03cf7b72011-10-28 00:41:25 +00004031void
4032CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
4033 const char *startSpec,
4034 unsigned specifierLen) {
4035 EmitFormatDiagnostic(
4036 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
4037 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
4038}
4039
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004040bool
4041CheckFormatHandler::CheckNumArgs(
4042 const analyze_format_string::FormatSpecifier &FS,
4043 const analyze_format_string::ConversionSpecifier &CS,
4044 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
4045
4046 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004047 PartialDiagnostic PDiag = FS.usesPositionalArg()
4048 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
4049 << (argIndex+1) << NumDataArgs)
4050 : S.PDiag(diag::warn_printf_insufficient_data_args);
4051 EmitFormatDiagnostic(
4052 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
4053 getSpecifierRange(startSpecifier, specifierLen));
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004054
4055 // Since more arguments than conversion tokens are given, by extension
4056 // all arguments are covered, so mark this as so.
4057 UncoveredArg.setAllCovered();
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004058 return false;
4059 }
4060 return true;
4061}
4062
Richard Trieu03cf7b72011-10-28 00:41:25 +00004063template<typename Range>
4064void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
4065 SourceLocation Loc,
4066 bool IsStringLocation,
4067 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00004068 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004069 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00004070 Loc, IsStringLocation, StringRange, FixIt);
4071}
4072
4073/// \brief If the format string is not within the funcion call, emit a note
4074/// so that the function call and string are in diagnostic messages.
4075///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00004076/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00004077/// call and only one diagnostic message will be produced. Otherwise, an
4078/// extra note will be emitted pointing to location of the format string.
4079///
4080/// \param ArgumentExpr the expression that is passed as the format string
4081/// argument in the function call. Used for getting locations when two
4082/// diagnostics are emitted.
4083///
4084/// \param PDiag the callee should already have provided any strings for the
4085/// diagnostic message. This function only adds locations and fixits
4086/// to diagnostics.
4087///
4088/// \param Loc primary location for diagnostic. If two diagnostics are
4089/// required, one will be at Loc and a new SourceLocation will be created for
4090/// the other one.
4091///
4092/// \param IsStringLocation if true, Loc points to the format string should be
4093/// used for the note. Otherwise, Loc points to the argument list and will
4094/// be used with PDiag.
4095///
4096/// \param StringRange some or all of the string to highlight. This is
4097/// templated so it can accept either a CharSourceRange or a SourceRange.
4098///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00004099/// \param FixIt optional fix it hint for the format string.
Richard Trieu03cf7b72011-10-28 00:41:25 +00004100template<typename Range>
4101void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
4102 const Expr *ArgumentExpr,
4103 PartialDiagnostic PDiag,
4104 SourceLocation Loc,
4105 bool IsStringLocation,
4106 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00004107 ArrayRef<FixItHint> FixIt) {
4108 if (InFunctionCall) {
4109 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
4110 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00004111 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00004112 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004113 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
4114 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00004115
4116 const Sema::SemaDiagnosticBuilder &Note =
4117 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
4118 diag::note_format_string_defined);
4119
4120 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00004121 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00004122 }
4123}
4124
Ted Kremenek02087932010-07-16 02:11:22 +00004125//===--- CHECK: Printf format string checking ------------------------------===//
4126
4127namespace {
4128class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004129 bool ObjCContext;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004130
Ted Kremenek02087932010-07-16 02:11:22 +00004131public:
4132 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
4133 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004134 unsigned numDataArgs, bool isObjC,
Ted Kremenek02087932010-07-16 02:11:22 +00004135 const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004136 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004137 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00004138 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004139 llvm::SmallBitVector &CheckedVarArgs,
4140 UncoveredArgHandler &UncoveredArg)
Richard Smithd7293d72013-08-05 18:49:43 +00004141 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
4142 numDataArgs, beg, hasVAListArg, Args,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004143 formatIdx, inFunctionCall, CallType, CheckedVarArgs,
4144 UncoveredArg),
Richard Smithd7293d72013-08-05 18:49:43 +00004145 ObjCContext(isObjC)
Jordan Rose3e0ec582012-07-19 18:10:23 +00004146 {}
4147
Ted Kremenek02087932010-07-16 02:11:22 +00004148 bool HandleInvalidPrintfConversionSpecifier(
4149 const analyze_printf::PrintfSpecifier &FS,
4150 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004151 unsigned specifierLen) override;
4152
Ted Kremenek02087932010-07-16 02:11:22 +00004153 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
4154 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004155 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00004156 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
4157 const char *StartSpecifier,
4158 unsigned SpecifierLen,
4159 const Expr *E);
4160
Ted Kremenek02087932010-07-16 02:11:22 +00004161 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
4162 const char *startSpecifier, unsigned specifierLen);
4163 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
4164 const analyze_printf::OptionalAmount &Amt,
4165 unsigned type,
4166 const char *startSpecifier, unsigned specifierLen);
4167 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
4168 const analyze_printf::OptionalFlag &flag,
4169 const char *startSpecifier, unsigned specifierLen);
4170 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
4171 const analyze_printf::OptionalFlag &ignoredFlag,
4172 const analyze_printf::OptionalFlag &flag,
4173 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004174 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00004175 const Expr *E);
Ted Kremenek2b417712015-07-02 05:39:16 +00004176
4177 void HandleEmptyObjCModifierFlag(const char *startFlag,
4178 unsigned flagLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00004179
Ted Kremenek2b417712015-07-02 05:39:16 +00004180 void HandleInvalidObjCModifierFlag(const char *startFlag,
4181 unsigned flagLen) override;
4182
4183 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
4184 const char *flagsEnd,
4185 const char *conversionPosition)
4186 override;
4187};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004188} // end anonymous namespace
Ted Kremenek02087932010-07-16 02:11:22 +00004189
4190bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
4191 const analyze_printf::PrintfSpecifier &FS,
4192 const char *startSpecifier,
4193 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004194 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00004195 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00004196
Ted Kremenekce815422010-07-19 21:25:57 +00004197 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
4198 getLocationOfByte(CS.getStart()),
4199 startSpecifier, specifierLen,
4200 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00004201}
4202
Ted Kremenek02087932010-07-16 02:11:22 +00004203bool CheckPrintfHandler::HandleAmount(
4204 const analyze_format_string::OptionalAmount &Amt,
4205 unsigned k, const char *startSpecifier,
4206 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00004207 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00004208 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00004209 unsigned argIndex = Amt.getArgIndex();
4210 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004211 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
4212 << k,
4213 getLocationOfByte(Amt.getStart()),
4214 /*IsStringLocation*/true,
4215 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00004216 // Don't do any more checking. We will just emit
4217 // spurious errors.
4218 return false;
4219 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004220
Ted Kremenek5739de72010-01-29 01:06:55 +00004221 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00004222 // Although not in conformance with C99, we also allow the argument to be
4223 // an 'unsigned int' as that is a reasonably safe case. GCC also
4224 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00004225 CoveredArgs.set(argIndex);
4226 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00004227 if (!Arg)
4228 return false;
4229
Ted Kremenek5739de72010-01-29 01:06:55 +00004230 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004231
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004232 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
4233 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004234
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004235 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004236 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004237 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00004238 << T << Arg->getSourceRange(),
4239 getLocationOfByte(Amt.getStart()),
4240 /*IsStringLocation*/true,
4241 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00004242 // Don't do any more checking. We will just emit
4243 // spurious errors.
4244 return false;
4245 }
4246 }
4247 }
4248 return true;
4249}
Ted Kremenek5739de72010-01-29 01:06:55 +00004250
Tom Careb49ec692010-06-17 19:00:27 +00004251void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00004252 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00004253 const analyze_printf::OptionalAmount &Amt,
4254 unsigned type,
4255 const char *startSpecifier,
4256 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004257 const analyze_printf::PrintfConversionSpecifier &CS =
4258 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00004259
Richard Trieu03cf7b72011-10-28 00:41:25 +00004260 FixItHint fixit =
4261 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
4262 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
4263 Amt.getConstantLength()))
4264 : FixItHint();
4265
4266 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
4267 << type << CS.toString(),
4268 getLocationOfByte(Amt.getStart()),
4269 /*IsStringLocation*/true,
4270 getSpecifierRange(startSpecifier, specifierLen),
4271 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00004272}
4273
Ted Kremenek02087932010-07-16 02:11:22 +00004274void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00004275 const analyze_printf::OptionalFlag &flag,
4276 const char *startSpecifier,
4277 unsigned specifierLen) {
4278 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004279 const analyze_printf::PrintfConversionSpecifier &CS =
4280 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00004281 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
4282 << flag.toString() << CS.toString(),
4283 getLocationOfByte(flag.getPosition()),
4284 /*IsStringLocation*/true,
4285 getSpecifierRange(startSpecifier, specifierLen),
4286 FixItHint::CreateRemoval(
4287 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00004288}
4289
4290void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00004291 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00004292 const analyze_printf::OptionalFlag &ignoredFlag,
4293 const analyze_printf::OptionalFlag &flag,
4294 const char *startSpecifier,
4295 unsigned specifierLen) {
4296 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00004297 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
4298 << ignoredFlag.toString() << flag.toString(),
4299 getLocationOfByte(ignoredFlag.getPosition()),
4300 /*IsStringLocation*/true,
4301 getSpecifierRange(startSpecifier, specifierLen),
4302 FixItHint::CreateRemoval(
4303 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00004304}
4305
Ted Kremenek2b417712015-07-02 05:39:16 +00004306// void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
4307// bool IsStringLocation, Range StringRange,
4308// ArrayRef<FixItHint> Fixit = None);
4309
4310void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
4311 unsigned flagLen) {
4312 // Warn about an empty flag.
4313 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
4314 getLocationOfByte(startFlag),
4315 /*IsStringLocation*/true,
4316 getSpecifierRange(startFlag, flagLen));
4317}
4318
4319void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
4320 unsigned flagLen) {
4321 // Warn about an invalid flag.
4322 auto Range = getSpecifierRange(startFlag, flagLen);
4323 StringRef flag(startFlag, flagLen);
4324 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
4325 getLocationOfByte(startFlag),
4326 /*IsStringLocation*/true,
4327 Range, FixItHint::CreateRemoval(Range));
4328}
4329
4330void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
4331 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
4332 // Warn about using '[...]' without a '@' conversion.
4333 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
4334 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
4335 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
4336 getLocationOfByte(conversionPosition),
4337 /*IsStringLocation*/true,
4338 Range, FixItHint::CreateRemoval(Range));
4339}
4340
Richard Smith55ce3522012-06-25 20:30:08 +00004341// Determines if the specified is a C++ class or struct containing
4342// a member with the specified name and kind (e.g. a CXXMethodDecl named
4343// "c_str()").
4344template<typename MemberKind>
4345static llvm::SmallPtrSet<MemberKind*, 1>
4346CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
4347 const RecordType *RT = Ty->getAs<RecordType>();
4348 llvm::SmallPtrSet<MemberKind*, 1> Results;
4349
4350 if (!RT)
4351 return Results;
4352 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00004353 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00004354 return Results;
4355
Alp Tokerb6cc5922014-05-03 03:45:55 +00004356 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00004357 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00004358 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00004359
4360 // We just need to include all members of the right kind turned up by the
4361 // filter, at this point.
4362 if (S.LookupQualifiedName(R, RT->getDecl()))
4363 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
4364 NamedDecl *decl = (*I)->getUnderlyingDecl();
4365 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
4366 Results.insert(FK);
4367 }
4368 return Results;
4369}
4370
Richard Smith2868a732014-02-28 01:36:39 +00004371/// Check if we could call '.c_str()' on an object.
4372///
4373/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
4374/// allow the call, or if it would be ambiguous).
4375bool Sema::hasCStrMethod(const Expr *E) {
4376 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
4377 MethodSet Results =
4378 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
4379 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
4380 MI != ME; ++MI)
4381 if ((*MI)->getMinRequiredArguments() == 0)
4382 return true;
4383 return false;
4384}
4385
Richard Smith55ce3522012-06-25 20:30:08 +00004386// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004387// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00004388// Returns true when a c_str() conversion method is found.
4389bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00004390 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00004391 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
4392
4393 MethodSet Results =
4394 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
4395
4396 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
4397 MI != ME; ++MI) {
4398 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00004399 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00004400 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00004401 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00004402 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00004403 S.Diag(E->getLocStart(), diag::note_printf_c_str)
4404 << "c_str()"
4405 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
4406 return true;
4407 }
4408 }
4409
4410 return false;
4411}
4412
Ted Kremenekab278de2010-01-28 23:39:18 +00004413bool
Ted Kremenek02087932010-07-16 02:11:22 +00004414CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00004415 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00004416 const char *startSpecifier,
4417 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004418 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00004419 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004420 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00004421
Ted Kremenek6cd69422010-07-19 22:01:06 +00004422 if (FS.consumesDataArgument()) {
4423 if (atFirstArg) {
4424 atFirstArg = false;
4425 usesPositionalArgs = FS.usesPositionalArg();
4426 }
4427 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004428 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
4429 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00004430 return false;
4431 }
Ted Kremenek5739de72010-01-29 01:06:55 +00004432 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004433
Ted Kremenekd1668192010-02-27 01:41:03 +00004434 // First check if the field width, precision, and conversion specifier
4435 // have matching data arguments.
4436 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
4437 startSpecifier, specifierLen)) {
4438 return false;
4439 }
4440
4441 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
4442 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00004443 return false;
4444 }
4445
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004446 if (!CS.consumesDataArgument()) {
4447 // FIXME: Technically specifying a precision or field width here
4448 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00004449 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004450 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004451
Ted Kremenek4a49d982010-02-26 19:18:41 +00004452 // Consume the argument.
4453 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00004454 if (argIndex < NumDataArgs) {
4455 // The check to see if the argIndex is valid will come later.
4456 // We set the bit here because we may exit early from this
4457 // function if we encounter some other error.
4458 CoveredArgs.set(argIndex);
4459 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00004460
Dimitry Andric6b5ed342015-02-19 22:32:33 +00004461 // FreeBSD kernel extensions.
4462 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
4463 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
4464 // We need at least two arguments.
4465 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
4466 return false;
4467
4468 // Claim the second argument.
4469 CoveredArgs.set(argIndex + 1);
4470
4471 // Type check the first argument (int for %b, pointer for %D)
4472 const Expr *Ex = getDataArg(argIndex);
4473 const analyze_printf::ArgType &AT =
4474 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
4475 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
4476 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
4477 EmitFormatDiagnostic(
4478 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4479 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
4480 << false << Ex->getSourceRange(),
4481 Ex->getLocStart(), /*IsStringLocation*/false,
4482 getSpecifierRange(startSpecifier, specifierLen));
4483
4484 // Type check the second argument (char * for both %b and %D)
4485 Ex = getDataArg(argIndex + 1);
4486 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
4487 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
4488 EmitFormatDiagnostic(
4489 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4490 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
4491 << false << Ex->getSourceRange(),
4492 Ex->getLocStart(), /*IsStringLocation*/false,
4493 getSpecifierRange(startSpecifier, specifierLen));
4494
4495 return true;
4496 }
4497
Ted Kremenek4a49d982010-02-26 19:18:41 +00004498 // Check for using an Objective-C specific conversion specifier
4499 // in a non-ObjC literal.
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004500 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00004501 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
4502 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00004503 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004504
Tom Careb49ec692010-06-17 19:00:27 +00004505 // Check for invalid use of field width
4506 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00004507 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00004508 startSpecifier, specifierLen);
4509 }
4510
4511 // Check for invalid use of precision
4512 if (!FS.hasValidPrecision()) {
4513 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
4514 startSpecifier, specifierLen);
4515 }
4516
4517 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00004518 if (!FS.hasValidThousandsGroupingPrefix())
4519 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00004520 if (!FS.hasValidLeadingZeros())
4521 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
4522 if (!FS.hasValidPlusPrefix())
4523 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00004524 if (!FS.hasValidSpacePrefix())
4525 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00004526 if (!FS.hasValidAlternativeForm())
4527 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
4528 if (!FS.hasValidLeftJustified())
4529 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
4530
4531 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00004532 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
4533 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
4534 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00004535 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
4536 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
4537 startSpecifier, specifierLen);
4538
4539 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00004540 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00004541 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4542 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00004543 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004544 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00004545 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004546 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4547 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00004548
Jordan Rose92303592012-09-08 04:00:03 +00004549 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
4550 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
4551
Ted Kremenek9fcd8302010-01-29 01:43:31 +00004552 // The remaining checks depend on the data arguments.
4553 if (HasVAListArg)
4554 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004555
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004556 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00004557 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004558
Jordan Rose58bbe422012-07-19 18:10:08 +00004559 const Expr *Arg = getDataArg(argIndex);
4560 if (!Arg)
4561 return true;
4562
4563 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00004564}
4565
Jordan Roseaee34382012-09-05 22:56:26 +00004566static bool requiresParensToAddCast(const Expr *E) {
4567 // FIXME: We should have a general way to reason about operator
4568 // precedence and whether parens are actually needed here.
4569 // Take care of a few common cases where they aren't.
4570 const Expr *Inside = E->IgnoreImpCasts();
4571 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
4572 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
4573
4574 switch (Inside->getStmtClass()) {
4575 case Stmt::ArraySubscriptExprClass:
4576 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004577 case Stmt::CharacterLiteralClass:
4578 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004579 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004580 case Stmt::FloatingLiteralClass:
4581 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004582 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004583 case Stmt::ObjCArrayLiteralClass:
4584 case Stmt::ObjCBoolLiteralExprClass:
4585 case Stmt::ObjCBoxedExprClass:
4586 case Stmt::ObjCDictionaryLiteralClass:
4587 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004588 case Stmt::ObjCIvarRefExprClass:
4589 case Stmt::ObjCMessageExprClass:
4590 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004591 case Stmt::ObjCStringLiteralClass:
4592 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004593 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004594 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004595 case Stmt::UnaryOperatorClass:
4596 return false;
4597 default:
4598 return true;
4599 }
4600}
4601
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004602static std::pair<QualType, StringRef>
4603shouldNotPrintDirectly(const ASTContext &Context,
4604 QualType IntendedTy,
4605 const Expr *E) {
4606 // Use a 'while' to peel off layers of typedefs.
4607 QualType TyTy = IntendedTy;
4608 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
4609 StringRef Name = UserTy->getDecl()->getName();
4610 QualType CastTy = llvm::StringSwitch<QualType>(Name)
4611 .Case("NSInteger", Context.LongTy)
4612 .Case("NSUInteger", Context.UnsignedLongTy)
4613 .Case("SInt32", Context.IntTy)
4614 .Case("UInt32", Context.UnsignedIntTy)
4615 .Default(QualType());
4616
4617 if (!CastTy.isNull())
4618 return std::make_pair(CastTy, Name);
4619
4620 TyTy = UserTy->desugar();
4621 }
4622
4623 // Strip parens if necessary.
4624 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
4625 return shouldNotPrintDirectly(Context,
4626 PE->getSubExpr()->getType(),
4627 PE->getSubExpr());
4628
4629 // If this is a conditional expression, then its result type is constructed
4630 // via usual arithmetic conversions and thus there might be no necessary
4631 // typedef sugar there. Recurse to operands to check for NSInteger &
4632 // Co. usage condition.
4633 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
4634 QualType TrueTy, FalseTy;
4635 StringRef TrueName, FalseName;
4636
4637 std::tie(TrueTy, TrueName) =
4638 shouldNotPrintDirectly(Context,
4639 CO->getTrueExpr()->getType(),
4640 CO->getTrueExpr());
4641 std::tie(FalseTy, FalseName) =
4642 shouldNotPrintDirectly(Context,
4643 CO->getFalseExpr()->getType(),
4644 CO->getFalseExpr());
4645
4646 if (TrueTy == FalseTy)
4647 return std::make_pair(TrueTy, TrueName);
4648 else if (TrueTy.isNull())
4649 return std::make_pair(FalseTy, FalseName);
4650 else if (FalseTy.isNull())
4651 return std::make_pair(TrueTy, TrueName);
4652 }
4653
4654 return std::make_pair(QualType(), StringRef());
4655}
4656
Richard Smith55ce3522012-06-25 20:30:08 +00004657bool
4658CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
4659 const char *StartSpecifier,
4660 unsigned SpecifierLen,
4661 const Expr *E) {
4662 using namespace analyze_format_string;
4663 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004664 // Now type check the data expression that matches the
4665 // format specifier.
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004666 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
4667 ObjCContext);
Jordan Rose22b74712012-09-05 22:56:19 +00004668 if (!AT.isValid())
4669 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00004670
Jordan Rose598ec092012-12-05 18:44:40 +00004671 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00004672 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
4673 ExprTy = TET->getUnderlyingExpr()->getType();
4674 }
4675
Seth Cantrellb4802962015-03-04 03:12:10 +00004676 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
4677
4678 if (match == analyze_printf::ArgType::Match) {
Jordan Rose22b74712012-09-05 22:56:19 +00004679 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00004680 }
Jordan Rose98709982012-06-04 22:48:57 +00004681
Jordan Rose22b74712012-09-05 22:56:19 +00004682 // Look through argument promotions for our error message's reported type.
4683 // This includes the integral and floating promotions, but excludes array
4684 // and function pointer decay; seeing that an argument intended to be a
4685 // string has type 'char [6]' is probably more confusing than 'char *'.
4686 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
4687 if (ICE->getCastKind() == CK_IntegralCast ||
4688 ICE->getCastKind() == CK_FloatingCast) {
4689 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00004690 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00004691
4692 // Check if we didn't match because of an implicit cast from a 'char'
4693 // or 'short' to an 'int'. This is done because printf is a varargs
4694 // function.
4695 if (ICE->getType() == S.Context.IntTy ||
4696 ICE->getType() == S.Context.UnsignedIntTy) {
4697 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00004698 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00004699 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00004700 }
Jordan Rose98709982012-06-04 22:48:57 +00004701 }
Jordan Rose598ec092012-12-05 18:44:40 +00004702 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
4703 // Special case for 'a', which has type 'int' in C.
4704 // Note, however, that we do /not/ want to treat multibyte constants like
4705 // 'MooV' as characters! This form is deprecated but still exists.
4706 if (ExprTy == S.Context.IntTy)
4707 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
4708 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00004709 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004710
Jordan Rosebc53ed12014-05-31 04:12:14 +00004711 // Look through enums to their underlying type.
4712 bool IsEnum = false;
4713 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
4714 ExprTy = EnumTy->getDecl()->getIntegerType();
4715 IsEnum = true;
4716 }
4717
Jordan Rose0e5badd2012-12-05 18:44:49 +00004718 // %C in an Objective-C context prints a unichar, not a wchar_t.
4719 // If the argument is an integer of some kind, believe the %C and suggest
4720 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00004721 QualType IntendedTy = ExprTy;
Jordan Rose0e5badd2012-12-05 18:44:49 +00004722 if (ObjCContext &&
4723 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
4724 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
4725 !ExprTy->isCharType()) {
4726 // 'unichar' is defined as a typedef of unsigned short, but we should
4727 // prefer using the typedef if it is visible.
4728 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00004729
4730 // While we are here, check if the value is an IntegerLiteral that happens
4731 // to be within the valid range.
4732 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
4733 const llvm::APInt &V = IL->getValue();
4734 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
4735 return true;
4736 }
4737
Jordan Rose0e5badd2012-12-05 18:44:49 +00004738 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
4739 Sema::LookupOrdinaryName);
4740 if (S.LookupName(Result, S.getCurScope())) {
4741 NamedDecl *ND = Result.getFoundDecl();
4742 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
4743 if (TD->getUnderlyingType() == IntendedTy)
4744 IntendedTy = S.Context.getTypedefType(TD);
4745 }
4746 }
4747 }
4748
4749 // Special-case some of Darwin's platform-independence types by suggesting
4750 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004751 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00004752 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004753 QualType CastTy;
4754 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
4755 if (!CastTy.isNull()) {
4756 IntendedTy = CastTy;
4757 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00004758 }
4759 }
4760
Jordan Rose22b74712012-09-05 22:56:19 +00004761 // We may be able to offer a FixItHint if it is a supported type.
4762 PrintfSpecifier fixedFS = FS;
Jordan Roseaee34382012-09-05 22:56:26 +00004763 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose22b74712012-09-05 22:56:19 +00004764 S.Context, ObjCContext);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004765
Jordan Rose22b74712012-09-05 22:56:19 +00004766 if (success) {
4767 // Get the fix string from the fixed format specifier
4768 SmallString<16> buf;
4769 llvm::raw_svector_ostream os(buf);
4770 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004771
Jordan Roseaee34382012-09-05 22:56:26 +00004772 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
4773
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004774 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Daniel Jasperad8d8492015-03-04 14:18:20 +00004775 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4776 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
4777 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4778 }
Jordan Rose0e5badd2012-12-05 18:44:49 +00004779 // In this case, the specifier is wrong and should be changed to match
4780 // the argument.
Daniel Jasperad8d8492015-03-04 14:18:20 +00004781 EmitFormatDiagnostic(S.PDiag(diag)
4782 << AT.getRepresentativeTypeName(S.Context)
4783 << IntendedTy << IsEnum << E->getSourceRange(),
4784 E->getLocStart(),
4785 /*IsStringLocation*/ false, SpecRange,
4786 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00004787 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00004788 // The canonical type for formatting this value is different from the
4789 // actual type of the expression. (This occurs, for example, with Darwin's
4790 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
4791 // should be printed as 'long' for 64-bit compatibility.)
4792 // Rather than emitting a normal format/argument mismatch, we want to
4793 // add a cast to the recommended type (and correct the format string
4794 // if necessary).
4795 SmallString<16> CastBuf;
4796 llvm::raw_svector_ostream CastFix(CastBuf);
4797 CastFix << "(";
4798 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
4799 CastFix << ")";
4800
4801 SmallVector<FixItHint,4> Hints;
4802 if (!AT.matchesType(S.Context, IntendedTy))
4803 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
4804
4805 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
4806 // If there's already a cast present, just replace it.
4807 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
4808 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
4809
4810 } else if (!requiresParensToAddCast(E)) {
4811 // If the expression has high enough precedence,
4812 // just write the C-style cast.
4813 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
4814 CastFix.str()));
4815 } else {
4816 // Otherwise, add parens around the expression as well as the cast.
4817 CastFix << "(";
4818 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
4819 CastFix.str()));
4820
Alp Tokerb6cc5922014-05-03 03:45:55 +00004821 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00004822 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
4823 }
4824
Jordan Rose0e5badd2012-12-05 18:44:49 +00004825 if (ShouldNotPrintDirectly) {
4826 // The expression has a type that should not be printed directly.
4827 // We extract the name from the typedef because we don't want to show
4828 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004829 StringRef Name;
4830 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
4831 Name = TypedefTy->getDecl()->getName();
4832 else
4833 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00004834 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00004835 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00004836 << E->getSourceRange(),
4837 E->getLocStart(), /*IsStringLocation=*/false,
4838 SpecRange, Hints);
4839 } else {
4840 // In this case, the expression could be printed using a different
4841 // specifier, but we've decided that the specifier is probably correct
4842 // and we should cast instead. Just use the normal warning message.
4843 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00004844 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4845 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00004846 << E->getSourceRange(),
4847 E->getLocStart(), /*IsStringLocation*/false,
4848 SpecRange, Hints);
4849 }
Jordan Roseaee34382012-09-05 22:56:26 +00004850 }
Jordan Rose22b74712012-09-05 22:56:19 +00004851 } else {
4852 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
4853 SpecifierLen);
4854 // Since the warning for passing non-POD types to variadic functions
4855 // was deferred until now, we emit a warning for non-POD
4856 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00004857 switch (S.isValidVarArgType(ExprTy)) {
4858 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00004859 case Sema::VAK_ValidInCXX11: {
4860 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4861 if (match == analyze_printf::ArgType::NoMatchPedantic) {
4862 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4863 }
Richard Smithd7293d72013-08-05 18:49:43 +00004864
Seth Cantrellb4802962015-03-04 03:12:10 +00004865 EmitFormatDiagnostic(
4866 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
4867 << IsEnum << CSR << E->getSourceRange(),
4868 E->getLocStart(), /*IsStringLocation*/ false, CSR);
4869 break;
4870 }
Richard Smithd7293d72013-08-05 18:49:43 +00004871 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00004872 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00004873 EmitFormatDiagnostic(
4874 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004875 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00004876 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00004877 << CallType
4878 << AT.getRepresentativeTypeName(S.Context)
4879 << CSR
4880 << E->getSourceRange(),
4881 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00004882 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00004883 break;
4884
4885 case Sema::VAK_Invalid:
4886 if (ExprTy->isObjCObjectType())
4887 EmitFormatDiagnostic(
4888 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
4889 << S.getLangOpts().CPlusPlus11
4890 << ExprTy
4891 << CallType
4892 << AT.getRepresentativeTypeName(S.Context)
4893 << CSR
4894 << E->getSourceRange(),
4895 E->getLocStart(), /*IsStringLocation*/false, CSR);
4896 else
4897 // FIXME: If this is an initializer list, suggest removing the braces
4898 // or inserting a cast to the target type.
4899 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
4900 << isa<InitListExpr>(E) << ExprTy << CallType
4901 << AT.getRepresentativeTypeName(S.Context)
4902 << E->getSourceRange();
4903 break;
4904 }
4905
4906 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
4907 "format string specifier index out of range");
4908 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004909 }
4910
Ted Kremenekab278de2010-01-28 23:39:18 +00004911 return true;
4912}
4913
Ted Kremenek02087932010-07-16 02:11:22 +00004914//===--- CHECK: Scanf format string checking ------------------------------===//
4915
4916namespace {
4917class CheckScanfHandler : public CheckFormatHandler {
4918public:
4919 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
4920 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004921 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004922 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004923 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00004924 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004925 llvm::SmallBitVector &CheckedVarArgs,
4926 UncoveredArgHandler &UncoveredArg)
Richard Smithd7293d72013-08-05 18:49:43 +00004927 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
4928 numDataArgs, beg, hasVAListArg,
4929 Args, formatIdx, inFunctionCall, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004930 CheckedVarArgs, UncoveredArg)
Jordan Rose3e0ec582012-07-19 18:10:23 +00004931 {}
Ted Kremenek02087932010-07-16 02:11:22 +00004932
4933 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
4934 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004935 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00004936
4937 bool HandleInvalidScanfConversionSpecifier(
4938 const analyze_scanf::ScanfSpecifier &FS,
4939 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004940 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00004941
Craig Toppere14c0f82014-03-12 04:55:44 +00004942 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00004943};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004944} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00004945
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00004946void CheckScanfHandler::HandleIncompleteScanList(const char *start,
4947 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004948 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
4949 getLocationOfByte(end), /*IsStringLocation*/true,
4950 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00004951}
4952
Ted Kremenekce815422010-07-19 21:25:57 +00004953bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
4954 const analyze_scanf::ScanfSpecifier &FS,
4955 const char *startSpecifier,
4956 unsigned specifierLen) {
4957
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004958 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00004959 FS.getConversionSpecifier();
4960
4961 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
4962 getLocationOfByte(CS.getStart()),
4963 startSpecifier, specifierLen,
4964 CS.getStart(), CS.getLength());
4965}
4966
Ted Kremenek02087932010-07-16 02:11:22 +00004967bool CheckScanfHandler::HandleScanfSpecifier(
4968 const analyze_scanf::ScanfSpecifier &FS,
4969 const char *startSpecifier,
4970 unsigned specifierLen) {
Ted Kremenek02087932010-07-16 02:11:22 +00004971 using namespace analyze_scanf;
4972 using namespace analyze_format_string;
4973
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004974 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00004975
Ted Kremenek6cd69422010-07-19 22:01:06 +00004976 // Handle case where '%' and '*' don't consume an argument. These shouldn't
4977 // be used to decide if we are using positional arguments consistently.
4978 if (FS.consumesDataArgument()) {
4979 if (atFirstArg) {
4980 atFirstArg = false;
4981 usesPositionalArgs = FS.usesPositionalArg();
4982 }
4983 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004984 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
4985 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00004986 return false;
4987 }
Ted Kremenek02087932010-07-16 02:11:22 +00004988 }
4989
4990 // Check if the field with is non-zero.
4991 const OptionalAmount &Amt = FS.getFieldWidth();
4992 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
4993 if (Amt.getConstantAmount() == 0) {
4994 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
4995 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00004996 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
4997 getLocationOfByte(Amt.getStart()),
4998 /*IsStringLocation*/true, R,
4999 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00005000 }
5001 }
Seth Cantrellb4802962015-03-04 03:12:10 +00005002
Ted Kremenek02087932010-07-16 02:11:22 +00005003 if (!FS.consumesDataArgument()) {
5004 // FIXME: Technically specifying a precision or field width here
5005 // makes no sense. Worth issuing a warning at some point.
5006 return true;
5007 }
Seth Cantrellb4802962015-03-04 03:12:10 +00005008
Ted Kremenek02087932010-07-16 02:11:22 +00005009 // Consume the argument.
5010 unsigned argIndex = FS.getArgIndex();
5011 if (argIndex < NumDataArgs) {
5012 // The check to see if the argIndex is valid will come later.
5013 // We set the bit here because we may exit early from this
5014 // function if we encounter some other error.
5015 CoveredArgs.set(argIndex);
5016 }
Seth Cantrellb4802962015-03-04 03:12:10 +00005017
Ted Kremenek4407ea42010-07-20 20:04:47 +00005018 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00005019 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00005020 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5021 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00005022 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00005023 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00005024 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00005025 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5026 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005027
Jordan Rose92303592012-09-08 04:00:03 +00005028 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
5029 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
5030
Ted Kremenek02087932010-07-16 02:11:22 +00005031 // The remaining checks depend on the data arguments.
5032 if (HasVAListArg)
5033 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00005034
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005035 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00005036 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00005037
Hans Wennborgb1a5e092011-12-10 13:20:11 +00005038 // Check that the argument type matches the format specifier.
5039 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00005040 if (!Ex)
5041 return true;
5042
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00005043 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00005044
5045 if (!AT.isValid()) {
5046 return true;
5047 }
5048
Seth Cantrellb4802962015-03-04 03:12:10 +00005049 analyze_format_string::ArgType::MatchKind match =
5050 AT.matchesType(S.Context, Ex->getType());
Seth Cantrell79340072015-03-04 05:58:08 +00005051 if (match == analyze_format_string::ArgType::Match) {
5052 return true;
5053 }
Seth Cantrellb4802962015-03-04 03:12:10 +00005054
Seth Cantrell79340072015-03-04 05:58:08 +00005055 ScanfSpecifier fixedFS = FS;
5056 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
5057 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00005058
Seth Cantrell79340072015-03-04 05:58:08 +00005059 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
5060 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
5061 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
5062 }
Hans Wennborgb1a5e092011-12-10 13:20:11 +00005063
Seth Cantrell79340072015-03-04 05:58:08 +00005064 if (success) {
5065 // Get the fix string from the fixed format specifier.
5066 SmallString<128> buf;
5067 llvm::raw_svector_ostream os(buf);
5068 fixedFS.toString(os);
5069
5070 EmitFormatDiagnostic(
5071 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
5072 << Ex->getType() << false << Ex->getSourceRange(),
5073 Ex->getLocStart(),
5074 /*IsStringLocation*/ false,
5075 getSpecifierRange(startSpecifier, specifierLen),
5076 FixItHint::CreateReplacement(
5077 getSpecifierRange(startSpecifier, specifierLen), os.str()));
5078 } else {
5079 EmitFormatDiagnostic(S.PDiag(diag)
5080 << AT.getRepresentativeTypeName(S.Context)
5081 << Ex->getType() << false << Ex->getSourceRange(),
5082 Ex->getLocStart(),
5083 /*IsStringLocation*/ false,
5084 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00005085 }
5086
Ted Kremenek02087932010-07-16 02:11:22 +00005087 return true;
5088}
5089
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005090static void CheckFormatString(Sema &S, const StringLiteral *FExpr,
5091 const Expr *OrigFormatExpr,
5092 ArrayRef<const Expr *> Args,
5093 bool HasVAListArg, unsigned format_idx,
5094 unsigned firstDataArg,
5095 Sema::FormatStringType Type,
5096 bool inFunctionCall,
5097 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005098 llvm::SmallBitVector &CheckedVarArgs,
5099 UncoveredArgHandler &UncoveredArg) {
Ted Kremenekab278de2010-01-28 23:39:18 +00005100 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00005101 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005102 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005103 S, inFunctionCall, Args[format_idx],
5104 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00005105 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00005106 return;
5107 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005108
Ted Kremenekab278de2010-01-28 23:39:18 +00005109 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005110 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00005111 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00005112 // Account for cases where the string literal is truncated in a declaration.
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005113 const ConstantArrayType *T =
5114 S.Context.getAsConstantArrayType(FExpr->getType());
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00005115 assert(T && "String literal not of constant array type!");
5116 size_t TypeSize = T->getSize().getZExtValue();
5117 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005118 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00005119
5120 // Emit a warning if the string literal is truncated and does not contain an
5121 // embedded null character.
5122 if (TypeSize <= StrRef.size() &&
5123 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
5124 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005125 S, inFunctionCall, Args[format_idx],
5126 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00005127 FExpr->getLocStart(),
5128 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
5129 return;
5130 }
5131
Ted Kremenekab278de2010-01-28 23:39:18 +00005132 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00005133 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005134 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005135 S, inFunctionCall, Args[format_idx],
5136 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00005137 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00005138 return;
5139 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005140
5141 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
5142 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSTrace) {
5143 CheckPrintfHandler H(S, FExpr, OrigFormatExpr, firstDataArg,
5144 numDataArgs, (Type == Sema::FST_NSString ||
5145 Type == Sema::FST_OSTrace),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005146 Str, HasVAListArg, Args, format_idx,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005147 inFunctionCall, CallType, CheckedVarArgs,
5148 UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005149
Hans Wennborg23926bd2011-12-15 10:25:47 +00005150 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005151 S.getLangOpts(),
5152 S.Context.getTargetInfo(),
5153 Type == Sema::FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00005154 H.DoneProcessing();
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005155 } else if (Type == Sema::FST_Scanf) {
5156 CheckScanfHandler H(S, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005157 Str, HasVAListArg, Args, format_idx,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005158 inFunctionCall, CallType, CheckedVarArgs,
5159 UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005160
Hans Wennborg23926bd2011-12-15 10:25:47 +00005161 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005162 S.getLangOpts(),
5163 S.Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00005164 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005165 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00005166}
5167
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00005168bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
5169 // Str - The format string. NOTE: this is NOT null-terminated!
5170 StringRef StrRef = FExpr->getString();
5171 const char *Str = StrRef.data();
5172 // Account for cases where the string literal is truncated in a declaration.
5173 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
5174 assert(T && "String literal not of constant array type!");
5175 size_t TypeSize = T->getSize().getZExtValue();
5176 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
5177 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
5178 getLangOpts(),
5179 Context.getTargetInfo());
5180}
5181
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005182//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
5183
5184// Returns the related absolute value function that is larger, of 0 if one
5185// does not exist.
5186static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
5187 switch (AbsFunction) {
5188 default:
5189 return 0;
5190
5191 case Builtin::BI__builtin_abs:
5192 return Builtin::BI__builtin_labs;
5193 case Builtin::BI__builtin_labs:
5194 return Builtin::BI__builtin_llabs;
5195 case Builtin::BI__builtin_llabs:
5196 return 0;
5197
5198 case Builtin::BI__builtin_fabsf:
5199 return Builtin::BI__builtin_fabs;
5200 case Builtin::BI__builtin_fabs:
5201 return Builtin::BI__builtin_fabsl;
5202 case Builtin::BI__builtin_fabsl:
5203 return 0;
5204
5205 case Builtin::BI__builtin_cabsf:
5206 return Builtin::BI__builtin_cabs;
5207 case Builtin::BI__builtin_cabs:
5208 return Builtin::BI__builtin_cabsl;
5209 case Builtin::BI__builtin_cabsl:
5210 return 0;
5211
5212 case Builtin::BIabs:
5213 return Builtin::BIlabs;
5214 case Builtin::BIlabs:
5215 return Builtin::BIllabs;
5216 case Builtin::BIllabs:
5217 return 0;
5218
5219 case Builtin::BIfabsf:
5220 return Builtin::BIfabs;
5221 case Builtin::BIfabs:
5222 return Builtin::BIfabsl;
5223 case Builtin::BIfabsl:
5224 return 0;
5225
5226 case Builtin::BIcabsf:
5227 return Builtin::BIcabs;
5228 case Builtin::BIcabs:
5229 return Builtin::BIcabsl;
5230 case Builtin::BIcabsl:
5231 return 0;
5232 }
5233}
5234
5235// Returns the argument type of the absolute value function.
5236static QualType getAbsoluteValueArgumentType(ASTContext &Context,
5237 unsigned AbsType) {
5238 if (AbsType == 0)
5239 return QualType();
5240
5241 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
5242 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
5243 if (Error != ASTContext::GE_None)
5244 return QualType();
5245
5246 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
5247 if (!FT)
5248 return QualType();
5249
5250 if (FT->getNumParams() != 1)
5251 return QualType();
5252
5253 return FT->getParamType(0);
5254}
5255
5256// Returns the best absolute value function, or zero, based on type and
5257// current absolute value function.
5258static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
5259 unsigned AbsFunctionKind) {
5260 unsigned BestKind = 0;
5261 uint64_t ArgSize = Context.getTypeSize(ArgType);
5262 for (unsigned Kind = AbsFunctionKind; Kind != 0;
5263 Kind = getLargerAbsoluteValueFunction(Kind)) {
5264 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
5265 if (Context.getTypeSize(ParamType) >= ArgSize) {
5266 if (BestKind == 0)
5267 BestKind = Kind;
5268 else if (Context.hasSameType(ParamType, ArgType)) {
5269 BestKind = Kind;
5270 break;
5271 }
5272 }
5273 }
5274 return BestKind;
5275}
5276
5277enum AbsoluteValueKind {
5278 AVK_Integer,
5279 AVK_Floating,
5280 AVK_Complex
5281};
5282
5283static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
5284 if (T->isIntegralOrEnumerationType())
5285 return AVK_Integer;
5286 if (T->isRealFloatingType())
5287 return AVK_Floating;
5288 if (T->isAnyComplexType())
5289 return AVK_Complex;
5290
5291 llvm_unreachable("Type not integer, floating, or complex");
5292}
5293
5294// Changes the absolute value function to a different type. Preserves whether
5295// the function is a builtin.
5296static unsigned changeAbsFunction(unsigned AbsKind,
5297 AbsoluteValueKind ValueKind) {
5298 switch (ValueKind) {
5299 case AVK_Integer:
5300 switch (AbsKind) {
5301 default:
5302 return 0;
5303 case Builtin::BI__builtin_fabsf:
5304 case Builtin::BI__builtin_fabs:
5305 case Builtin::BI__builtin_fabsl:
5306 case Builtin::BI__builtin_cabsf:
5307 case Builtin::BI__builtin_cabs:
5308 case Builtin::BI__builtin_cabsl:
5309 return Builtin::BI__builtin_abs;
5310 case Builtin::BIfabsf:
5311 case Builtin::BIfabs:
5312 case Builtin::BIfabsl:
5313 case Builtin::BIcabsf:
5314 case Builtin::BIcabs:
5315 case Builtin::BIcabsl:
5316 return Builtin::BIabs;
5317 }
5318 case AVK_Floating:
5319 switch (AbsKind) {
5320 default:
5321 return 0;
5322 case Builtin::BI__builtin_abs:
5323 case Builtin::BI__builtin_labs:
5324 case Builtin::BI__builtin_llabs:
5325 case Builtin::BI__builtin_cabsf:
5326 case Builtin::BI__builtin_cabs:
5327 case Builtin::BI__builtin_cabsl:
5328 return Builtin::BI__builtin_fabsf;
5329 case Builtin::BIabs:
5330 case Builtin::BIlabs:
5331 case Builtin::BIllabs:
5332 case Builtin::BIcabsf:
5333 case Builtin::BIcabs:
5334 case Builtin::BIcabsl:
5335 return Builtin::BIfabsf;
5336 }
5337 case AVK_Complex:
5338 switch (AbsKind) {
5339 default:
5340 return 0;
5341 case Builtin::BI__builtin_abs:
5342 case Builtin::BI__builtin_labs:
5343 case Builtin::BI__builtin_llabs:
5344 case Builtin::BI__builtin_fabsf:
5345 case Builtin::BI__builtin_fabs:
5346 case Builtin::BI__builtin_fabsl:
5347 return Builtin::BI__builtin_cabsf;
5348 case Builtin::BIabs:
5349 case Builtin::BIlabs:
5350 case Builtin::BIllabs:
5351 case Builtin::BIfabsf:
5352 case Builtin::BIfabs:
5353 case Builtin::BIfabsl:
5354 return Builtin::BIcabsf;
5355 }
5356 }
5357 llvm_unreachable("Unable to convert function");
5358}
5359
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00005360static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005361 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
5362 if (!FnInfo)
5363 return 0;
5364
5365 switch (FDecl->getBuiltinID()) {
5366 default:
5367 return 0;
5368 case Builtin::BI__builtin_abs:
5369 case Builtin::BI__builtin_fabs:
5370 case Builtin::BI__builtin_fabsf:
5371 case Builtin::BI__builtin_fabsl:
5372 case Builtin::BI__builtin_labs:
5373 case Builtin::BI__builtin_llabs:
5374 case Builtin::BI__builtin_cabs:
5375 case Builtin::BI__builtin_cabsf:
5376 case Builtin::BI__builtin_cabsl:
5377 case Builtin::BIabs:
5378 case Builtin::BIlabs:
5379 case Builtin::BIllabs:
5380 case Builtin::BIfabs:
5381 case Builtin::BIfabsf:
5382 case Builtin::BIfabsl:
5383 case Builtin::BIcabs:
5384 case Builtin::BIcabsf:
5385 case Builtin::BIcabsl:
5386 return FDecl->getBuiltinID();
5387 }
5388 llvm_unreachable("Unknown Builtin type");
5389}
5390
5391// If the replacement is valid, emit a note with replacement function.
5392// Additionally, suggest including the proper header if not already included.
5393static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00005394 unsigned AbsKind, QualType ArgType) {
5395 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00005396 const char *HeaderName = nullptr;
5397 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00005398 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
5399 FunctionName = "std::abs";
5400 if (ArgType->isIntegralOrEnumerationType()) {
5401 HeaderName = "cstdlib";
5402 } else if (ArgType->isRealFloatingType()) {
5403 HeaderName = "cmath";
5404 } else {
5405 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005406 }
Richard Trieubeffb832014-04-15 23:47:53 +00005407
5408 // Lookup all std::abs
5409 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00005410 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00005411 R.suppressDiagnostics();
5412 S.LookupQualifiedName(R, Std);
5413
5414 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005415 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00005416 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
5417 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
5418 } else {
5419 FDecl = dyn_cast<FunctionDecl>(I);
5420 }
5421 if (!FDecl)
5422 continue;
5423
5424 // Found std::abs(), check that they are the right ones.
5425 if (FDecl->getNumParams() != 1)
5426 continue;
5427
5428 // Check that the parameter type can handle the argument.
5429 QualType ParamType = FDecl->getParamDecl(0)->getType();
5430 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
5431 S.Context.getTypeSize(ArgType) <=
5432 S.Context.getTypeSize(ParamType)) {
5433 // Found a function, don't need the header hint.
5434 EmitHeaderHint = false;
5435 break;
5436 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005437 }
Richard Trieubeffb832014-04-15 23:47:53 +00005438 }
5439 } else {
Eric Christopher02d5d862015-08-06 01:01:12 +00005440 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
Richard Trieubeffb832014-04-15 23:47:53 +00005441 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
5442
5443 if (HeaderName) {
5444 DeclarationName DN(&S.Context.Idents.get(FunctionName));
5445 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
5446 R.suppressDiagnostics();
5447 S.LookupName(R, S.getCurScope());
5448
5449 if (R.isSingleResult()) {
5450 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
5451 if (FD && FD->getBuiltinID() == AbsKind) {
5452 EmitHeaderHint = false;
5453 } else {
5454 return;
5455 }
5456 } else if (!R.empty()) {
5457 return;
5458 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005459 }
5460 }
5461
5462 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00005463 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005464
Richard Trieubeffb832014-04-15 23:47:53 +00005465 if (!HeaderName)
5466 return;
5467
5468 if (!EmitHeaderHint)
5469 return;
5470
Alp Toker5d96e0a2014-07-11 20:53:51 +00005471 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
5472 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00005473}
5474
5475static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
5476 if (!FDecl)
5477 return false;
5478
5479 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
5480 return false;
5481
5482 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
5483
5484 while (ND && ND->isInlineNamespace()) {
5485 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005486 }
Richard Trieubeffb832014-04-15 23:47:53 +00005487
5488 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
5489 return false;
5490
5491 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
5492 return false;
5493
5494 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005495}
5496
5497// Warn when using the wrong abs() function.
5498void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
5499 const FunctionDecl *FDecl,
5500 IdentifierInfo *FnInfo) {
5501 if (Call->getNumArgs() != 1)
5502 return;
5503
5504 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieubeffb832014-04-15 23:47:53 +00005505 bool IsStdAbs = IsFunctionStdAbs(FDecl);
5506 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005507 return;
5508
5509 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
5510 QualType ParamType = Call->getArg(0)->getType();
5511
Alp Toker5d96e0a2014-07-11 20:53:51 +00005512 // Unsigned types cannot be negative. Suggest removing the absolute value
5513 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005514 if (ArgType->isUnsignedIntegerType()) {
Richard Trieubeffb832014-04-15 23:47:53 +00005515 const char *FunctionName =
Eric Christopher02d5d862015-08-06 01:01:12 +00005516 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005517 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
5518 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00005519 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005520 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
5521 return;
5522 }
5523
David Majnemer7f77eb92015-11-15 03:04:34 +00005524 // Taking the absolute value of a pointer is very suspicious, they probably
5525 // wanted to index into an array, dereference a pointer, call a function, etc.
5526 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
5527 unsigned DiagType = 0;
5528 if (ArgType->isFunctionType())
5529 DiagType = 1;
5530 else if (ArgType->isArrayType())
5531 DiagType = 2;
5532
5533 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
5534 return;
5535 }
5536
Richard Trieubeffb832014-04-15 23:47:53 +00005537 // std::abs has overloads which prevent most of the absolute value problems
5538 // from occurring.
5539 if (IsStdAbs)
5540 return;
5541
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005542 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
5543 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
5544
5545 // The argument and parameter are the same kind. Check if they are the right
5546 // size.
5547 if (ArgValueKind == ParamValueKind) {
5548 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
5549 return;
5550
5551 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
5552 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
5553 << FDecl << ArgType << ParamType;
5554
5555 if (NewAbsKind == 0)
5556 return;
5557
5558 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00005559 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005560 return;
5561 }
5562
5563 // ArgValueKind != ParamValueKind
5564 // The wrong type of absolute value function was used. Attempt to find the
5565 // proper one.
5566 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
5567 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
5568 if (NewAbsKind == 0)
5569 return;
5570
5571 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
5572 << FDecl << ParamValueKind << ArgValueKind;
5573
5574 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00005575 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005576}
5577
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005578//===--- CHECK: Standard memory functions ---------------------------------===//
5579
Nico Weber0e6daef2013-12-26 23:38:39 +00005580/// \brief Takes the expression passed to the size_t parameter of functions
5581/// such as memcmp, strncat, etc and warns if it's a comparison.
5582///
5583/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
5584static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
5585 IdentifierInfo *FnName,
5586 SourceLocation FnLoc,
5587 SourceLocation RParenLoc) {
5588 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
5589 if (!Size)
5590 return false;
5591
5592 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
5593 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
5594 return false;
5595
Nico Weber0e6daef2013-12-26 23:38:39 +00005596 SourceRange SizeRange = Size->getSourceRange();
5597 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
5598 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00005599 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00005600 << FnName << FixItHint::CreateInsertion(
5601 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00005602 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00005603 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00005604 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00005605 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
5606 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00005607
5608 return true;
5609}
5610
Reid Kleckner5fb5b122014-06-27 23:58:21 +00005611/// \brief Determine whether the given type is or contains a dynamic class type
5612/// (e.g., whether it has a vtable).
5613static const CXXRecordDecl *getContainedDynamicClass(QualType T,
5614 bool &IsContained) {
5615 // Look through array types while ignoring qualifiers.
5616 const Type *Ty = T->getBaseElementTypeUnsafe();
5617 IsContained = false;
5618
5619 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
5620 RD = RD ? RD->getDefinition() : nullptr;
Richard Trieu1c7237a2016-03-31 04:18:07 +00005621 if (!RD || RD->isInvalidDecl())
Reid Kleckner5fb5b122014-06-27 23:58:21 +00005622 return nullptr;
5623
5624 if (RD->isDynamicClass())
5625 return RD;
5626
5627 // Check all the fields. If any bases were dynamic, the class is dynamic.
5628 // It's impossible for a class to transitively contain itself by value, so
5629 // infinite recursion is impossible.
5630 for (auto *FD : RD->fields()) {
5631 bool SubContained;
5632 if (const CXXRecordDecl *ContainedRD =
5633 getContainedDynamicClass(FD->getType(), SubContained)) {
5634 IsContained = true;
5635 return ContainedRD;
5636 }
5637 }
5638
5639 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00005640}
5641
Chandler Carruth889ed862011-06-21 23:04:20 +00005642/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005643/// otherwise returns NULL.
Nico Weberc44b35e2015-03-21 17:37:46 +00005644static const Expr *getSizeOfExprArg(const Expr *E) {
Nico Weberc5e73862011-06-14 16:14:58 +00005645 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005646 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
5647 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
5648 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00005649
Craig Topperc3ec1492014-05-26 06:22:03 +00005650 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005651}
5652
Chandler Carruth889ed862011-06-21 23:04:20 +00005653/// \brief If E is a sizeof expression, returns its argument type.
Nico Weberc44b35e2015-03-21 17:37:46 +00005654static QualType getSizeOfArgType(const Expr *E) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005655 if (const UnaryExprOrTypeTraitExpr *SizeOf =
5656 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
5657 if (SizeOf->getKind() == clang::UETT_SizeOf)
5658 return SizeOf->getTypeOfArgument();
5659
5660 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00005661}
5662
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005663/// \brief Check for dangerous or invalid arguments to memset().
5664///
Chandler Carruthac687262011-06-03 06:23:57 +00005665/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00005666/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
5667/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005668///
5669/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00005670void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00005671 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00005672 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00005673 assert(BId != 0);
5674
Ted Kremenekb5fabb22011-04-28 01:38:02 +00005675 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00005676 // we have enough arguments, and if not, abort further checking.
Anna Zaks22122702012-01-17 00:37:07 +00005677 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00005678 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00005679 return;
5680
Anna Zaks22122702012-01-17 00:37:07 +00005681 unsigned LastArg = (BId == Builtin::BImemset ||
5682 BId == Builtin::BIstrndup ? 1 : 2);
5683 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00005684 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005685
Nico Weber0e6daef2013-12-26 23:38:39 +00005686 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
5687 Call->getLocStart(), Call->getRParenLoc()))
5688 return;
5689
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005690 // We have special checking when the length is a sizeof expression.
5691 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
5692 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
5693 llvm::FoldingSetNodeID SizeOfArgID;
5694
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005695 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
5696 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00005697 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005698
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005699 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00005700 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005701 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00005702 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00005703
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005704 // Never warn about void type pointers. This can be used to suppress
5705 // false positives.
5706 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005707 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005708
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005709 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
5710 // actually comparing the expressions for equality. Because computing the
5711 // expression IDs can be expensive, we only do this if the diagnostic is
5712 // enabled.
5713 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00005714 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
5715 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005716 // We only compute IDs for expressions if the warning is enabled, and
5717 // cache the sizeof arg's ID.
5718 if (SizeOfArgID == llvm::FoldingSetNodeID())
5719 SizeOfArg->Profile(SizeOfArgID, Context, true);
5720 llvm::FoldingSetNodeID DestID;
5721 Dest->Profile(DestID, Context, true);
5722 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00005723 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
5724 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005725 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00005726 StringRef ReadableName = FnName->getName();
5727
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005728 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00005729 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005730 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00005731 if (!PointeeTy->isIncompleteType() &&
5732 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005733 ActionIdx = 2; // If the pointee's size is sizeof(char),
5734 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00005735
5736 // If the function is defined as a builtin macro, do not show macro
5737 // expansion.
5738 SourceLocation SL = SizeOfArg->getExprLoc();
5739 SourceRange DSR = Dest->getSourceRange();
5740 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00005741 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00005742
5743 if (SM.isMacroArgExpansion(SL)) {
5744 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
5745 SL = SM.getSpellingLoc(SL);
5746 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
5747 SM.getSpellingLoc(DSR.getEnd()));
5748 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
5749 SM.getSpellingLoc(SSR.getEnd()));
5750 }
5751
Anna Zaksd08d9152012-05-30 23:14:52 +00005752 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005753 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00005754 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00005755 << PointeeTy
5756 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00005757 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00005758 << SSR);
5759 DiagRuntimeBehavior(SL, SizeOfArg,
5760 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
5761 << ActionIdx
5762 << SSR);
5763
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005764 break;
5765 }
5766 }
5767
5768 // Also check for cases where the sizeof argument is the exact same
5769 // type as the memory argument, and where it points to a user-defined
5770 // record type.
5771 if (SizeOfArgTy != QualType()) {
5772 if (PointeeTy->isRecordType() &&
5773 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
5774 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
5775 PDiag(diag::warn_sizeof_pointer_type_memaccess)
5776 << FnName << SizeOfArgTy << ArgIdx
5777 << PointeeTy << Dest->getSourceRange()
5778 << LenExpr->getSourceRange());
5779 break;
5780 }
Nico Weberc5e73862011-06-14 16:14:58 +00005781 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00005782 } else if (DestTy->isArrayType()) {
5783 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00005784 }
Nico Weberc5e73862011-06-14 16:14:58 +00005785
Nico Weberc44b35e2015-03-21 17:37:46 +00005786 if (PointeeTy == QualType())
5787 continue;
Anna Zaks22122702012-01-17 00:37:07 +00005788
Nico Weberc44b35e2015-03-21 17:37:46 +00005789 // Always complain about dynamic classes.
5790 bool IsContained;
5791 if (const CXXRecordDecl *ContainedRD =
5792 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00005793
Nico Weberc44b35e2015-03-21 17:37:46 +00005794 unsigned OperationType = 0;
5795 // "overwritten" if we're warning about the destination for any call
5796 // but memcmp; otherwise a verb appropriate to the call.
5797 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
5798 if (BId == Builtin::BImemcpy)
5799 OperationType = 1;
5800 else if(BId == Builtin::BImemmove)
5801 OperationType = 2;
5802 else if (BId == Builtin::BImemcmp)
5803 OperationType = 3;
5804 }
5805
John McCall31168b02011-06-15 23:02:42 +00005806 DiagRuntimeBehavior(
5807 Dest->getExprLoc(), Dest,
Nico Weberc44b35e2015-03-21 17:37:46 +00005808 PDiag(diag::warn_dyn_class_memaccess)
5809 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
5810 << FnName << IsContained << ContainedRD << OperationType
5811 << Call->getCallee()->getSourceRange());
5812 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
5813 BId != Builtin::BImemset)
5814 DiagRuntimeBehavior(
5815 Dest->getExprLoc(), Dest,
5816 PDiag(diag::warn_arc_object_memaccess)
5817 << ArgIdx << FnName << PointeeTy
5818 << Call->getCallee()->getSourceRange());
5819 else
5820 continue;
5821
5822 DiagRuntimeBehavior(
5823 Dest->getExprLoc(), Dest,
5824 PDiag(diag::note_bad_memaccess_silence)
5825 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
5826 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005827 }
5828}
5829
Ted Kremenek6865f772011-08-18 20:55:45 +00005830// A little helper routine: ignore addition and subtraction of integer literals.
5831// This intentionally does not ignore all integer constant expressions because
5832// we don't want to remove sizeof().
5833static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
5834 Ex = Ex->IgnoreParenCasts();
5835
5836 for (;;) {
5837 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
5838 if (!BO || !BO->isAdditiveOp())
5839 break;
5840
5841 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
5842 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
5843
5844 if (isa<IntegerLiteral>(RHS))
5845 Ex = LHS;
5846 else if (isa<IntegerLiteral>(LHS))
5847 Ex = RHS;
5848 else
5849 break;
5850 }
5851
5852 return Ex;
5853}
5854
Anna Zaks13b08572012-08-08 21:42:23 +00005855static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
5856 ASTContext &Context) {
5857 // Only handle constant-sized or VLAs, but not flexible members.
5858 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
5859 // Only issue the FIXIT for arrays of size > 1.
5860 if (CAT->getSize().getSExtValue() <= 1)
5861 return false;
5862 } else if (!Ty->isVariableArrayType()) {
5863 return false;
5864 }
5865 return true;
5866}
5867
Ted Kremenek6865f772011-08-18 20:55:45 +00005868// Warn if the user has made the 'size' argument to strlcpy or strlcat
5869// be the size of the source, instead of the destination.
5870void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
5871 IdentifierInfo *FnName) {
5872
5873 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00005874 unsigned NumArgs = Call->getNumArgs();
5875 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00005876 return;
5877
5878 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
5879 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00005880 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00005881
5882 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
5883 Call->getLocStart(), Call->getRParenLoc()))
5884 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00005885
5886 // Look for 'strlcpy(dst, x, sizeof(x))'
5887 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
5888 CompareWithSrc = Ex;
5889 else {
5890 // Look for 'strlcpy(dst, x, strlen(x))'
5891 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00005892 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
5893 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00005894 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
5895 }
5896 }
5897
5898 if (!CompareWithSrc)
5899 return;
5900
5901 // Determine if the argument to sizeof/strlen is equal to the source
5902 // argument. In principle there's all kinds of things you could do
5903 // here, for instance creating an == expression and evaluating it with
5904 // EvaluateAsBooleanCondition, but this uses a more direct technique:
5905 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
5906 if (!SrcArgDRE)
5907 return;
5908
5909 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
5910 if (!CompareWithSrcDRE ||
5911 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
5912 return;
5913
5914 const Expr *OriginalSizeArg = Call->getArg(2);
5915 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
5916 << OriginalSizeArg->getSourceRange() << FnName;
5917
5918 // Output a FIXIT hint if the destination is an array (rather than a
5919 // pointer to an array). This could be enhanced to handle some
5920 // pointers if we know the actual size, like if DstArg is 'array+2'
5921 // we could say 'sizeof(array)-2'.
5922 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00005923 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00005924 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00005925
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00005926 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00005927 llvm::raw_svector_ostream OS(sizeString);
5928 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00005929 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00005930 OS << ")";
5931
5932 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
5933 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
5934 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00005935}
5936
Anna Zaks314cd092012-02-01 19:08:57 +00005937/// Check if two expressions refer to the same declaration.
5938static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
5939 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
5940 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
5941 return D1->getDecl() == D2->getDecl();
5942 return false;
5943}
5944
5945static const Expr *getStrlenExprArg(const Expr *E) {
5946 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
5947 const FunctionDecl *FD = CE->getDirectCallee();
5948 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00005949 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00005950 return CE->getArg(0)->IgnoreParenCasts();
5951 }
Craig Topperc3ec1492014-05-26 06:22:03 +00005952 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00005953}
5954
5955// Warn on anti-patterns as the 'size' argument to strncat.
5956// The correct size argument should look like following:
5957// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
5958void Sema::CheckStrncatArguments(const CallExpr *CE,
5959 IdentifierInfo *FnName) {
5960 // Don't crash if the user has the wrong number of arguments.
5961 if (CE->getNumArgs() < 3)
5962 return;
5963 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
5964 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
5965 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
5966
Nico Weber0e6daef2013-12-26 23:38:39 +00005967 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
5968 CE->getRParenLoc()))
5969 return;
5970
Anna Zaks314cd092012-02-01 19:08:57 +00005971 // Identify common expressions, which are wrongly used as the size argument
5972 // to strncat and may lead to buffer overflows.
5973 unsigned PatternType = 0;
5974 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
5975 // - sizeof(dst)
5976 if (referToTheSameDecl(SizeOfArg, DstArg))
5977 PatternType = 1;
5978 // - sizeof(src)
5979 else if (referToTheSameDecl(SizeOfArg, SrcArg))
5980 PatternType = 2;
5981 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
5982 if (BE->getOpcode() == BO_Sub) {
5983 const Expr *L = BE->getLHS()->IgnoreParenCasts();
5984 const Expr *R = BE->getRHS()->IgnoreParenCasts();
5985 // - sizeof(dst) - strlen(dst)
5986 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
5987 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
5988 PatternType = 1;
5989 // - sizeof(src) - (anything)
5990 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
5991 PatternType = 2;
5992 }
5993 }
5994
5995 if (PatternType == 0)
5996 return;
5997
Anna Zaks5069aa32012-02-03 01:27:37 +00005998 // Generate the diagnostic.
5999 SourceLocation SL = LenArg->getLocStart();
6000 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00006001 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00006002
6003 // If the function is defined as a builtin macro, do not show macro expansion.
6004 if (SM.isMacroArgExpansion(SL)) {
6005 SL = SM.getSpellingLoc(SL);
6006 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
6007 SM.getSpellingLoc(SR.getEnd()));
6008 }
6009
Anna Zaks13b08572012-08-08 21:42:23 +00006010 // Check if the destination is an array (rather than a pointer to an array).
6011 QualType DstTy = DstArg->getType();
6012 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
6013 Context);
6014 if (!isKnownSizeArray) {
6015 if (PatternType == 1)
6016 Diag(SL, diag::warn_strncat_wrong_size) << SR;
6017 else
6018 Diag(SL, diag::warn_strncat_src_size) << SR;
6019 return;
6020 }
6021
Anna Zaks314cd092012-02-01 19:08:57 +00006022 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00006023 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00006024 else
Anna Zaks5069aa32012-02-03 01:27:37 +00006025 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00006026
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00006027 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00006028 llvm::raw_svector_ostream OS(sizeString);
6029 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00006030 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00006031 OS << ") - ";
6032 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00006033 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00006034 OS << ") - 1";
6035
Anna Zaks5069aa32012-02-03 01:27:37 +00006036 Diag(SL, diag::note_strncat_wrong_size)
6037 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00006038}
6039
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006040//===--- CHECK: Return Address of Stack Variable --------------------------===//
6041
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006042static const Expr *EvalVal(const Expr *E,
6043 SmallVectorImpl<const DeclRefExpr *> &refVars,
6044 const Decl *ParentDecl);
6045static const Expr *EvalAddr(const Expr *E,
6046 SmallVectorImpl<const DeclRefExpr *> &refVars,
6047 const Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006048
6049/// CheckReturnStackAddr - Check if a return statement returns the address
6050/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006051static void
6052CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
6053 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00006054
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006055 const Expr *stackE = nullptr;
6056 SmallVector<const DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006057
6058 // Perform checking for returned stack addresses, local blocks,
6059 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00006060 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006061 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006062 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00006063 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006064 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006065 }
6066
Craig Topperc3ec1492014-05-26 06:22:03 +00006067 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006068 return; // Nothing suspicious was found.
6069
6070 SourceLocation diagLoc;
6071 SourceRange diagRange;
6072 if (refVars.empty()) {
6073 diagLoc = stackE->getLocStart();
6074 diagRange = stackE->getSourceRange();
6075 } else {
6076 // We followed through a reference variable. 'stackE' contains the
6077 // problematic expression but we will warn at the return statement pointing
6078 // at the reference variable. We will later display the "trail" of
6079 // reference variables using notes.
6080 diagLoc = refVars[0]->getLocStart();
6081 diagRange = refVars[0]->getSourceRange();
6082 }
6083
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006084 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
6085 // address of local var
Craig Topperda7b27f2015-11-17 05:40:09 +00006086 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006087 << DR->getDecl()->getDeclName() << diagRange;
6088 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006089 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006090 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006091 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006092 } else { // local temporary.
Craig Topperda7b27f2015-11-17 05:40:09 +00006093 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
6094 << lhsType->isReferenceType() << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006095 }
6096
6097 // Display the "trail" of reference variables that we followed until we
6098 // found the problematic expression using notes.
6099 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006100 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006101 // If this var binds to another reference var, show the range of the next
6102 // var, otherwise the var binds to the problematic expression, in which case
6103 // show the range of the expression.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006104 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
6105 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006106 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
6107 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006108 }
6109}
6110
6111/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
6112/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006113/// to a location on the stack, a local block, an address of a label, or a
6114/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006115/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006116/// encounter a subexpression that (1) clearly does not lead to one of the
6117/// above problematic expressions (2) is something we cannot determine leads to
6118/// a problematic expression based on such local checking.
6119///
6120/// Both EvalAddr and EvalVal follow through reference variables to evaluate
6121/// the expression that they point to. Such variables are added to the
6122/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006123///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00006124/// EvalAddr processes expressions that are pointers that are used as
6125/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006126/// At the base case of the recursion is a check for the above problematic
6127/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006128///
6129/// This implementation handles:
6130///
6131/// * pointer-to-pointer casts
6132/// * implicit conversions from array references to pointers
6133/// * taking the address of fields
6134/// * arbitrary interplay between "&" and "*" operators
6135/// * pointer arithmetic from an address of a stack variable
6136/// * taking the address of an array element where the array is on the stack
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006137static const Expr *EvalAddr(const Expr *E,
6138 SmallVectorImpl<const DeclRefExpr *> &refVars,
6139 const Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006140 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00006141 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006142
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006143 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00006144 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00006145 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006146 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00006147 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00006148
Peter Collingbourne91147592011-04-15 00:35:48 +00006149 E = E->IgnoreParens();
6150
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006151 // Our "symbolic interpreter" is just a dispatch off the currently
6152 // viewed AST node. We then recursively traverse the AST by calling
6153 // EvalAddr and EvalVal appropriately.
6154 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006155 case Stmt::DeclRefExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006156 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006157
Richard Smith40f08eb2014-01-30 22:05:38 +00006158 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00006159 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00006160 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00006161
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006162 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006163 // If this is a reference variable, follow through to the expression that
6164 // it points to.
6165 if (V->hasLocalStorage() &&
6166 V->getType()->isReferenceType() && V->hasInit()) {
6167 // Add the reference variable to the "trail".
6168 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006169 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006170 }
6171
Craig Topperc3ec1492014-05-26 06:22:03 +00006172 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006173 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006174
Chris Lattner934edb22007-12-28 05:31:15 +00006175 case Stmt::UnaryOperatorClass: {
6176 // The only unary operator that make sense to handle here
6177 // is AddrOf. All others don't make sense as pointers.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006178 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00006179
John McCalle3027922010-08-25 11:45:40 +00006180 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006181 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006182 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006183 }
Mike Stump11289f42009-09-09 15:08:12 +00006184
Chris Lattner934edb22007-12-28 05:31:15 +00006185 case Stmt::BinaryOperatorClass: {
6186 // Handle pointer arithmetic. All other binary operators are not valid
6187 // in this context.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006188 const BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00006189 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00006190
John McCalle3027922010-08-25 11:45:40 +00006191 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00006192 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00006193
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006194 const Expr *Base = B->getLHS();
Chris Lattner934edb22007-12-28 05:31:15 +00006195
6196 // Determine which argument is the real pointer base. It could be
6197 // the RHS argument instead of the LHS.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006198 if (!Base->getType()->isPointerType())
6199 Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00006200
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006201 assert(Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006202 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00006203 }
Steve Naroff2752a172008-09-10 19:17:48 +00006204
Chris Lattner934edb22007-12-28 05:31:15 +00006205 // For conditional operators we need to see if either the LHS or RHS are
6206 // valid DeclRefExpr*s. If one of them is valid, we return it.
6207 case Stmt::ConditionalOperatorClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006208 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00006209
Chris Lattner934edb22007-12-28 05:31:15 +00006210 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006211 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006212 if (const Expr *LHSExpr = C->getLHS()) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006213 // In C++, we can have a throw-expression, which has 'void' type.
6214 if (!LHSExpr->getType()->isVoidType())
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006215 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00006216 return LHS;
6217 }
Chris Lattner934edb22007-12-28 05:31:15 +00006218
Douglas Gregor270b2ef2010-10-21 16:21:08 +00006219 // In C++, we can have a throw-expression, which has 'void' type.
6220 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00006221 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00006222
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006223 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00006224 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006225
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006226 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00006227 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006228 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00006229 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006230
6231 case Stmt::AddrLabelExprClass:
6232 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00006233
John McCall28fc7092011-11-10 05:35:25 +00006234 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006235 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
6236 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00006237
Ted Kremenekc3b4c522008-08-07 00:49:01 +00006238 // For casts, we need to handle conversions from arrays to
6239 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00006240 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00006241 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00006242 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00006243 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00006244 case Stmt::CXXStaticCastExprClass:
6245 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00006246 case Stmt::CXXConstCastExprClass:
6247 case Stmt::CXXReinterpretCastExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006248 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Eli Friedman8195ad72012-02-23 23:04:32 +00006249 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00006250 case CK_LValueToRValue:
6251 case CK_NoOp:
6252 case CK_BaseToDerived:
6253 case CK_DerivedToBase:
6254 case CK_UncheckedDerivedToBase:
6255 case CK_Dynamic:
6256 case CK_CPointerToObjCPointerCast:
6257 case CK_BlockPointerToObjCPointerCast:
6258 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006259 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00006260
6261 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006262 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00006263
Richard Trieudadefde2014-07-02 04:39:38 +00006264 case CK_BitCast:
6265 if (SubExpr->getType()->isAnyPointerType() ||
6266 SubExpr->getType()->isBlockPointerType() ||
6267 SubExpr->getType()->isObjCQualifiedIdType())
6268 return EvalAddr(SubExpr, refVars, ParentDecl);
6269 else
6270 return nullptr;
6271
Eli Friedman8195ad72012-02-23 23:04:32 +00006272 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00006273 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00006274 }
Chris Lattner934edb22007-12-28 05:31:15 +00006275 }
Mike Stump11289f42009-09-09 15:08:12 +00006276
Douglas Gregorfe314812011-06-21 17:03:29 +00006277 case Stmt::MaterializeTemporaryExprClass:
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006278 if (const Expr *Result =
6279 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
6280 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00006281 return Result;
Douglas Gregorfe314812011-06-21 17:03:29 +00006282 return E;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006283
Chris Lattner934edb22007-12-28 05:31:15 +00006284 // Everything else: we simply don't reason about them.
6285 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00006286 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00006287 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006288}
Mike Stump11289f42009-09-09 15:08:12 +00006289
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006290/// EvalVal - This function is complements EvalAddr in the mutual recursion.
6291/// See the comments for EvalAddr for more details.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006292static const Expr *EvalVal(const Expr *E,
6293 SmallVectorImpl<const DeclRefExpr *> &refVars,
6294 const Decl *ParentDecl) {
6295 do {
6296 // We should only be called for evaluating non-pointer expressions, or
6297 // expressions with a pointer type that are not used as references but
6298 // instead
6299 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00006300
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006301 // Our "symbolic interpreter" is just a dispatch off the currently
6302 // viewed AST node. We then recursively traverse the AST by calling
6303 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00006304
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006305 E = E->IgnoreParens();
6306 switch (E->getStmtClass()) {
6307 case Stmt::ImplicitCastExprClass: {
6308 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
6309 if (IE->getValueKind() == VK_LValue) {
6310 E = IE->getSubExpr();
6311 continue;
6312 }
Craig Topperc3ec1492014-05-26 06:22:03 +00006313 return nullptr;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006314 }
Richard Smith40f08eb2014-01-30 22:05:38 +00006315
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006316 case Stmt::ExprWithCleanupsClass:
6317 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
6318 ParentDecl);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006319
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006320 case Stmt::DeclRefExprClass: {
6321 // When we hit a DeclRefExpr we are looking at code that refers to a
6322 // variable's name. If it's not a reference variable we check if it has
6323 // local storage within the function, and if so, return the expression.
6324 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
6325
6326 // If we leave the immediate function, the lifetime isn't about to end.
6327 if (DR->refersToEnclosingVariableOrCapture())
6328 return nullptr;
6329
6330 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
6331 // Check if it refers to itself, e.g. "int& i = i;".
6332 if (V == ParentDecl)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006333 return DR;
6334
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006335 if (V->hasLocalStorage()) {
6336 if (!V->getType()->isReferenceType())
6337 return DR;
6338
6339 // Reference variable, follow through to the expression that
6340 // it points to.
6341 if (V->hasInit()) {
6342 // Add the reference variable to the "trail".
6343 refVars.push_back(DR);
6344 return EvalVal(V->getInit(), refVars, V);
6345 }
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006346 }
6347 }
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006348
6349 return nullptr;
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006350 }
Mike Stump11289f42009-09-09 15:08:12 +00006351
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006352 case Stmt::UnaryOperatorClass: {
6353 // The only unary operator that make sense to handle here
6354 // is Deref. All others don't resolve to a "name." This includes
6355 // handling all sorts of rvalues passed to a unary operator.
6356 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00006357
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006358 if (U->getOpcode() == UO_Deref)
6359 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Mike Stump11289f42009-09-09 15:08:12 +00006360
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006361 return nullptr;
6362 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006363
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006364 case Stmt::ArraySubscriptExprClass: {
6365 // Array subscripts are potential references to data on the stack. We
6366 // retrieve the DeclRefExpr* for the array variable if it indeed
6367 // has local storage.
Saleem Abdulrasoolcfd45532016-02-15 01:51:24 +00006368 const auto *ASE = cast<ArraySubscriptExpr>(E);
6369 if (ASE->isTypeDependent())
6370 return nullptr;
6371 return EvalAddr(ASE->getBase(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006372 }
Mike Stump11289f42009-09-09 15:08:12 +00006373
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006374 case Stmt::OMPArraySectionExprClass: {
6375 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
6376 ParentDecl);
6377 }
Mike Stump11289f42009-09-09 15:08:12 +00006378
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006379 case Stmt::ConditionalOperatorClass: {
6380 // For conditional operators we need to see if either the LHS or RHS are
6381 // non-NULL Expr's. If one is non-NULL, we return it.
6382 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Alexey Bataev1a3320e2015-08-25 14:24:04 +00006383
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006384 // Handle the GNU extension for missing LHS.
6385 if (const Expr *LHSExpr = C->getLHS()) {
6386 // In C++, we can have a throw-expression, which has 'void' type.
6387 if (!LHSExpr->getType()->isVoidType())
6388 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
6389 return LHS;
6390 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006391
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006392 // In C++, we can have a throw-expression, which has 'void' type.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006393 if (C->getRHS()->getType()->isVoidType())
6394 return nullptr;
6395
6396 return EvalVal(C->getRHS(), refVars, ParentDecl);
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006397 }
6398
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006399 // Accesses to members are potential references to data on the stack.
6400 case Stmt::MemberExprClass: {
6401 const MemberExpr *M = cast<MemberExpr>(E);
Anders Carlsson801c5c72007-11-30 19:04:31 +00006402
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006403 // Check for indirect access. We only want direct field accesses.
6404 if (M->isArrow())
6405 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00006406
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006407 // Check whether the member type is itself a reference, in which case
6408 // we're not going to refer to the member, but to what the member refers
6409 // to.
6410 if (M->getMemberDecl()->getType()->isReferenceType())
6411 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00006412
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006413 return EvalVal(M->getBase(), refVars, ParentDecl);
6414 }
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00006415
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006416 case Stmt::MaterializeTemporaryExprClass:
6417 if (const Expr *Result =
6418 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
6419 refVars, ParentDecl))
6420 return Result;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006421 return E;
6422
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006423 default:
6424 // Check that we don't return or take the address of a reference to a
6425 // temporary. This is only useful in C++.
6426 if (!E->isTypeDependent() && E->isRValue())
6427 return E;
6428
6429 // Everything else: we simply don't reason about them.
6430 return nullptr;
6431 }
6432 } while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006433}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006434
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006435void
6436Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
6437 SourceLocation ReturnLoc,
6438 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00006439 const AttrVec *Attrs,
6440 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006441 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
6442
6443 // Check if the return value is null but should not be.
Douglas Gregorb4866e82015-06-19 18:13:19 +00006444 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
6445 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
Benjamin Kramerae852a62014-02-23 14:34:50 +00006446 CheckNonNullExpr(*this, RetValExp))
6447 Diag(ReturnLoc, diag::warn_null_ret)
6448 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00006449
6450 // C++11 [basic.stc.dynamic.allocation]p4:
6451 // If an allocation function declared with a non-throwing
6452 // exception-specification fails to allocate storage, it shall return
6453 // a null pointer. Any other allocation function that fails to allocate
6454 // storage shall indicate failure only by throwing an exception [...]
6455 if (FD) {
6456 OverloadedOperatorKind Op = FD->getOverloadedOperator();
6457 if (Op == OO_New || Op == OO_Array_New) {
6458 const FunctionProtoType *Proto
6459 = FD->getType()->castAs<FunctionProtoType>();
6460 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
6461 CheckNonNullExpr(*this, RetValExp))
6462 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
6463 << FD << getLangOpts().CPlusPlus11;
6464 }
6465 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006466}
6467
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006468//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
6469
6470/// Check for comparisons of floating point operands using != and ==.
6471/// Issue a warning if these are no self-comparisons, as they are not likely
6472/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00006473void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00006474 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
6475 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006476
6477 // Special case: check for x == x (which is OK).
6478 // Do not emit warnings for such cases.
6479 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
6480 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
6481 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00006482 return;
Mike Stump11289f42009-09-09 15:08:12 +00006483
Ted Kremenekeda40e22007-11-29 00:59:04 +00006484 // Special case: check for comparisons against literals that can be exactly
6485 // represented by APFloat. In such cases, do not emit a warning. This
6486 // is a heuristic: often comparison against such literals are used to
6487 // detect if a value in a variable has not changed. This clearly can
6488 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00006489 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
6490 if (FLL->isExact())
6491 return;
6492 } else
6493 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
6494 if (FLR->isExact())
6495 return;
Mike Stump11289f42009-09-09 15:08:12 +00006496
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006497 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00006498 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00006499 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00006500 return;
Mike Stump11289f42009-09-09 15:08:12 +00006501
David Blaikie1f4ff152012-07-16 20:47:22 +00006502 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00006503 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00006504 return;
Mike Stump11289f42009-09-09 15:08:12 +00006505
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006506 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00006507 Diag(Loc, diag::warn_floatingpoint_eq)
6508 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006509}
John McCallca01b222010-01-04 23:21:16 +00006510
John McCall70aa5392010-01-06 05:24:50 +00006511//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
6512//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00006513
John McCall70aa5392010-01-06 05:24:50 +00006514namespace {
John McCallca01b222010-01-04 23:21:16 +00006515
John McCall70aa5392010-01-06 05:24:50 +00006516/// Structure recording the 'active' range of an integer-valued
6517/// expression.
6518struct IntRange {
6519 /// The number of bits active in the int.
6520 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00006521
John McCall70aa5392010-01-06 05:24:50 +00006522 /// True if the int is known not to have negative values.
6523 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00006524
John McCall70aa5392010-01-06 05:24:50 +00006525 IntRange(unsigned Width, bool NonNegative)
6526 : Width(Width), NonNegative(NonNegative)
6527 {}
John McCallca01b222010-01-04 23:21:16 +00006528
John McCall817d4af2010-11-10 23:38:19 +00006529 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00006530 static IntRange forBoolType() {
6531 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00006532 }
6533
John McCall817d4af2010-11-10 23:38:19 +00006534 /// Returns the range of an opaque value of the given integral type.
6535 static IntRange forValueOfType(ASTContext &C, QualType T) {
6536 return forValueOfCanonicalType(C,
6537 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00006538 }
6539
John McCall817d4af2010-11-10 23:38:19 +00006540 /// Returns the range of an opaque value of a canonical integral type.
6541 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00006542 assert(T->isCanonicalUnqualified());
6543
6544 if (const VectorType *VT = dyn_cast<VectorType>(T))
6545 T = VT->getElementType().getTypePtr();
6546 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
6547 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00006548 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
6549 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00006550
David Majnemer6a426652013-06-07 22:07:20 +00006551 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00006552 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00006553 EnumDecl *Enum = ET->getDecl();
6554 if (!Enum->isCompleteDefinition())
6555 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00006556
David Majnemer6a426652013-06-07 22:07:20 +00006557 unsigned NumPositive = Enum->getNumPositiveBits();
6558 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00006559
David Majnemer6a426652013-06-07 22:07:20 +00006560 if (NumNegative == 0)
6561 return IntRange(NumPositive, true/*NonNegative*/);
6562 else
6563 return IntRange(std::max(NumPositive + 1, NumNegative),
6564 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00006565 }
John McCall70aa5392010-01-06 05:24:50 +00006566
6567 const BuiltinType *BT = cast<BuiltinType>(T);
6568 assert(BT->isInteger());
6569
6570 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
6571 }
6572
John McCall817d4af2010-11-10 23:38:19 +00006573 /// Returns the "target" range of a canonical integral type, i.e.
6574 /// the range of values expressible in the type.
6575 ///
6576 /// This matches forValueOfCanonicalType except that enums have the
6577 /// full range of their type, not the range of their enumerators.
6578 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
6579 assert(T->isCanonicalUnqualified());
6580
6581 if (const VectorType *VT = dyn_cast<VectorType>(T))
6582 T = VT->getElementType().getTypePtr();
6583 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
6584 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00006585 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
6586 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00006587 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00006588 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00006589
6590 const BuiltinType *BT = cast<BuiltinType>(T);
6591 assert(BT->isInteger());
6592
6593 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
6594 }
6595
6596 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00006597 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00006598 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00006599 L.NonNegative && R.NonNegative);
6600 }
6601
John McCall817d4af2010-11-10 23:38:19 +00006602 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00006603 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00006604 return IntRange(std::min(L.Width, R.Width),
6605 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00006606 }
6607};
6608
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006609IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00006610 if (value.isSigned() && value.isNegative())
6611 return IntRange(value.getMinSignedBits(), false);
6612
6613 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00006614 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00006615
6616 // isNonNegative() just checks the sign bit without considering
6617 // signedness.
6618 return IntRange(value.getActiveBits(), true);
6619}
6620
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006621IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
6622 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00006623 if (result.isInt())
6624 return GetValueRange(C, result.getInt(), MaxWidth);
6625
6626 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00006627 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
6628 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
6629 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
6630 R = IntRange::join(R, El);
6631 }
John McCall70aa5392010-01-06 05:24:50 +00006632 return R;
6633 }
6634
6635 if (result.isComplexInt()) {
6636 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
6637 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
6638 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00006639 }
6640
6641 // This can happen with lossless casts to intptr_t of "based" lvalues.
6642 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00006643 // FIXME: The only reason we need to pass the type in here is to get
6644 // the sign right on this one case. It would be nice if APValue
6645 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006646 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00006647 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00006648}
John McCall70aa5392010-01-06 05:24:50 +00006649
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006650QualType GetExprType(const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00006651 QualType Ty = E->getType();
6652 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
6653 Ty = AtomicRHS->getValueType();
6654 return Ty;
6655}
6656
John McCall70aa5392010-01-06 05:24:50 +00006657/// Pseudo-evaluate the given integer expression, estimating the
6658/// range of values it might take.
6659///
6660/// \param MaxWidth - the width to which the value will be truncated
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006661IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00006662 E = E->IgnoreParens();
6663
6664 // Try a full evaluation first.
6665 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00006666 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00006667 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00006668
6669 // I think we only want to look through implicit casts here; if the
6670 // user has an explicit widening cast, we should treat the value as
6671 // being of the new, wider type.
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00006672 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00006673 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00006674 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
6675
Eli Friedmane6d33952013-07-08 20:20:06 +00006676 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00006677
George Burgess IVdf1ed002016-01-13 01:52:39 +00006678 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
6679 CE->getCastKind() == CK_BooleanToSignedIntegral;
John McCall2ce81ad2010-01-06 22:07:33 +00006680
John McCall70aa5392010-01-06 05:24:50 +00006681 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00006682 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00006683 return OutputTypeRange;
6684
6685 IntRange SubRange
6686 = GetExprRange(C, CE->getSubExpr(),
6687 std::min(MaxWidth, OutputTypeRange.Width));
6688
6689 // Bail out if the subexpr's range is as wide as the cast type.
6690 if (SubRange.Width >= OutputTypeRange.Width)
6691 return OutputTypeRange;
6692
6693 // Otherwise, we take the smaller width, and we're non-negative if
6694 // either the output type or the subexpr is.
6695 return IntRange(SubRange.Width,
6696 SubRange.NonNegative || OutputTypeRange.NonNegative);
6697 }
6698
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00006699 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00006700 // If we can fold the condition, just take that operand.
6701 bool CondResult;
6702 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
6703 return GetExprRange(C, CondResult ? CO->getTrueExpr()
6704 : CO->getFalseExpr(),
6705 MaxWidth);
6706
6707 // Otherwise, conservatively merge.
6708 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
6709 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
6710 return IntRange::join(L, R);
6711 }
6712
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00006713 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00006714 switch (BO->getOpcode()) {
6715
6716 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00006717 case BO_LAnd:
6718 case BO_LOr:
6719 case BO_LT:
6720 case BO_GT:
6721 case BO_LE:
6722 case BO_GE:
6723 case BO_EQ:
6724 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00006725 return IntRange::forBoolType();
6726
John McCallc3688382011-07-13 06:35:24 +00006727 // The type of the assignments is the type of the LHS, so the RHS
6728 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00006729 case BO_MulAssign:
6730 case BO_DivAssign:
6731 case BO_RemAssign:
6732 case BO_AddAssign:
6733 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00006734 case BO_XorAssign:
6735 case BO_OrAssign:
6736 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00006737 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00006738
John McCallc3688382011-07-13 06:35:24 +00006739 // Simple assignments just pass through the RHS, which will have
6740 // been coerced to the LHS type.
6741 case BO_Assign:
6742 // TODO: bitfields?
6743 return GetExprRange(C, BO->getRHS(), MaxWidth);
6744
John McCall70aa5392010-01-06 05:24:50 +00006745 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00006746 case BO_PtrMemD:
6747 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00006748 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006749
John McCall2ce81ad2010-01-06 22:07:33 +00006750 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00006751 case BO_And:
6752 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00006753 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
6754 GetExprRange(C, BO->getRHS(), MaxWidth));
6755
John McCall70aa5392010-01-06 05:24:50 +00006756 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00006757 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00006758 // ...except that we want to treat '1 << (blah)' as logically
6759 // positive. It's an important idiom.
6760 if (IntegerLiteral *I
6761 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
6762 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00006763 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00006764 return IntRange(R.Width, /*NonNegative*/ true);
6765 }
6766 }
6767 // fallthrough
6768
John McCalle3027922010-08-25 11:45:40 +00006769 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00006770 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006771
John McCall2ce81ad2010-01-06 22:07:33 +00006772 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00006773 case BO_Shr:
6774 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00006775 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
6776
6777 // If the shift amount is a positive constant, drop the width by
6778 // that much.
6779 llvm::APSInt shift;
6780 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
6781 shift.isNonNegative()) {
6782 unsigned zext = shift.getZExtValue();
6783 if (zext >= L.Width)
6784 L.Width = (L.NonNegative ? 0 : 1);
6785 else
6786 L.Width -= zext;
6787 }
6788
6789 return L;
6790 }
6791
6792 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00006793 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00006794 return GetExprRange(C, BO->getRHS(), MaxWidth);
6795
John McCall2ce81ad2010-01-06 22:07:33 +00006796 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00006797 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00006798 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00006799 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00006800 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006801
John McCall51431812011-07-14 22:39:48 +00006802 // The width of a division result is mostly determined by the size
6803 // of the LHS.
6804 case BO_Div: {
6805 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00006806 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00006807 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
6808
6809 // If the divisor is constant, use that.
6810 llvm::APSInt divisor;
6811 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
6812 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
6813 if (log2 >= L.Width)
6814 L.Width = (L.NonNegative ? 0 : 1);
6815 else
6816 L.Width = std::min(L.Width - log2, MaxWidth);
6817 return L;
6818 }
6819
6820 // Otherwise, just use the LHS's width.
6821 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
6822 return IntRange(L.Width, L.NonNegative && R.NonNegative);
6823 }
6824
6825 // The result of a remainder can't be larger than the result of
6826 // either side.
6827 case BO_Rem: {
6828 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00006829 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00006830 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
6831 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
6832
6833 IntRange meet = IntRange::meet(L, R);
6834 meet.Width = std::min(meet.Width, MaxWidth);
6835 return meet;
6836 }
6837
6838 // The default behavior is okay for these.
6839 case BO_Mul:
6840 case BO_Add:
6841 case BO_Xor:
6842 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00006843 break;
6844 }
6845
John McCall51431812011-07-14 22:39:48 +00006846 // The default case is to treat the operation as if it were closed
6847 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00006848 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
6849 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
6850 return IntRange::join(L, R);
6851 }
6852
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00006853 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00006854 switch (UO->getOpcode()) {
6855 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00006856 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00006857 return IntRange::forBoolType();
6858
6859 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00006860 case UO_Deref:
6861 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00006862 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006863
6864 default:
6865 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
6866 }
6867 }
6868
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00006869 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
Ted Kremeneka553fbf2013-10-14 18:55:27 +00006870 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
6871
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00006872 if (const auto *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00006873 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00006874 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00006875
Eli Friedmane6d33952013-07-08 20:20:06 +00006876 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006877}
John McCall263a48b2010-01-04 23:31:57 +00006878
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006879IntRange GetExprRange(ASTContext &C, const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00006880 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00006881}
6882
John McCall263a48b2010-01-04 23:31:57 +00006883/// Checks whether the given value, which currently has the given
6884/// source semantics, has the same value when coerced through the
6885/// target semantics.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006886bool IsSameFloatAfterCast(const llvm::APFloat &value,
6887 const llvm::fltSemantics &Src,
6888 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00006889 llvm::APFloat truncated = value;
6890
6891 bool ignored;
6892 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
6893 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
6894
6895 return truncated.bitwiseIsEqual(value);
6896}
6897
6898/// Checks whether the given value, which currently has the given
6899/// source semantics, has the same value when coerced through the
6900/// target semantics.
6901///
6902/// The value might be a vector of floats (or a complex number).
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006903bool IsSameFloatAfterCast(const APValue &value,
6904 const llvm::fltSemantics &Src,
6905 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00006906 if (value.isFloat())
6907 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
6908
6909 if (value.isVector()) {
6910 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
6911 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
6912 return false;
6913 return true;
6914 }
6915
6916 assert(value.isComplexFloat());
6917 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
6918 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
6919}
6920
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006921void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006922
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006923bool IsZero(Sema &S, Expr *E) {
Ted Kremenek6274be42010-09-23 21:43:44 +00006924 // Suppress cases where we are comparing against an enum constant.
6925 if (const DeclRefExpr *DR =
6926 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
6927 if (isa<EnumConstantDecl>(DR->getDecl()))
6928 return false;
6929
6930 // Suppress cases where the '0' value is expanded from a macro.
6931 if (E->getLocStart().isMacroID())
6932 return false;
6933
John McCallcc7e5bf2010-05-06 08:58:33 +00006934 llvm::APSInt Value;
6935 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
6936}
6937
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006938bool HasEnumType(Expr *E) {
John McCall2551c1b2010-10-06 00:25:24 +00006939 // Strip off implicit integral promotions.
6940 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00006941 if (ICE->getCastKind() != CK_IntegralCast &&
6942 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00006943 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00006944 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00006945 }
6946
6947 return E->getType()->isEnumeralType();
6948}
6949
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006950void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00006951 // Disable warning in template instantiations.
6952 if (!S.ActiveTemplateInstantiations.empty())
6953 return;
6954
John McCalle3027922010-08-25 11:45:40 +00006955 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00006956 if (E->isValueDependent())
6957 return;
6958
John McCalle3027922010-08-25 11:45:40 +00006959 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006960 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006961 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006962 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00006963 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006964 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006965 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006966 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00006967 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006968 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006969 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006970 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00006971 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006972 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006973 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006974 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
6975 }
6976}
6977
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006978void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
6979 Expr *Constant, Expr *Other,
6980 llvm::APSInt Value,
6981 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00006982 // Disable warning in template instantiations.
6983 if (!S.ActiveTemplateInstantiations.empty())
6984 return;
6985
Richard Trieu0f097742014-04-04 04:13:47 +00006986 // TODO: Investigate using GetExprRange() to get tighter bounds
6987 // on the bit ranges.
6988 QualType OtherT = Other->getType();
David Majnemer7800f1f2015-05-23 01:32:17 +00006989 if (const auto *AT = OtherT->getAs<AtomicType>())
Justin Bogner4f42fc42014-07-21 18:01:53 +00006990 OtherT = AT->getValueType();
Richard Trieu0f097742014-04-04 04:13:47 +00006991 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
6992 unsigned OtherWidth = OtherRange.Width;
6993
6994 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
6995
Richard Trieu560910c2012-11-14 22:50:24 +00006996 // 0 values are handled later by CheckTrivialUnsignedComparison().
Richard Trieu0f097742014-04-04 04:13:47 +00006997 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00006998 return;
6999
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007000 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00007001 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00007002
Richard Trieu0f097742014-04-04 04:13:47 +00007003 // Used for diagnostic printout.
7004 enum {
7005 LiteralConstant = 0,
7006 CXXBoolLiteralTrue,
7007 CXXBoolLiteralFalse
7008 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00007009
Richard Trieu0f097742014-04-04 04:13:47 +00007010 if (!OtherIsBooleanType) {
7011 QualType ConstantT = Constant->getType();
7012 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00007013
Richard Trieu0f097742014-04-04 04:13:47 +00007014 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
7015 return;
7016 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
7017 "comparison with non-integer type");
7018
7019 bool ConstantSigned = ConstantT->isSignedIntegerType();
7020 bool CommonSigned = CommonT->isSignedIntegerType();
7021
7022 bool EqualityOnly = false;
7023
7024 if (CommonSigned) {
7025 // The common type is signed, therefore no signed to unsigned conversion.
7026 if (!OtherRange.NonNegative) {
7027 // Check that the constant is representable in type OtherT.
7028 if (ConstantSigned) {
7029 if (OtherWidth >= Value.getMinSignedBits())
7030 return;
7031 } else { // !ConstantSigned
7032 if (OtherWidth >= Value.getActiveBits() + 1)
7033 return;
7034 }
7035 } else { // !OtherSigned
7036 // Check that the constant is representable in type OtherT.
7037 // Negative values are out of range.
7038 if (ConstantSigned) {
7039 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
7040 return;
7041 } else { // !ConstantSigned
7042 if (OtherWidth >= Value.getActiveBits())
7043 return;
7044 }
Richard Trieu560910c2012-11-14 22:50:24 +00007045 }
Richard Trieu0f097742014-04-04 04:13:47 +00007046 } else { // !CommonSigned
7047 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00007048 if (OtherWidth >= Value.getActiveBits())
7049 return;
Craig Toppercf360162014-06-18 05:13:11 +00007050 } else { // OtherSigned
7051 assert(!ConstantSigned &&
7052 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00007053 // Check to see if the constant is representable in OtherT.
7054 if (OtherWidth > Value.getActiveBits())
7055 return;
7056 // Check to see if the constant is equivalent to a negative value
7057 // cast to CommonT.
7058 if (S.Context.getIntWidth(ConstantT) ==
7059 S.Context.getIntWidth(CommonT) &&
7060 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
7061 return;
7062 // The constant value rests between values that OtherT can represent
7063 // after conversion. Relational comparison still works, but equality
7064 // comparisons will be tautological.
7065 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00007066 }
7067 }
Richard Trieu0f097742014-04-04 04:13:47 +00007068
7069 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
7070
7071 if (op == BO_EQ || op == BO_NE) {
7072 IsTrue = op == BO_NE;
7073 } else if (EqualityOnly) {
7074 return;
7075 } else if (RhsConstant) {
7076 if (op == BO_GT || op == BO_GE)
7077 IsTrue = !PositiveConstant;
7078 else // op == BO_LT || op == BO_LE
7079 IsTrue = PositiveConstant;
7080 } else {
7081 if (op == BO_LT || op == BO_LE)
7082 IsTrue = !PositiveConstant;
7083 else // op == BO_GT || op == BO_GE
7084 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00007085 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00007086 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00007087 // Other isKnownToHaveBooleanValue
7088 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
7089 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
7090 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
7091
7092 static const struct LinkedConditions {
7093 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
7094 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
7095 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
7096 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
7097 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
7098 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
7099
7100 } TruthTable = {
7101 // Constant on LHS. | Constant on RHS. |
7102 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
7103 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
7104 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
7105 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
7106 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
7107 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
7108 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
7109 };
7110
7111 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
7112
7113 enum ConstantValue ConstVal = Zero;
7114 if (Value.isUnsigned() || Value.isNonNegative()) {
7115 if (Value == 0) {
7116 LiteralOrBoolConstant =
7117 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
7118 ConstVal = Zero;
7119 } else if (Value == 1) {
7120 LiteralOrBoolConstant =
7121 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
7122 ConstVal = One;
7123 } else {
7124 LiteralOrBoolConstant = LiteralConstant;
7125 ConstVal = GT_One;
7126 }
7127 } else {
7128 ConstVal = LT_Zero;
7129 }
7130
7131 CompareBoolWithConstantResult CmpRes;
7132
7133 switch (op) {
7134 case BO_LT:
7135 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
7136 break;
7137 case BO_GT:
7138 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
7139 break;
7140 case BO_LE:
7141 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
7142 break;
7143 case BO_GE:
7144 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
7145 break;
7146 case BO_EQ:
7147 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
7148 break;
7149 case BO_NE:
7150 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
7151 break;
7152 default:
7153 CmpRes = Unkwn;
7154 break;
7155 }
7156
7157 if (CmpRes == AFals) {
7158 IsTrue = false;
7159 } else if (CmpRes == ATrue) {
7160 IsTrue = true;
7161 } else {
7162 return;
7163 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007164 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00007165
7166 // If this is a comparison to an enum constant, include that
7167 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00007168 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00007169 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
7170 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
7171
7172 SmallString<64> PrettySourceValue;
7173 llvm::raw_svector_ostream OS(PrettySourceValue);
7174 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00007175 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00007176 else
7177 OS << Value;
7178
Richard Trieu0f097742014-04-04 04:13:47 +00007179 S.DiagRuntimeBehavior(
7180 E->getOperatorLoc(), E,
7181 S.PDiag(diag::warn_out_of_range_compare)
7182 << OS.str() << LiteralOrBoolConstant
7183 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
7184 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007185}
7186
John McCallcc7e5bf2010-05-06 08:58:33 +00007187/// Analyze the operands of the given comparison. Implements the
7188/// fallback case from AnalyzeComparison.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007189void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00007190 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
7191 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00007192}
John McCall263a48b2010-01-04 23:31:57 +00007193
John McCallca01b222010-01-04 23:21:16 +00007194/// \brief Implements -Wsign-compare.
7195///
Richard Trieu82402a02011-09-15 21:56:47 +00007196/// \param E the binary operator to check for warnings
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007197void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007198 // The type the comparison is being performed in.
7199 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00007200
7201 // Only analyze comparison operators where both sides have been converted to
7202 // the same type.
7203 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
7204 return AnalyzeImpConvsInComparison(S, E);
7205
7206 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00007207 if (E->isValueDependent())
7208 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00007209
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007210 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
7211 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007212
7213 bool IsComparisonConstant = false;
7214
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00007215 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007216 // of 'true' or 'false'.
7217 if (T->isIntegralType(S.Context)) {
7218 llvm::APSInt RHSValue;
7219 bool IsRHSIntegralLiteral =
7220 RHS->isIntegerConstantExpr(RHSValue, S.Context);
7221 llvm::APSInt LHSValue;
7222 bool IsLHSIntegralLiteral =
7223 LHS->isIntegerConstantExpr(LHSValue, S.Context);
7224 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
7225 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
7226 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
7227 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
7228 else
7229 IsComparisonConstant =
7230 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00007231 } else if (!T->hasUnsignedIntegerRepresentation())
7232 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007233
John McCallcc7e5bf2010-05-06 08:58:33 +00007234 // We don't do anything special if this isn't an unsigned integral
7235 // comparison: we're only interested in integral comparisons, and
7236 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00007237 //
7238 // We also don't care about value-dependent expressions or expressions
7239 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007240 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00007241 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007242
John McCallcc7e5bf2010-05-06 08:58:33 +00007243 // Check to see if one of the (unmodified) operands is of different
7244 // signedness.
7245 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00007246 if (LHS->getType()->hasSignedIntegerRepresentation()) {
7247 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00007248 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00007249 signedOperand = LHS;
7250 unsignedOperand = RHS;
7251 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
7252 signedOperand = RHS;
7253 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00007254 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00007255 CheckTrivialUnsignedComparison(S, E);
7256 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00007257 }
7258
John McCallcc7e5bf2010-05-06 08:58:33 +00007259 // Otherwise, calculate the effective range of the signed operand.
7260 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00007261
John McCallcc7e5bf2010-05-06 08:58:33 +00007262 // Go ahead and analyze implicit conversions in the operands. Note
7263 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00007264 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
7265 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00007266
John McCallcc7e5bf2010-05-06 08:58:33 +00007267 // If the signed range is non-negative, -Wsign-compare won't fire,
7268 // but we should still check for comparisons which are always true
7269 // or false.
7270 if (signedRange.NonNegative)
7271 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00007272
7273 // For (in)equality comparisons, if the unsigned operand is a
7274 // constant which cannot collide with a overflowed signed operand,
7275 // then reinterpreting the signed operand as unsigned will not
7276 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00007277 if (E->isEqualityOp()) {
7278 unsigned comparisonWidth = S.Context.getIntWidth(T);
7279 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00007280
John McCallcc7e5bf2010-05-06 08:58:33 +00007281 // We should never be unable to prove that the unsigned operand is
7282 // non-negative.
7283 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
7284
7285 if (unsignedRange.Width < comparisonWidth)
7286 return;
7287 }
7288
Douglas Gregorbfb4a212012-05-01 01:53:49 +00007289 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
7290 S.PDiag(diag::warn_mixed_sign_comparison)
7291 << LHS->getType() << RHS->getType()
7292 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00007293}
7294
John McCall1f425642010-11-11 03:21:53 +00007295/// Analyzes an attempt to assign the given value to a bitfield.
7296///
7297/// Returns true if there was something fishy about the attempt.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007298bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
7299 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00007300 assert(Bitfield->isBitField());
7301 if (Bitfield->isInvalidDecl())
7302 return false;
7303
John McCalldeebbcf2010-11-11 05:33:51 +00007304 // White-list bool bitfields.
7305 if (Bitfield->getType()->isBooleanType())
7306 return false;
7307
Douglas Gregor789adec2011-02-04 13:09:01 +00007308 // Ignore value- or type-dependent expressions.
7309 if (Bitfield->getBitWidth()->isValueDependent() ||
7310 Bitfield->getBitWidth()->isTypeDependent() ||
7311 Init->isValueDependent() ||
7312 Init->isTypeDependent())
7313 return false;
7314
John McCall1f425642010-11-11 03:21:53 +00007315 Expr *OriginalInit = Init->IgnoreParenImpCasts();
7316
Richard Smith5fab0c92011-12-28 19:48:30 +00007317 llvm::APSInt Value;
7318 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00007319 return false;
7320
John McCall1f425642010-11-11 03:21:53 +00007321 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00007322 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00007323
7324 if (OriginalWidth <= FieldWidth)
7325 return false;
7326
Eli Friedmanc267a322012-01-26 23:11:39 +00007327 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00007328 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedmanc267a322012-01-26 23:11:39 +00007329 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00007330
Eli Friedmanc267a322012-01-26 23:11:39 +00007331 // Check whether the stored value is equal to the original value.
7332 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00007333 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00007334 return false;
7335
Eli Friedmanc267a322012-01-26 23:11:39 +00007336 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00007337 // therefore don't strictly fit into a signed bitfield of width 1.
7338 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00007339 return false;
7340
John McCall1f425642010-11-11 03:21:53 +00007341 std::string PrettyValue = Value.toString(10);
7342 std::string PrettyTrunc = TruncatedValue.toString(10);
7343
7344 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
7345 << PrettyValue << PrettyTrunc << OriginalInit->getType()
7346 << Init->getSourceRange();
7347
7348 return true;
7349}
7350
John McCalld2a53122010-11-09 23:24:47 +00007351/// Analyze the given simple or compound assignment for warning-worthy
7352/// operations.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007353void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00007354 // Just recurse on the LHS.
7355 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
7356
7357 // We want to recurse on the RHS as normal unless we're assigning to
7358 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00007359 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007360 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00007361 E->getOperatorLoc())) {
7362 // Recurse, ignoring any implicit conversions on the RHS.
7363 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
7364 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00007365 }
7366 }
7367
7368 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
7369}
7370
John McCall263a48b2010-01-04 23:31:57 +00007371/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007372void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
7373 SourceLocation CContext, unsigned diag,
7374 bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00007375 if (pruneControlFlow) {
7376 S.DiagRuntimeBehavior(E->getExprLoc(), E,
7377 S.PDiag(diag)
7378 << SourceType << T << E->getSourceRange()
7379 << SourceRange(CContext));
7380 return;
7381 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00007382 S.Diag(E->getExprLoc(), diag)
7383 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
7384}
7385
Chandler Carruth7f3654f2011-04-05 06:47:57 +00007386/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007387void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
7388 unsigned diag, bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00007389 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00007390}
7391
Richard Trieube234c32016-04-21 21:04:55 +00007392
7393/// Diagnose an implicit cast from a floating point value to an integer value.
7394void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
7395
7396 SourceLocation CContext) {
7397 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
7398 const bool PruneWarnings = !S.ActiveTemplateInstantiations.empty();
7399
7400 Expr *InnerE = E->IgnoreParenImpCasts();
7401 // We also want to warn on, e.g., "int i = -1.234"
7402 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
7403 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
7404 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
7405
7406 const bool IsLiteral =
7407 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
7408
7409 llvm::APFloat Value(0.0);
7410 bool IsConstant =
7411 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
7412 if (!IsConstant) {
Richard Trieu891f0f12016-04-22 22:14:32 +00007413 return DiagnoseImpCast(S, E, T, CContext,
7414 diag::warn_impcast_float_integer, PruneWarnings);
Richard Trieube234c32016-04-21 21:04:55 +00007415 }
7416
Chandler Carruth016ef402011-04-10 08:36:24 +00007417 bool isExact = false;
Richard Trieube234c32016-04-21 21:04:55 +00007418
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00007419 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
7420 T->hasUnsignedIntegerRepresentation());
Richard Trieube234c32016-04-21 21:04:55 +00007421 if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero,
7422 &isExact) == llvm::APFloat::opOK &&
Richard Trieu891f0f12016-04-22 22:14:32 +00007423 isExact) {
Richard Trieube234c32016-04-21 21:04:55 +00007424 if (IsLiteral) return;
7425 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
7426 PruneWarnings);
7427 }
7428
7429 unsigned DiagID = 0;
Richard Trieu891f0f12016-04-22 22:14:32 +00007430 if (IsLiteral) {
Richard Trieube234c32016-04-21 21:04:55 +00007431 // Warn on floating point literal to integer.
7432 DiagID = diag::warn_impcast_literal_float_to_integer;
7433 } else if (IntegerValue == 0) {
7434 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
7435 return DiagnoseImpCast(S, E, T, CContext,
7436 diag::warn_impcast_float_integer, PruneWarnings);
7437 }
7438 // Warn on non-zero to zero conversion.
7439 DiagID = diag::warn_impcast_float_to_integer_zero;
7440 } else {
7441 if (IntegerValue.isUnsigned()) {
7442 if (!IntegerValue.isMaxValue()) {
7443 return DiagnoseImpCast(S, E, T, CContext,
7444 diag::warn_impcast_float_integer, PruneWarnings);
7445 }
7446 } else { // IntegerValue.isSigned()
7447 if (!IntegerValue.isMaxSignedValue() &&
7448 !IntegerValue.isMinSignedValue()) {
7449 return DiagnoseImpCast(S, E, T, CContext,
7450 diag::warn_impcast_float_integer, PruneWarnings);
7451 }
7452 }
7453 // Warn on evaluatable floating point expression to integer conversion.
7454 DiagID = diag::warn_impcast_float_to_integer;
7455 }
Chandler Carruth016ef402011-04-10 08:36:24 +00007456
Eli Friedman07185912013-08-29 23:44:43 +00007457 // FIXME: Force the precision of the source value down so we don't print
7458 // digits which are usually useless (we don't really care here if we
7459 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
7460 // would automatically print the shortest representation, but it's a bit
7461 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00007462 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00007463 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
7464 precision = (precision * 59 + 195) / 196;
7465 Value.toString(PrettySourceValue, precision);
7466
David Blaikie9b88cc02012-05-15 17:18:27 +00007467 SmallString<16> PrettyTargetValue;
Richard Trieube234c32016-04-21 21:04:55 +00007468 if (IsBool)
Aaron Ballmandbc441e2015-12-30 14:26:07 +00007469 PrettyTargetValue = Value.isZero() ? "false" : "true";
David Blaikie7555b6a2012-05-15 16:56:36 +00007470 else
David Blaikie9b88cc02012-05-15 17:18:27 +00007471 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00007472
Richard Trieube234c32016-04-21 21:04:55 +00007473 if (PruneWarnings) {
7474 S.DiagRuntimeBehavior(E->getExprLoc(), E,
7475 S.PDiag(DiagID)
7476 << E->getType() << T.getUnqualifiedType()
7477 << PrettySourceValue << PrettyTargetValue
7478 << E->getSourceRange() << SourceRange(CContext));
7479 } else {
7480 S.Diag(E->getExprLoc(), DiagID)
7481 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
7482 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
7483 }
Chandler Carruth016ef402011-04-10 08:36:24 +00007484}
7485
John McCall18a2c2c2010-11-09 22:22:12 +00007486std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
7487 if (!Range.Width) return "0";
7488
7489 llvm::APSInt ValueInRange = Value;
7490 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00007491 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00007492 return ValueInRange.toString(10);
7493}
7494
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007495bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00007496 if (!isa<ImplicitCastExpr>(Ex))
7497 return false;
7498
7499 Expr *InnerE = Ex->IgnoreParenImpCasts();
7500 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
7501 const Type *Source =
7502 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
7503 if (Target->isDependentType())
7504 return false;
7505
7506 const BuiltinType *FloatCandidateBT =
7507 dyn_cast<BuiltinType>(ToBool ? Source : Target);
7508 const Type *BoolCandidateType = ToBool ? Target : Source;
7509
7510 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
7511 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
7512}
7513
7514void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
7515 SourceLocation CC) {
7516 unsigned NumArgs = TheCall->getNumArgs();
7517 for (unsigned i = 0; i < NumArgs; ++i) {
7518 Expr *CurrA = TheCall->getArg(i);
7519 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
7520 continue;
7521
7522 bool IsSwapped = ((i > 0) &&
7523 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
7524 IsSwapped |= ((i < (NumArgs - 1)) &&
7525 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
7526 if (IsSwapped) {
7527 // Warn on this floating-point to bool conversion.
7528 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
7529 CurrA->getType(), CC,
7530 diag::warn_impcast_floating_point_to_bool);
7531 }
7532 }
7533}
7534
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007535void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) {
Richard Trieu5b993502014-10-15 03:42:06 +00007536 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
7537 E->getExprLoc()))
7538 return;
7539
Richard Trieu09d6b802016-01-08 23:35:06 +00007540 // Don't warn on functions which have return type nullptr_t.
7541 if (isa<CallExpr>(E))
7542 return;
7543
Richard Trieu5b993502014-10-15 03:42:06 +00007544 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
7545 const Expr::NullPointerConstantKind NullKind =
7546 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
7547 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
7548 return;
7549
7550 // Return if target type is a safe conversion.
7551 if (T->isAnyPointerType() || T->isBlockPointerType() ||
7552 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
7553 return;
7554
7555 SourceLocation Loc = E->getSourceRange().getBegin();
7556
Richard Trieu0a5e1662016-02-13 00:58:53 +00007557 // Venture through the macro stacks to get to the source of macro arguments.
7558 // The new location is a better location than the complete location that was
7559 // passed in.
7560 while (S.SourceMgr.isMacroArgExpansion(Loc))
7561 Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc);
7562
7563 while (S.SourceMgr.isMacroArgExpansion(CC))
7564 CC = S.SourceMgr.getImmediateMacroCallerLoc(CC);
7565
Richard Trieu5b993502014-10-15 03:42:06 +00007566 // __null is usually wrapped in a macro. Go up a macro if that is the case.
Richard Trieu0a5e1662016-02-13 00:58:53 +00007567 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
7568 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
7569 Loc, S.SourceMgr, S.getLangOpts());
7570 if (MacroName == "NULL")
7571 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
Richard Trieu5b993502014-10-15 03:42:06 +00007572 }
7573
7574 // Only warn if the null and context location are in the same macro expansion.
7575 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
7576 return;
7577
7578 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
7579 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
7580 << FixItHint::CreateReplacement(Loc,
7581 S.getFixItZeroLiteralForType(T, Loc));
7582}
7583
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007584void checkObjCArrayLiteral(Sema &S, QualType TargetType,
7585 ObjCArrayLiteral *ArrayLiteral);
7586void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
7587 ObjCDictionaryLiteral *DictionaryLiteral);
Douglas Gregor5054cb02015-07-07 03:58:22 +00007588
7589/// Check a single element within a collection literal against the
7590/// target element type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007591void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType,
7592 Expr *Element, unsigned ElementKind) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00007593 // Skip a bitcast to 'id' or qualified 'id'.
7594 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
7595 if (ICE->getCastKind() == CK_BitCast &&
7596 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
7597 Element = ICE->getSubExpr();
7598 }
7599
7600 QualType ElementType = Element->getType();
7601 ExprResult ElementResult(Element);
7602 if (ElementType->getAs<ObjCObjectPointerType>() &&
7603 S.CheckSingleAssignmentConstraints(TargetElementType,
7604 ElementResult,
7605 false, false)
7606 != Sema::Compatible) {
7607 S.Diag(Element->getLocStart(),
7608 diag::warn_objc_collection_literal_element)
7609 << ElementType << ElementKind << TargetElementType
7610 << Element->getSourceRange();
7611 }
7612
7613 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
7614 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
7615 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
7616 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
7617}
7618
7619/// Check an Objective-C array literal being converted to the given
7620/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007621void checkObjCArrayLiteral(Sema &S, QualType TargetType,
7622 ObjCArrayLiteral *ArrayLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00007623 if (!S.NSArrayDecl)
7624 return;
7625
7626 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
7627 if (!TargetObjCPtr)
7628 return;
7629
7630 if (TargetObjCPtr->isUnspecialized() ||
7631 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
7632 != S.NSArrayDecl->getCanonicalDecl())
7633 return;
7634
7635 auto TypeArgs = TargetObjCPtr->getTypeArgs();
7636 if (TypeArgs.size() != 1)
7637 return;
7638
7639 QualType TargetElementType = TypeArgs[0];
7640 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
7641 checkObjCCollectionLiteralElement(S, TargetElementType,
7642 ArrayLiteral->getElement(I),
7643 0);
7644 }
7645}
7646
7647/// Check an Objective-C dictionary literal being converted to the given
7648/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007649void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
7650 ObjCDictionaryLiteral *DictionaryLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00007651 if (!S.NSDictionaryDecl)
7652 return;
7653
7654 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
7655 if (!TargetObjCPtr)
7656 return;
7657
7658 if (TargetObjCPtr->isUnspecialized() ||
7659 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
7660 != S.NSDictionaryDecl->getCanonicalDecl())
7661 return;
7662
7663 auto TypeArgs = TargetObjCPtr->getTypeArgs();
7664 if (TypeArgs.size() != 2)
7665 return;
7666
7667 QualType TargetKeyType = TypeArgs[0];
7668 QualType TargetObjectType = TypeArgs[1];
7669 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
7670 auto Element = DictionaryLiteral->getKeyValueElement(I);
7671 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
7672 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
7673 }
7674}
7675
Richard Trieufc404c72016-02-05 23:02:38 +00007676// Helper function to filter out cases for constant width constant conversion.
7677// Don't warn on char array initialization or for non-decimal values.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007678bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
7679 SourceLocation CC) {
Richard Trieufc404c72016-02-05 23:02:38 +00007680 // If initializing from a constant, and the constant starts with '0',
7681 // then it is a binary, octal, or hexadecimal. Allow these constants
7682 // to fill all the bits, even if there is a sign change.
7683 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
7684 const char FirstLiteralCharacter =
7685 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
7686 if (FirstLiteralCharacter == '0')
7687 return false;
7688 }
7689
7690 // If the CC location points to a '{', and the type is char, then assume
7691 // assume it is an array initialization.
7692 if (CC.isValid() && T->isCharType()) {
7693 const char FirstContextCharacter =
7694 S.getSourceManager().getCharacterData(CC)[0];
7695 if (FirstContextCharacter == '{')
7696 return false;
7697 }
7698
7699 return true;
7700}
7701
John McCallcc7e5bf2010-05-06 08:58:33 +00007702void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00007703 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007704 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00007705
John McCallcc7e5bf2010-05-06 08:58:33 +00007706 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
7707 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
7708 if (Source == Target) return;
7709 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00007710
Chandler Carruthc22845a2011-07-26 05:40:03 +00007711 // If the conversion context location is invalid don't complain. We also
7712 // don't want to emit a warning if the issue occurs from the expansion of
7713 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
7714 // delay this check as long as possible. Once we detect we are in that
7715 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007716 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00007717 return;
7718
Richard Trieu021baa32011-09-23 20:10:00 +00007719 // Diagnose implicit casts to bool.
7720 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
7721 if (isa<StringLiteral>(E))
7722 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00007723 // and expressions, for instance, assert(0 && "error here"), are
7724 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00007725 return DiagnoseImpCast(S, E, T, CC,
7726 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00007727 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
7728 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
7729 // This covers the literal expressions that evaluate to Objective-C
7730 // objects.
7731 return DiagnoseImpCast(S, E, T, CC,
7732 diag::warn_impcast_objective_c_literal_to_bool);
7733 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00007734 if (Source->isPointerType() || Source->canDecayToPointerType()) {
7735 // Warn on pointer to bool conversion that is always true.
7736 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
7737 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00007738 }
Richard Trieu021baa32011-09-23 20:10:00 +00007739 }
John McCall263a48b2010-01-04 23:31:57 +00007740
Douglas Gregor5054cb02015-07-07 03:58:22 +00007741 // Check implicit casts from Objective-C collection literals to specialized
7742 // collection types, e.g., NSArray<NSString *> *.
7743 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
7744 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
7745 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
7746 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
7747
John McCall263a48b2010-01-04 23:31:57 +00007748 // Strip vector types.
7749 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007750 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007751 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007752 return;
John McCallacf0ee52010-10-08 02:01:28 +00007753 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007754 }
Chris Lattneree7286f2011-06-14 04:51:15 +00007755
7756 // If the vector cast is cast between two vectors of the same size, it is
7757 // a bitcast, not a conversion.
7758 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
7759 return;
John McCall263a48b2010-01-04 23:31:57 +00007760
7761 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
7762 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
7763 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00007764 if (auto VecTy = dyn_cast<VectorType>(Target))
7765 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00007766
7767 // Strip complex types.
7768 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007769 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007770 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007771 return;
7772
John McCallacf0ee52010-10-08 02:01:28 +00007773 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007774 }
John McCall263a48b2010-01-04 23:31:57 +00007775
7776 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
7777 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
7778 }
7779
7780 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
7781 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
7782
7783 // If the source is floating point...
7784 if (SourceBT && SourceBT->isFloatingPoint()) {
7785 // ...and the target is floating point...
7786 if (TargetBT && TargetBT->isFloatingPoint()) {
7787 // ...then warn if we're dropping FP rank.
7788
7789 // Builtin FP kinds are ordered by increasing FP rank.
7790 if (SourceBT->getKind() > TargetBT->getKind()) {
7791 // Don't warn about float constants that are precisely
7792 // representable in the target type.
7793 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00007794 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00007795 // Value might be a float, a float vector, or a float complex.
7796 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00007797 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
7798 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00007799 return;
7800 }
7801
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007802 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007803 return;
7804
John McCallacf0ee52010-10-08 02:01:28 +00007805 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
George Burgess IV148e0d32015-10-29 00:28:52 +00007806 }
7807 // ... or possibly if we're increasing rank, too
7808 else if (TargetBT->getKind() > SourceBT->getKind()) {
7809 if (S.SourceMgr.isInSystemMacro(CC))
7810 return;
7811
7812 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
John McCall263a48b2010-01-04 23:31:57 +00007813 }
7814 return;
7815 }
7816
Richard Trieube234c32016-04-21 21:04:55 +00007817 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00007818 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007819 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007820 return;
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00007821
Richard Trieube234c32016-04-21 21:04:55 +00007822 DiagnoseFloatingImpCast(S, E, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00007823 }
John McCall263a48b2010-01-04 23:31:57 +00007824
Richard Smith54894fd2015-12-30 01:06:52 +00007825 // Detect the case where a call result is converted from floating-point to
7826 // to bool, and the final argument to the call is converted from bool, to
7827 // discover this typo:
7828 //
7829 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
7830 //
7831 // FIXME: This is an incredibly special case; is there some more general
7832 // way to detect this class of misplaced-parentheses bug?
7833 if (Target->isBooleanType() && isa<CallExpr>(E)) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00007834 // Check last argument of function call to see if it is an
7835 // implicit cast from a type matching the type the result
7836 // is being cast to.
7837 CallExpr *CEx = cast<CallExpr>(E);
Richard Smith54894fd2015-12-30 01:06:52 +00007838 if (unsigned NumArgs = CEx->getNumArgs()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00007839 Expr *LastA = CEx->getArg(NumArgs - 1);
7840 Expr *InnerE = LastA->IgnoreParenImpCasts();
Richard Smith54894fd2015-12-30 01:06:52 +00007841 if (isa<ImplicitCastExpr>(LastA) &&
7842 InnerE->getType()->isBooleanType()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00007843 // Warn on this floating-point to bool conversion
7844 DiagnoseImpCast(S, E, T, CC,
7845 diag::warn_impcast_floating_point_to_bool);
7846 }
7847 }
7848 }
John McCall263a48b2010-01-04 23:31:57 +00007849 return;
7850 }
7851
Richard Trieu5b993502014-10-15 03:42:06 +00007852 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +00007853
David Blaikie9366d2b2012-06-19 21:19:06 +00007854 if (!Source->isIntegerType() || !Target->isIntegerType())
7855 return;
7856
David Blaikie7555b6a2012-05-15 16:56:36 +00007857 // TODO: remove this early return once the false positives for constant->bool
7858 // in templates, macros, etc, are reduced or removed.
7859 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
7860 return;
7861
John McCallcc7e5bf2010-05-06 08:58:33 +00007862 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00007863 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00007864
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007865 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00007866 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007867 // TODO: this should happen for bitfield stores, too.
7868 llvm::APSInt Value(32);
Richard Trieudcb55572016-01-29 23:51:16 +00007869 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007870 if (S.SourceMgr.isInSystemMacro(CC))
7871 return;
7872
John McCall18a2c2c2010-11-09 22:22:12 +00007873 std::string PrettySourceValue = Value.toString(10);
7874 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007875
Ted Kremenek33ba9952011-10-22 02:37:33 +00007876 S.DiagRuntimeBehavior(E->getExprLoc(), E,
7877 S.PDiag(diag::warn_impcast_integer_precision_constant)
7878 << PrettySourceValue << PrettyTargetValue
7879 << E->getType() << T << E->getSourceRange()
7880 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00007881 return;
7882 }
7883
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007884 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
7885 if (S.SourceMgr.isInSystemMacro(CC))
7886 return;
7887
David Blaikie9455da02012-04-12 22:40:54 +00007888 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00007889 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
7890 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00007891 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00007892 }
7893
Richard Trieudcb55572016-01-29 23:51:16 +00007894 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
7895 SourceRange.NonNegative && Source->isSignedIntegerType()) {
7896 // Warn when doing a signed to signed conversion, warn if the positive
7897 // source value is exactly the width of the target type, which will
7898 // cause a negative value to be stored.
7899
7900 llvm::APSInt Value;
Richard Trieufc404c72016-02-05 23:02:38 +00007901 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
7902 !S.SourceMgr.isInSystemMacro(CC)) {
7903 if (isSameWidthConstantConversion(S, E, T, CC)) {
7904 std::string PrettySourceValue = Value.toString(10);
7905 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Richard Trieudcb55572016-01-29 23:51:16 +00007906
Richard Trieufc404c72016-02-05 23:02:38 +00007907 S.DiagRuntimeBehavior(
7908 E->getExprLoc(), E,
7909 S.PDiag(diag::warn_impcast_integer_precision_constant)
7910 << PrettySourceValue << PrettyTargetValue << E->getType() << T
7911 << E->getSourceRange() << clang::SourceRange(CC));
7912 return;
Richard Trieudcb55572016-01-29 23:51:16 +00007913 }
7914 }
Richard Trieufc404c72016-02-05 23:02:38 +00007915
Richard Trieudcb55572016-01-29 23:51:16 +00007916 // Fall through for non-constants to give a sign conversion warning.
7917 }
7918
John McCallcc7e5bf2010-05-06 08:58:33 +00007919 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
7920 (!TargetRange.NonNegative && SourceRange.NonNegative &&
7921 SourceRange.Width == TargetRange.Width)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007922 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007923 return;
7924
John McCallcc7e5bf2010-05-06 08:58:33 +00007925 unsigned DiagID = diag::warn_impcast_integer_sign;
7926
7927 // Traditionally, gcc has warned about this under -Wsign-compare.
7928 // We also want to warn about it in -Wconversion.
7929 // So if -Wconversion is off, use a completely identical diagnostic
7930 // in the sign-compare group.
7931 // The conditional-checking code will
7932 if (ICContext) {
7933 DiagID = diag::warn_impcast_integer_sign_conditional;
7934 *ICContext = true;
7935 }
7936
John McCallacf0ee52010-10-08 02:01:28 +00007937 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00007938 }
7939
Douglas Gregora78f1932011-02-22 02:45:07 +00007940 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00007941 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
7942 // type, to give us better diagnostics.
7943 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00007944 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00007945 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
7946 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
7947 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
7948 SourceType = S.Context.getTypeDeclType(Enum);
7949 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
7950 }
7951 }
7952
Douglas Gregora78f1932011-02-22 02:45:07 +00007953 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
7954 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00007955 if (SourceEnum->getDecl()->hasNameForLinkage() &&
7956 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007957 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007958 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007959 return;
7960
Douglas Gregor364f7db2011-03-12 00:14:31 +00007961 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00007962 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007963 }
John McCall263a48b2010-01-04 23:31:57 +00007964}
7965
David Blaikie18e9ac72012-05-15 21:57:38 +00007966void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
7967 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00007968
7969void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00007970 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007971 E = E->IgnoreParenImpCasts();
7972
7973 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00007974 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00007975
John McCallacf0ee52010-10-08 02:01:28 +00007976 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007977 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00007978 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00007979}
7980
David Blaikie18e9ac72012-05-15 21:57:38 +00007981void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
7982 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00007983 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00007984
7985 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00007986 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
7987 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00007988
7989 // If -Wconversion would have warned about either of the candidates
7990 // for a signedness conversion to the context type...
7991 if (!Suspicious) return;
7992
7993 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007994 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00007995 return;
7996
John McCallcc7e5bf2010-05-06 08:58:33 +00007997 // ...then check whether it would have warned about either of the
7998 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00007999 if (E->getType() == T) return;
8000
8001 Suspicious = false;
8002 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
8003 E->getType(), CC, &Suspicious);
8004 if (!Suspicious)
8005 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00008006 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00008007}
8008
Richard Trieu65724892014-11-15 06:37:39 +00008009/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
8010/// Input argument E is a logical expression.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008011void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
Richard Trieu65724892014-11-15 06:37:39 +00008012 if (S.getLangOpts().Bool)
8013 return;
8014 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
8015}
8016
John McCallcc7e5bf2010-05-06 08:58:33 +00008017/// AnalyzeImplicitConversions - Find and report any interesting
8018/// implicit conversions in the given expression. There are a couple
8019/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00008020void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00008021 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00008022 Expr *E = OrigE->IgnoreParenImpCasts();
8023
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00008024 if (E->isTypeDependent() || E->isValueDependent())
8025 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00008026
John McCallcc7e5bf2010-05-06 08:58:33 +00008027 // For conditional operators, we analyze the arguments as if they
8028 // were being fed directly into the output.
8029 if (isa<ConditionalOperator>(E)) {
8030 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00008031 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00008032 return;
8033 }
8034
Hans Wennborgf4ad2322012-08-28 15:44:30 +00008035 // Check implicit argument conversions for function calls.
8036 if (CallExpr *Call = dyn_cast<CallExpr>(E))
8037 CheckImplicitArgumentConversions(S, Call, CC);
8038
John McCallcc7e5bf2010-05-06 08:58:33 +00008039 // Go ahead and check any implicit conversions we might have skipped.
8040 // The non-canonical typecheck is just an optimization;
8041 // CheckImplicitConversion will filter out dead implicit conversions.
8042 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00008043 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008044
8045 // Now continue drilling into this expression.
Richard Smithd7bed4d2015-11-22 02:57:17 +00008046
8047 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
8048 // The bound subexpressions in a PseudoObjectExpr are not reachable
8049 // as transitive children.
8050 // FIXME: Use a more uniform representation for this.
8051 for (auto *SE : POE->semantics())
8052 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
8053 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00008054 }
Richard Smithd7bed4d2015-11-22 02:57:17 +00008055
John McCallcc7e5bf2010-05-06 08:58:33 +00008056 // Skip past explicit casts.
8057 if (isa<ExplicitCastExpr>(E)) {
8058 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00008059 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008060 }
8061
John McCalld2a53122010-11-09 23:24:47 +00008062 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
8063 // Do a somewhat different check with comparison operators.
8064 if (BO->isComparisonOp())
8065 return AnalyzeComparison(S, BO);
8066
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008067 // And with simple assignments.
8068 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00008069 return AnalyzeAssignment(S, BO);
8070 }
John McCallcc7e5bf2010-05-06 08:58:33 +00008071
8072 // These break the otherwise-useful invariant below. Fortunately,
8073 // we don't really need to recurse into them, because any internal
8074 // expressions should have been analyzed already when they were
8075 // built into statements.
8076 if (isa<StmtExpr>(E)) return;
8077
8078 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00008079 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00008080
8081 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00008082 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00008083 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00008084 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Benjamin Kramer642f1732015-07-02 21:03:14 +00008085 for (Stmt *SubStmt : E->children()) {
8086 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00008087 if (!ChildExpr)
8088 continue;
8089
Richard Trieu955231d2014-01-25 01:10:35 +00008090 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00008091 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00008092 // Ignore checking string literals that are in logical and operators.
8093 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00008094 continue;
8095 AnalyzeImplicitConversions(S, ChildExpr, CC);
8096 }
Richard Trieu791b86e2014-11-19 06:08:18 +00008097
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00008098 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +00008099 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
8100 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00008101 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +00008102
8103 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
8104 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00008105 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00008106 }
Richard Trieu791b86e2014-11-19 06:08:18 +00008107
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00008108 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
8109 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +00008110 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008111}
8112
8113} // end anonymous namespace
8114
Richard Trieuc1888e02014-06-28 23:25:37 +00008115// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
8116// Returns true when emitting a warning about taking the address of a reference.
8117static bool CheckForReference(Sema &SemaRef, const Expr *E,
8118 PartialDiagnostic PD) {
8119 E = E->IgnoreParenImpCasts();
8120
8121 const FunctionDecl *FD = nullptr;
8122
8123 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
8124 if (!DRE->getDecl()->getType()->isReferenceType())
8125 return false;
8126 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
8127 if (!M->getMemberDecl()->getType()->isReferenceType())
8128 return false;
8129 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +00008130 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +00008131 return false;
8132 FD = Call->getDirectCallee();
8133 } else {
8134 return false;
8135 }
8136
8137 SemaRef.Diag(E->getExprLoc(), PD);
8138
8139 // If possible, point to location of function.
8140 if (FD) {
8141 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
8142 }
8143
8144 return true;
8145}
8146
Richard Trieu4cbff5c2014-08-08 22:41:43 +00008147// Returns true if the SourceLocation is expanded from any macro body.
8148// Returns false if the SourceLocation is invalid, is from not in a macro
8149// expansion, or is from expanded from a top-level macro argument.
8150static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
8151 if (Loc.isInvalid())
8152 return false;
8153
8154 while (Loc.isMacroID()) {
8155 if (SM.isMacroBodyExpansion(Loc))
8156 return true;
8157 Loc = SM.getImmediateMacroCallerLoc(Loc);
8158 }
8159
8160 return false;
8161}
8162
Richard Trieu3bb8b562014-02-26 02:36:06 +00008163/// \brief Diagnose pointers that are always non-null.
8164/// \param E the expression containing the pointer
8165/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
8166/// compared to a null pointer
8167/// \param IsEqual True when the comparison is equal to a null pointer
8168/// \param Range Extra SourceRange to highlight in the diagnostic
8169void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
8170 Expr::NullPointerConstantKind NullKind,
8171 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00008172 if (!E)
8173 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00008174
8175 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +00008176 if (E->getExprLoc().isMacroID()) {
8177 const SourceManager &SM = getSourceManager();
8178 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
8179 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +00008180 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +00008181 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00008182 E = E->IgnoreImpCasts();
8183
8184 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
8185
Richard Trieuf7432752014-06-06 21:39:26 +00008186 if (isa<CXXThisExpr>(E)) {
8187 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
8188 : diag::warn_this_bool_conversion;
8189 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
8190 return;
8191 }
8192
Richard Trieu3bb8b562014-02-26 02:36:06 +00008193 bool IsAddressOf = false;
8194
8195 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
8196 if (UO->getOpcode() != UO_AddrOf)
8197 return;
8198 IsAddressOf = true;
8199 E = UO->getSubExpr();
8200 }
8201
Richard Trieuc1888e02014-06-28 23:25:37 +00008202 if (IsAddressOf) {
8203 unsigned DiagID = IsCompare
8204 ? diag::warn_address_of_reference_null_compare
8205 : diag::warn_address_of_reference_bool_conversion;
8206 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
8207 << IsEqual;
8208 if (CheckForReference(*this, E, PD)) {
8209 return;
8210 }
8211 }
8212
George Burgess IV850269a2015-12-08 22:02:00 +00008213 auto ComplainAboutNonnullParamOrCall = [&](bool IsParam) {
8214 std::string Str;
8215 llvm::raw_string_ostream S(Str);
8216 E->printPretty(S, nullptr, getPrintingPolicy());
8217 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
8218 : diag::warn_cast_nonnull_to_bool;
8219 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
8220 << E->getSourceRange() << Range << IsEqual;
8221 };
8222
8223 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
8224 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
8225 if (auto *Callee = Call->getDirectCallee()) {
8226 if (Callee->hasAttr<ReturnsNonNullAttr>()) {
8227 ComplainAboutNonnullParamOrCall(false);
8228 return;
8229 }
8230 }
8231 }
8232
Richard Trieu3bb8b562014-02-26 02:36:06 +00008233 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +00008234 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +00008235 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
8236 D = R->getDecl();
8237 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
8238 D = M->getMemberDecl();
8239 }
8240
8241 // Weak Decls can be null.
8242 if (!D || D->isWeak())
8243 return;
George Burgess IV850269a2015-12-08 22:02:00 +00008244
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008245 // Check for parameter decl with nonnull attribute
George Burgess IV850269a2015-12-08 22:02:00 +00008246 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
8247 if (getCurFunction() &&
8248 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
8249 if (PV->hasAttr<NonNullAttr>()) {
8250 ComplainAboutNonnullParamOrCall(true);
8251 return;
8252 }
8253
8254 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
8255 auto ParamIter = std::find(FD->param_begin(), FD->param_end(), PV);
8256 assert(ParamIter != FD->param_end());
8257 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
8258
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008259 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
8260 if (!NonNull->args_size()) {
George Burgess IV850269a2015-12-08 22:02:00 +00008261 ComplainAboutNonnullParamOrCall(true);
8262 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008263 }
George Burgess IV850269a2015-12-08 22:02:00 +00008264
8265 for (unsigned ArgNo : NonNull->args()) {
8266 if (ArgNo == ParamNo) {
8267 ComplainAboutNonnullParamOrCall(true);
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008268 return;
8269 }
George Burgess IV850269a2015-12-08 22:02:00 +00008270 }
8271 }
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008272 }
8273 }
George Burgess IV850269a2015-12-08 22:02:00 +00008274 }
8275
Richard Trieu3bb8b562014-02-26 02:36:06 +00008276 QualType T = D->getType();
8277 const bool IsArray = T->isArrayType();
8278 const bool IsFunction = T->isFunctionType();
8279
Richard Trieuc1888e02014-06-28 23:25:37 +00008280 // Address of function is used to silence the function warning.
8281 if (IsAddressOf && IsFunction) {
8282 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00008283 }
8284
8285 // Found nothing.
8286 if (!IsAddressOf && !IsFunction && !IsArray)
8287 return;
8288
8289 // Pretty print the expression for the diagnostic.
8290 std::string Str;
8291 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +00008292 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +00008293
8294 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
8295 : diag::warn_impcast_pointer_to_bool;
Craig Topperfa1340f2015-12-23 05:44:46 +00008296 enum {
8297 AddressOf,
8298 FunctionPointer,
8299 ArrayPointer
8300 } DiagType;
Richard Trieu3bb8b562014-02-26 02:36:06 +00008301 if (IsAddressOf)
8302 DiagType = AddressOf;
8303 else if (IsFunction)
8304 DiagType = FunctionPointer;
8305 else if (IsArray)
8306 DiagType = ArrayPointer;
8307 else
8308 llvm_unreachable("Could not determine diagnostic.");
8309 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
8310 << Range << IsEqual;
8311
8312 if (!IsFunction)
8313 return;
8314
8315 // Suggest '&' to silence the function warning.
8316 Diag(E->getExprLoc(), diag::note_function_warning_silence)
8317 << FixItHint::CreateInsertion(E->getLocStart(), "&");
8318
8319 // Check to see if '()' fixit should be emitted.
8320 QualType ReturnType;
8321 UnresolvedSet<4> NonTemplateOverloads;
8322 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
8323 if (ReturnType.isNull())
8324 return;
8325
8326 if (IsCompare) {
8327 // There are two cases here. If there is null constant, the only suggest
8328 // for a pointer return type. If the null is 0, then suggest if the return
8329 // type is a pointer or an integer type.
8330 if (!ReturnType->isPointerType()) {
8331 if (NullKind == Expr::NPCK_ZeroExpression ||
8332 NullKind == Expr::NPCK_ZeroLiteral) {
8333 if (!ReturnType->isIntegerType())
8334 return;
8335 } else {
8336 return;
8337 }
8338 }
8339 } else { // !IsCompare
8340 // For function to bool, only suggest if the function pointer has bool
8341 // return type.
8342 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
8343 return;
8344 }
8345 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +00008346 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +00008347}
8348
John McCallcc7e5bf2010-05-06 08:58:33 +00008349/// Diagnoses "dangerous" implicit conversions within the given
8350/// expression (which is a full expression). Implements -Wconversion
8351/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00008352///
8353/// \param CC the "context" location of the implicit conversion, i.e.
8354/// the most location of the syntactic entity requiring the implicit
8355/// conversion
8356void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008357 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00008358 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00008359 return;
8360
8361 // Don't diagnose for value- or type-dependent expressions.
8362 if (E->isTypeDependent() || E->isValueDependent())
8363 return;
8364
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008365 // Check for array bounds violations in cases where the check isn't triggered
8366 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
8367 // ArraySubscriptExpr is on the RHS of a variable initialization.
8368 CheckArrayAccess(E);
8369
John McCallacf0ee52010-10-08 02:01:28 +00008370 // This is not the right CC for (e.g.) a variable initialization.
8371 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008372}
8373
Richard Trieu65724892014-11-15 06:37:39 +00008374/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
8375/// Input argument E is a logical expression.
8376void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
8377 ::CheckBoolLikeConversion(*this, E, CC);
8378}
8379
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008380/// Diagnose when expression is an integer constant expression and its evaluation
8381/// results in integer overflow
8382void Sema::CheckForIntOverflow (Expr *E) {
Akira Hatanakadfe2156f2016-02-10 06:06:06 +00008383 // Use a work list to deal with nested struct initializers.
8384 SmallVector<Expr *, 2> Exprs(1, E);
8385
8386 do {
8387 Expr *E = Exprs.pop_back_val();
8388
8389 if (isa<BinaryOperator>(E->IgnoreParenCasts())) {
8390 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
8391 continue;
8392 }
8393
8394 if (auto InitList = dyn_cast<InitListExpr>(E))
8395 Exprs.append(InitList->inits().begin(), InitList->inits().end());
8396 } while (!Exprs.empty());
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008397}
8398
Richard Smithc406cb72013-01-17 01:17:56 +00008399namespace {
8400/// \brief Visitor for expressions which looks for unsequenced operations on the
8401/// same object.
8402class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00008403 typedef EvaluatedExprVisitor<SequenceChecker> Base;
8404
Richard Smithc406cb72013-01-17 01:17:56 +00008405 /// \brief A tree of sequenced regions within an expression. Two regions are
8406 /// unsequenced if one is an ancestor or a descendent of the other. When we
8407 /// finish processing an expression with sequencing, such as a comma
8408 /// expression, we fold its tree nodes into its parent, since they are
8409 /// unsequenced with respect to nodes we will visit later.
8410 class SequenceTree {
8411 struct Value {
8412 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
8413 unsigned Parent : 31;
8414 bool Merged : 1;
8415 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008416 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00008417
8418 public:
8419 /// \brief A region within an expression which may be sequenced with respect
8420 /// to some other region.
8421 class Seq {
8422 explicit Seq(unsigned N) : Index(N) {}
8423 unsigned Index;
8424 friend class SequenceTree;
8425 public:
8426 Seq() : Index(0) {}
8427 };
8428
8429 SequenceTree() { Values.push_back(Value(0)); }
8430 Seq root() const { return Seq(0); }
8431
8432 /// \brief Create a new sequence of operations, which is an unsequenced
8433 /// subset of \p Parent. This sequence of operations is sequenced with
8434 /// respect to other children of \p Parent.
8435 Seq allocate(Seq Parent) {
8436 Values.push_back(Value(Parent.Index));
8437 return Seq(Values.size() - 1);
8438 }
8439
8440 /// \brief Merge a sequence of operations into its parent.
8441 void merge(Seq S) {
8442 Values[S.Index].Merged = true;
8443 }
8444
8445 /// \brief Determine whether two operations are unsequenced. This operation
8446 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
8447 /// should have been merged into its parent as appropriate.
8448 bool isUnsequenced(Seq Cur, Seq Old) {
8449 unsigned C = representative(Cur.Index);
8450 unsigned Target = representative(Old.Index);
8451 while (C >= Target) {
8452 if (C == Target)
8453 return true;
8454 C = Values[C].Parent;
8455 }
8456 return false;
8457 }
8458
8459 private:
8460 /// \brief Pick a representative for a sequence.
8461 unsigned representative(unsigned K) {
8462 if (Values[K].Merged)
8463 // Perform path compression as we go.
8464 return Values[K].Parent = representative(Values[K].Parent);
8465 return K;
8466 }
8467 };
8468
8469 /// An object for which we can track unsequenced uses.
8470 typedef NamedDecl *Object;
8471
8472 /// Different flavors of object usage which we track. We only track the
8473 /// least-sequenced usage of each kind.
8474 enum UsageKind {
8475 /// A read of an object. Multiple unsequenced reads are OK.
8476 UK_Use,
8477 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00008478 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00008479 UK_ModAsValue,
8480 /// A modification of an object which is not sequenced before the value
8481 /// computation of the expression, such as n++.
8482 UK_ModAsSideEffect,
8483
8484 UK_Count = UK_ModAsSideEffect + 1
8485 };
8486
8487 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +00008488 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +00008489 Expr *Use;
8490 SequenceTree::Seq Seq;
8491 };
8492
8493 struct UsageInfo {
8494 UsageInfo() : Diagnosed(false) {}
8495 Usage Uses[UK_Count];
8496 /// Have we issued a diagnostic for this variable already?
8497 bool Diagnosed;
8498 };
8499 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
8500
8501 Sema &SemaRef;
8502 /// Sequenced regions within the expression.
8503 SequenceTree Tree;
8504 /// Declaration modifications and references which we have seen.
8505 UsageInfoMap UsageMap;
8506 /// The region we are currently within.
8507 SequenceTree::Seq Region;
8508 /// Filled in with declarations which were modified as a side-effect
8509 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008510 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00008511 /// Expressions to check later. We defer checking these to reduce
8512 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008513 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00008514
8515 /// RAII object wrapping the visitation of a sequenced subexpression of an
8516 /// expression. At the end of this process, the side-effects of the evaluation
8517 /// become sequenced with respect to the value computation of the result, so
8518 /// we downgrade any UK_ModAsSideEffect within the evaluation to
8519 /// UK_ModAsValue.
8520 struct SequencedSubexpression {
8521 SequencedSubexpression(SequenceChecker &Self)
8522 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
8523 Self.ModAsSideEffect = &ModAsSideEffect;
8524 }
8525 ~SequencedSubexpression() {
Richard Smithe8efd992014-12-03 01:05:50 +00008526 for (auto MI = ModAsSideEffect.rbegin(), ME = ModAsSideEffect.rend();
8527 MI != ME; ++MI) {
8528 UsageInfo &U = Self.UsageMap[MI->first];
8529 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
8530 Self.addUsage(U, MI->first, SideEffectUsage.Use, UK_ModAsValue);
8531 SideEffectUsage = MI->second;
Richard Smithc406cb72013-01-17 01:17:56 +00008532 }
8533 Self.ModAsSideEffect = OldModAsSideEffect;
8534 }
8535
8536 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008537 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
8538 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00008539 };
8540
Richard Smith40238f02013-06-20 22:21:56 +00008541 /// RAII object wrapping the visitation of a subexpression which we might
8542 /// choose to evaluate as a constant. If any subexpression is evaluated and
8543 /// found to be non-constant, this allows us to suppress the evaluation of
8544 /// the outer expression.
8545 class EvaluationTracker {
8546 public:
8547 EvaluationTracker(SequenceChecker &Self)
8548 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
8549 Self.EvalTracker = this;
8550 }
8551 ~EvaluationTracker() {
8552 Self.EvalTracker = Prev;
8553 if (Prev)
8554 Prev->EvalOK &= EvalOK;
8555 }
8556
8557 bool evaluate(const Expr *E, bool &Result) {
8558 if (!EvalOK || E->isValueDependent())
8559 return false;
8560 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
8561 return EvalOK;
8562 }
8563
8564 private:
8565 SequenceChecker &Self;
8566 EvaluationTracker *Prev;
8567 bool EvalOK;
8568 } *EvalTracker;
8569
Richard Smithc406cb72013-01-17 01:17:56 +00008570 /// \brief Find the object which is produced by the specified expression,
8571 /// if any.
8572 Object getObject(Expr *E, bool Mod) const {
8573 E = E->IgnoreParenCasts();
8574 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
8575 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
8576 return getObject(UO->getSubExpr(), Mod);
8577 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
8578 if (BO->getOpcode() == BO_Comma)
8579 return getObject(BO->getRHS(), Mod);
8580 if (Mod && BO->isAssignmentOp())
8581 return getObject(BO->getLHS(), Mod);
8582 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
8583 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
8584 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
8585 return ME->getMemberDecl();
8586 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
8587 // FIXME: If this is a reference, map through to its value.
8588 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00008589 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +00008590 }
8591
8592 /// \brief Note that an object was modified or used by an expression.
8593 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
8594 Usage &U = UI.Uses[UK];
8595 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
8596 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
8597 ModAsSideEffect->push_back(std::make_pair(O, U));
8598 U.Use = Ref;
8599 U.Seq = Region;
8600 }
8601 }
8602 /// \brief Check whether a modification or use conflicts with a prior usage.
8603 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
8604 bool IsModMod) {
8605 if (UI.Diagnosed)
8606 return;
8607
8608 const Usage &U = UI.Uses[OtherKind];
8609 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
8610 return;
8611
8612 Expr *Mod = U.Use;
8613 Expr *ModOrUse = Ref;
8614 if (OtherKind == UK_Use)
8615 std::swap(Mod, ModOrUse);
8616
8617 SemaRef.Diag(Mod->getExprLoc(),
8618 IsModMod ? diag::warn_unsequenced_mod_mod
8619 : diag::warn_unsequenced_mod_use)
8620 << O << SourceRange(ModOrUse->getExprLoc());
8621 UI.Diagnosed = true;
8622 }
8623
8624 void notePreUse(Object O, Expr *Use) {
8625 UsageInfo &U = UsageMap[O];
8626 // Uses conflict with other modifications.
8627 checkUsage(O, U, Use, UK_ModAsValue, false);
8628 }
8629 void notePostUse(Object O, Expr *Use) {
8630 UsageInfo &U = UsageMap[O];
8631 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
8632 addUsage(U, O, Use, UK_Use);
8633 }
8634
8635 void notePreMod(Object O, Expr *Mod) {
8636 UsageInfo &U = UsageMap[O];
8637 // Modifications conflict with other modifications and with uses.
8638 checkUsage(O, U, Mod, UK_ModAsValue, true);
8639 checkUsage(O, U, Mod, UK_Use, false);
8640 }
8641 void notePostMod(Object O, Expr *Use, UsageKind UK) {
8642 UsageInfo &U = UsageMap[O];
8643 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
8644 addUsage(U, O, Use, UK);
8645 }
8646
8647public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008648 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +00008649 : Base(S.Context), SemaRef(S), Region(Tree.root()),
8650 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +00008651 Visit(E);
8652 }
8653
8654 void VisitStmt(Stmt *S) {
8655 // Skip all statements which aren't expressions for now.
8656 }
8657
8658 void VisitExpr(Expr *E) {
8659 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00008660 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00008661 }
8662
8663 void VisitCastExpr(CastExpr *E) {
8664 Object O = Object();
8665 if (E->getCastKind() == CK_LValueToRValue)
8666 O = getObject(E->getSubExpr(), false);
8667
8668 if (O)
8669 notePreUse(O, E);
8670 VisitExpr(E);
8671 if (O)
8672 notePostUse(O, E);
8673 }
8674
8675 void VisitBinComma(BinaryOperator *BO) {
8676 // C++11 [expr.comma]p1:
8677 // Every value computation and side effect associated with the left
8678 // expression is sequenced before every value computation and side
8679 // effect associated with the right expression.
8680 SequenceTree::Seq LHS = Tree.allocate(Region);
8681 SequenceTree::Seq RHS = Tree.allocate(Region);
8682 SequenceTree::Seq OldRegion = Region;
8683
8684 {
8685 SequencedSubexpression SeqLHS(*this);
8686 Region = LHS;
8687 Visit(BO->getLHS());
8688 }
8689
8690 Region = RHS;
8691 Visit(BO->getRHS());
8692
8693 Region = OldRegion;
8694
8695 // Forget that LHS and RHS are sequenced. They are both unsequenced
8696 // with respect to other stuff.
8697 Tree.merge(LHS);
8698 Tree.merge(RHS);
8699 }
8700
8701 void VisitBinAssign(BinaryOperator *BO) {
8702 // The modification is sequenced after the value computation of the LHS
8703 // and RHS, so check it before inspecting the operands and update the
8704 // map afterwards.
8705 Object O = getObject(BO->getLHS(), true);
8706 if (!O)
8707 return VisitExpr(BO);
8708
8709 notePreMod(O, BO);
8710
8711 // C++11 [expr.ass]p7:
8712 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
8713 // only once.
8714 //
8715 // Therefore, for a compound assignment operator, O is considered used
8716 // everywhere except within the evaluation of E1 itself.
8717 if (isa<CompoundAssignOperator>(BO))
8718 notePreUse(O, BO);
8719
8720 Visit(BO->getLHS());
8721
8722 if (isa<CompoundAssignOperator>(BO))
8723 notePostUse(O, BO);
8724
8725 Visit(BO->getRHS());
8726
Richard Smith83e37bee2013-06-26 23:16:51 +00008727 // C++11 [expr.ass]p1:
8728 // the assignment is sequenced [...] before the value computation of the
8729 // assignment expression.
8730 // C11 6.5.16/3 has no such rule.
8731 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
8732 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00008733 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008734
Richard Smithc406cb72013-01-17 01:17:56 +00008735 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
8736 VisitBinAssign(CAO);
8737 }
8738
8739 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
8740 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
8741 void VisitUnaryPreIncDec(UnaryOperator *UO) {
8742 Object O = getObject(UO->getSubExpr(), true);
8743 if (!O)
8744 return VisitExpr(UO);
8745
8746 notePreMod(O, UO);
8747 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +00008748 // C++11 [expr.pre.incr]p1:
8749 // the expression ++x is equivalent to x+=1
8750 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
8751 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00008752 }
8753
8754 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
8755 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
8756 void VisitUnaryPostIncDec(UnaryOperator *UO) {
8757 Object O = getObject(UO->getSubExpr(), true);
8758 if (!O)
8759 return VisitExpr(UO);
8760
8761 notePreMod(O, UO);
8762 Visit(UO->getSubExpr());
8763 notePostMod(O, UO, UK_ModAsSideEffect);
8764 }
8765
8766 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
8767 void VisitBinLOr(BinaryOperator *BO) {
8768 // The side-effects of the LHS of an '&&' are sequenced before the
8769 // value computation of the RHS, and hence before the value computation
8770 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
8771 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +00008772 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00008773 {
8774 SequencedSubexpression Sequenced(*this);
8775 Visit(BO->getLHS());
8776 }
8777
8778 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00008779 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00008780 if (!Result)
8781 Visit(BO->getRHS());
8782 } else {
8783 // Check for unsequenced operations in the RHS, treating it as an
8784 // entirely separate evaluation.
8785 //
8786 // FIXME: If there are operations in the RHS which are unsequenced
8787 // with respect to operations outside the RHS, and those operations
8788 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +00008789 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00008790 }
Richard Smithc406cb72013-01-17 01:17:56 +00008791 }
8792 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +00008793 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00008794 {
8795 SequencedSubexpression Sequenced(*this);
8796 Visit(BO->getLHS());
8797 }
8798
8799 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00008800 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00008801 if (Result)
8802 Visit(BO->getRHS());
8803 } else {
Richard Smithd33f5202013-01-17 23:18:09 +00008804 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00008805 }
Richard Smithc406cb72013-01-17 01:17:56 +00008806 }
8807
8808 // Only visit the condition, unless we can be sure which subexpression will
8809 // be chosen.
8810 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +00008811 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +00008812 {
8813 SequencedSubexpression Sequenced(*this);
8814 Visit(CO->getCond());
8815 }
Richard Smithc406cb72013-01-17 01:17:56 +00008816
8817 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00008818 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +00008819 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00008820 else {
Richard Smithd33f5202013-01-17 23:18:09 +00008821 WorkList.push_back(CO->getTrueExpr());
8822 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00008823 }
Richard Smithc406cb72013-01-17 01:17:56 +00008824 }
8825
Richard Smithe3dbfe02013-06-30 10:40:20 +00008826 void VisitCallExpr(CallExpr *CE) {
8827 // C++11 [intro.execution]p15:
8828 // When calling a function [...], every value computation and side effect
8829 // associated with any argument expression, or with the postfix expression
8830 // designating the called function, is sequenced before execution of every
8831 // expression or statement in the body of the function [and thus before
8832 // the value computation of its result].
8833 SequencedSubexpression Sequenced(*this);
8834 Base::VisitCallExpr(CE);
8835
8836 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
8837 }
8838
Richard Smithc406cb72013-01-17 01:17:56 +00008839 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +00008840 // This is a call, so all subexpressions are sequenced before the result.
8841 SequencedSubexpression Sequenced(*this);
8842
Richard Smithc406cb72013-01-17 01:17:56 +00008843 if (!CCE->isListInitialization())
8844 return VisitExpr(CCE);
8845
8846 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008847 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00008848 SequenceTree::Seq Parent = Region;
8849 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
8850 E = CCE->arg_end();
8851 I != E; ++I) {
8852 Region = Tree.allocate(Parent);
8853 Elts.push_back(Region);
8854 Visit(*I);
8855 }
8856
8857 // Forget that the initializers are sequenced.
8858 Region = Parent;
8859 for (unsigned I = 0; I < Elts.size(); ++I)
8860 Tree.merge(Elts[I]);
8861 }
8862
8863 void VisitInitListExpr(InitListExpr *ILE) {
8864 if (!SemaRef.getLangOpts().CPlusPlus11)
8865 return VisitExpr(ILE);
8866
8867 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008868 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00008869 SequenceTree::Seq Parent = Region;
8870 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
8871 Expr *E = ILE->getInit(I);
8872 if (!E) continue;
8873 Region = Tree.allocate(Parent);
8874 Elts.push_back(Region);
8875 Visit(E);
8876 }
8877
8878 // Forget that the initializers are sequenced.
8879 Region = Parent;
8880 for (unsigned I = 0; I < Elts.size(); ++I)
8881 Tree.merge(Elts[I]);
8882 }
8883};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008884} // end anonymous namespace
Richard Smithc406cb72013-01-17 01:17:56 +00008885
8886void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008887 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +00008888 WorkList.push_back(E);
8889 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00008890 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +00008891 SequenceChecker(*this, Item, WorkList);
8892 }
Richard Smithc406cb72013-01-17 01:17:56 +00008893}
8894
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008895void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
8896 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +00008897 CheckImplicitConversions(E, CheckLoc);
8898 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008899 if (!IsConstexpr && !E->isValueDependent())
8900 CheckForIntOverflow(E);
Richard Smithc406cb72013-01-17 01:17:56 +00008901}
8902
John McCall1f425642010-11-11 03:21:53 +00008903void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
8904 FieldDecl *BitField,
8905 Expr *Init) {
8906 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
8907}
8908
David Majnemer61a5bbf2015-04-07 22:08:51 +00008909static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
8910 SourceLocation Loc) {
8911 if (!PType->isVariablyModifiedType())
8912 return;
8913 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
8914 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
8915 return;
8916 }
David Majnemerdf8f73f2015-04-09 19:53:25 +00008917 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
8918 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
8919 return;
8920 }
David Majnemer61a5bbf2015-04-07 22:08:51 +00008921 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
8922 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
8923 return;
8924 }
8925
8926 const ArrayType *AT = S.Context.getAsArrayType(PType);
8927 if (!AT)
8928 return;
8929
8930 if (AT->getSizeModifier() != ArrayType::Star) {
8931 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
8932 return;
8933 }
8934
8935 S.Diag(Loc, diag::err_array_star_in_function_definition);
8936}
8937
Mike Stump0c2ec772010-01-21 03:59:47 +00008938/// CheckParmsForFunctionDef - Check that the parameters of the given
8939/// function are appropriate for the definition of a function. This
8940/// takes care of any checks that cannot be performed on the
8941/// declaration itself, e.g., that the types of each of the function
8942/// parameters are complete.
Reid Kleckner5a115802013-06-24 14:38:26 +00008943bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
8944 ParmVarDecl *const *PEnd,
Douglas Gregorb524d902010-11-01 18:37:59 +00008945 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +00008946 bool HasInvalidParm = false;
Douglas Gregorb524d902010-11-01 18:37:59 +00008947 for (; P != PEnd; ++P) {
8948 ParmVarDecl *Param = *P;
8949
Mike Stump0c2ec772010-01-21 03:59:47 +00008950 // C99 6.7.5.3p4: the parameters in a parameter type list in a
8951 // function declarator that is part of a function definition of
8952 // that function shall not have incomplete type.
8953 //
8954 // This is also C++ [dcl.fct]p6.
8955 if (!Param->isInvalidDecl() &&
8956 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00008957 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +00008958 Param->setInvalidDecl();
8959 HasInvalidParm = true;
8960 }
8961
8962 // C99 6.9.1p5: If the declarator includes a parameter type list, the
8963 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +00008964 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +00008965 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +00008966 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00008967 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +00008968 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +00008969
8970 // C99 6.7.5.3p12:
8971 // If the function declarator is not part of a definition of that
8972 // function, parameters may have incomplete type and may use the [*]
8973 // notation in their sequences of declarator specifiers to specify
8974 // variable length array types.
8975 QualType PType = Param->getOriginalType();
David Majnemer61a5bbf2015-04-07 22:08:51 +00008976 // FIXME: This diagnostic should point the '[*]' if source-location
8977 // information is added for it.
8978 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00008979
8980 // MSVC destroys objects passed by value in the callee. Therefore a
8981 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00008982 // object's destructor. However, we don't perform any direct access check
8983 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +00008984 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
8985 .getCXXABI()
8986 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +00008987 if (!Param->isInvalidDecl()) {
8988 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
8989 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
8990 if (!ClassDecl->isInvalidDecl() &&
8991 !ClassDecl->hasIrrelevantDestructor() &&
8992 !ClassDecl->isDependentContext()) {
8993 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
8994 MarkFunctionReferenced(Param->getLocation(), Destructor);
8995 DiagnoseUseOfDecl(Destructor, Param->getLocation());
8996 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00008997 }
8998 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00008999 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009000
9001 // Parameters with the pass_object_size attribute only need to be marked
9002 // constant at function definitions. Because we lack information about
9003 // whether we're on a declaration or definition when we're instantiating the
9004 // attribute, we need to check for constness here.
9005 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
9006 if (!Param->getType().isConstQualified())
9007 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
9008 << Attr->getSpelling() << 1;
Mike Stump0c2ec772010-01-21 03:59:47 +00009009 }
9010
9011 return HasInvalidParm;
9012}
John McCall2b5c1b22010-08-12 21:44:57 +00009013
9014/// CheckCastAlign - Implements -Wcast-align, which warns when a
9015/// pointer cast increases the alignment requirements.
9016void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
9017 // This is actually a lot of work to potentially be doing on every
9018 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009019 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +00009020 return;
9021
9022 // Ignore dependent types.
9023 if (T->isDependentType() || Op->getType()->isDependentType())
9024 return;
9025
9026 // Require that the destination be a pointer type.
9027 const PointerType *DestPtr = T->getAs<PointerType>();
9028 if (!DestPtr) return;
9029
9030 // If the destination has alignment 1, we're done.
9031 QualType DestPointee = DestPtr->getPointeeType();
9032 if (DestPointee->isIncompleteType()) return;
9033 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
9034 if (DestAlign.isOne()) return;
9035
9036 // Require that the source be a pointer type.
9037 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
9038 if (!SrcPtr) return;
9039 QualType SrcPointee = SrcPtr->getPointeeType();
9040
9041 // Whitelist casts from cv void*. We already implicitly
9042 // whitelisted casts to cv void*, since they have alignment 1.
9043 // Also whitelist casts involving incomplete types, which implicitly
9044 // includes 'void'.
9045 if (SrcPointee->isIncompleteType()) return;
9046
9047 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
9048 if (SrcAlign >= DestAlign) return;
9049
9050 Diag(TRange.getBegin(), diag::warn_cast_align)
9051 << Op->getType() << T
9052 << static_cast<unsigned>(SrcAlign.getQuantity())
9053 << static_cast<unsigned>(DestAlign.getQuantity())
9054 << TRange << Op->getSourceRange();
9055}
9056
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009057static const Type* getElementType(const Expr *BaseExpr) {
9058 const Type* EltType = BaseExpr->getType().getTypePtr();
9059 if (EltType->isAnyPointerType())
9060 return EltType->getPointeeType().getTypePtr();
9061 else if (EltType->isArrayType())
9062 return EltType->getBaseElementTypeUnsafe();
9063 return EltType;
9064}
9065
Chandler Carruth28389f02011-08-05 09:10:50 +00009066/// \brief Check whether this array fits the idiom of a size-one tail padded
9067/// array member of a struct.
9068///
9069/// We avoid emitting out-of-bounds access warnings for such arrays as they are
9070/// commonly used to emulate flexible arrays in C89 code.
9071static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
9072 const NamedDecl *ND) {
9073 if (Size != 1 || !ND) return false;
9074
9075 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
9076 if (!FD) return false;
9077
9078 // Don't consider sizes resulting from macro expansions or template argument
9079 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +00009080
9081 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00009082 while (TInfo) {
9083 TypeLoc TL = TInfo->getTypeLoc();
9084 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +00009085 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
9086 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00009087 TInfo = TDL->getTypeSourceInfo();
9088 continue;
9089 }
David Blaikie6adc78e2013-02-18 22:06:02 +00009090 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
9091 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +00009092 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
9093 return false;
9094 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +00009095 break;
Sean Callanan06a48a62012-05-04 18:22:53 +00009096 }
Chandler Carruth28389f02011-08-05 09:10:50 +00009097
9098 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +00009099 if (!RD) return false;
9100 if (RD->isUnion()) return false;
9101 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
9102 if (!CRD->isStandardLayout()) return false;
9103 }
Chandler Carruth28389f02011-08-05 09:10:50 +00009104
Benjamin Kramer8c543672011-08-06 03:04:42 +00009105 // See if this is the last field decl in the record.
9106 const Decl *D = FD;
9107 while ((D = D->getNextDeclInContext()))
9108 if (isa<FieldDecl>(D))
9109 return false;
9110 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +00009111}
9112
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009113void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009114 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +00009115 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +00009116 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009117 if (IndexExpr->isValueDependent())
9118 return;
9119
Matt Beaumont-Gay9d570c42011-12-12 22:35:02 +00009120 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009121 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009122 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009123 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009124 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +00009125 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +00009126
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009127 llvm::APSInt index;
Richard Smith0c6124b2015-12-03 01:36:22 +00009128 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
Ted Kremenek64699be2011-02-16 01:57:07 +00009129 return;
Richard Smith13f67182011-12-16 19:31:14 +00009130 if (IndexNegated)
9131 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +00009132
Craig Topperc3ec1492014-05-26 06:22:03 +00009133 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +00009134 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
9135 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +00009136 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +00009137 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +00009138
Ted Kremeneke4b316c2011-02-23 23:06:04 +00009139 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00009140 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +00009141 if (!size.isStrictlyPositive())
9142 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009143
9144 const Type* BaseType = getElementType(BaseExpr);
Nico Weber7c299802011-09-17 22:59:41 +00009145 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009146 // Make sure we're comparing apples to apples when comparing index to size
9147 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
9148 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +00009149 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +00009150 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009151 if (ptrarith_typesize != array_typesize) {
9152 // There's a cast to a different size type involved
9153 uint64_t ratio = array_typesize / ptrarith_typesize;
9154 // TODO: Be smarter about handling cases where array_typesize is not a
9155 // multiple of ptrarith_typesize
9156 if (ptrarith_typesize * ratio == array_typesize)
9157 size *= llvm::APInt(size.getBitWidth(), ratio);
9158 }
9159 }
9160
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009161 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00009162 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00009163 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00009164 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00009165
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009166 // For array subscripting the index must be less than size, but for pointer
9167 // arithmetic also allow the index (offset) to be equal to size since
9168 // computing the next address after the end of the array is legal and
9169 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +00009170 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +00009171 return;
9172
9173 // Also don't warn for arrays of size 1 which are members of some
9174 // structure. These are often used to approximate flexible arrays in C89
9175 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009176 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +00009177 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009178
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009179 // Suppress the warning if the subscript expression (as identified by the
9180 // ']' location) and the index expression are both from macro expansions
9181 // within a system header.
9182 if (ASE) {
9183 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
9184 ASE->getRBracketLoc());
9185 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
9186 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
9187 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +00009188 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009189 return;
9190 }
9191 }
9192
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009193 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009194 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009195 DiagID = diag::warn_array_index_exceeds_bounds;
9196
9197 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
9198 PDiag(DiagID) << index.toString(10, true)
9199 << size.toString(10, true)
9200 << (unsigned)size.getLimitedValue(~0U)
9201 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009202 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009203 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009204 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009205 DiagID = diag::warn_ptr_arith_precedes_bounds;
9206 if (index.isNegative()) index = -index;
9207 }
9208
9209 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
9210 PDiag(DiagID) << index.toString(10, true)
9211 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +00009212 }
Chandler Carruth1af88f12011-02-17 21:10:52 +00009213
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +00009214 if (!ND) {
9215 // Try harder to find a NamedDecl to point at in the note.
9216 while (const ArraySubscriptExpr *ASE =
9217 dyn_cast<ArraySubscriptExpr>(BaseExpr))
9218 BaseExpr = ASE->getBase()->IgnoreParenCasts();
9219 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
9220 ND = dyn_cast<NamedDecl>(DRE->getDecl());
9221 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
9222 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
9223 }
9224
Chandler Carruth1af88f12011-02-17 21:10:52 +00009225 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009226 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
9227 PDiag(diag::note_array_index_out_of_bounds)
9228 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +00009229}
9230
Ted Kremenekdf26df72011-03-01 18:41:00 +00009231void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009232 int AllowOnePastEnd = 0;
9233 while (expr) {
9234 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +00009235 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009236 case Stmt::ArraySubscriptExprClass: {
9237 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009238 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009239 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +00009240 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009241 }
Alexey Bataev1a3320e2015-08-25 14:24:04 +00009242 case Stmt::OMPArraySectionExprClass: {
9243 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
9244 if (ASE->getLowerBound())
9245 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
9246 /*ASE=*/nullptr, AllowOnePastEnd > 0);
9247 return;
9248 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009249 case Stmt::UnaryOperatorClass: {
9250 // Only unwrap the * and & unary operators
9251 const UnaryOperator *UO = cast<UnaryOperator>(expr);
9252 expr = UO->getSubExpr();
9253 switch (UO->getOpcode()) {
9254 case UO_AddrOf:
9255 AllowOnePastEnd++;
9256 break;
9257 case UO_Deref:
9258 AllowOnePastEnd--;
9259 break;
9260 default:
9261 return;
9262 }
9263 break;
9264 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00009265 case Stmt::ConditionalOperatorClass: {
9266 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
9267 if (const Expr *lhs = cond->getLHS())
9268 CheckArrayAccess(lhs);
9269 if (const Expr *rhs = cond->getRHS())
9270 CheckArrayAccess(rhs);
9271 return;
9272 }
9273 default:
9274 return;
9275 }
Peter Collingbourne91147592011-04-15 00:35:48 +00009276 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00009277}
John McCall31168b02011-06-15 23:02:42 +00009278
9279//===--- CHECK: Objective-C retain cycles ----------------------------------//
9280
9281namespace {
9282 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +00009283 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +00009284 VarDecl *Variable;
9285 SourceRange Range;
9286 SourceLocation Loc;
9287 bool Indirect;
9288
9289 void setLocsFrom(Expr *e) {
9290 Loc = e->getExprLoc();
9291 Range = e->getSourceRange();
9292 }
9293 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009294} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +00009295
9296/// Consider whether capturing the given variable can possibly lead to
9297/// a retain cycle.
9298static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00009299 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +00009300 // lifetime. In MRR, it's captured strongly if the variable is
9301 // __block and has an appropriate type.
9302 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
9303 return false;
9304
9305 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00009306 if (ref)
9307 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +00009308 return true;
9309}
9310
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009311static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +00009312 while (true) {
9313 e = e->IgnoreParens();
9314 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
9315 switch (cast->getCastKind()) {
9316 case CK_BitCast:
9317 case CK_LValueBitCast:
9318 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00009319 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +00009320 e = cast->getSubExpr();
9321 continue;
9322
John McCall31168b02011-06-15 23:02:42 +00009323 default:
9324 return false;
9325 }
9326 }
9327
9328 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
9329 ObjCIvarDecl *ivar = ref->getDecl();
9330 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
9331 return false;
9332
9333 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009334 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +00009335 return false;
9336
9337 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
9338 owner.Indirect = true;
9339 return true;
9340 }
9341
9342 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
9343 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
9344 if (!var) return false;
9345 return considerVariable(var, ref, owner);
9346 }
9347
John McCall31168b02011-06-15 23:02:42 +00009348 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
9349 if (member->isArrow()) return false;
9350
9351 // Don't count this as an indirect ownership.
9352 e = member->getBase();
9353 continue;
9354 }
9355
John McCallfe96e0b2011-11-06 09:01:30 +00009356 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
9357 // Only pay attention to pseudo-objects on property references.
9358 ObjCPropertyRefExpr *pre
9359 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
9360 ->IgnoreParens());
9361 if (!pre) return false;
9362 if (pre->isImplicitProperty()) return false;
9363 ObjCPropertyDecl *property = pre->getExplicitProperty();
9364 if (!property->isRetaining() &&
9365 !(property->getPropertyIvarDecl() &&
9366 property->getPropertyIvarDecl()->getType()
9367 .getObjCLifetime() == Qualifiers::OCL_Strong))
9368 return false;
9369
9370 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009371 if (pre->isSuperReceiver()) {
9372 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
9373 if (!owner.Variable)
9374 return false;
9375 owner.Loc = pre->getLocation();
9376 owner.Range = pre->getSourceRange();
9377 return true;
9378 }
John McCallfe96e0b2011-11-06 09:01:30 +00009379 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
9380 ->getSourceExpr());
9381 continue;
9382 }
9383
John McCall31168b02011-06-15 23:02:42 +00009384 // Array ivars?
9385
9386 return false;
9387 }
9388}
9389
9390namespace {
9391 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
9392 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
9393 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00009394 Context(Context), Variable(variable), Capturer(nullptr),
9395 VarWillBeReased(false) {}
9396 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +00009397 VarDecl *Variable;
9398 Expr *Capturer;
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00009399 bool VarWillBeReased;
John McCall31168b02011-06-15 23:02:42 +00009400
9401 void VisitDeclRefExpr(DeclRefExpr *ref) {
9402 if (ref->getDecl() == Variable && !Capturer)
9403 Capturer = ref;
9404 }
9405
John McCall31168b02011-06-15 23:02:42 +00009406 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
9407 if (Capturer) return;
9408 Visit(ref->getBase());
9409 if (Capturer && ref->isFreeIvar())
9410 Capturer = ref;
9411 }
9412
9413 void VisitBlockExpr(BlockExpr *block) {
9414 // Look inside nested blocks
9415 if (block->getBlockDecl()->capturesVariable(Variable))
9416 Visit(block->getBlockDecl()->getBody());
9417 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +00009418
9419 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
9420 if (Capturer) return;
9421 if (OVE->getSourceExpr())
9422 Visit(OVE->getSourceExpr());
9423 }
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00009424 void VisitBinaryOperator(BinaryOperator *BinOp) {
9425 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
9426 return;
9427 Expr *LHS = BinOp->getLHS();
9428 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
9429 if (DRE->getDecl() != Variable)
9430 return;
9431 if (Expr *RHS = BinOp->getRHS()) {
9432 RHS = RHS->IgnoreParenCasts();
9433 llvm::APSInt Value;
9434 VarWillBeReased =
9435 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
9436 }
9437 }
9438 }
John McCall31168b02011-06-15 23:02:42 +00009439 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009440} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +00009441
9442/// Check whether the given argument is a block which captures a
9443/// variable.
9444static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
9445 assert(owner.Variable && owner.Loc.isValid());
9446
9447 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +00009448
9449 // Look through [^{...} copy] and Block_copy(^{...}).
9450 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
9451 Selector Cmd = ME->getSelector();
9452 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
9453 e = ME->getInstanceReceiver();
9454 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +00009455 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +00009456 e = e->IgnoreParenCasts();
9457 }
9458 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
9459 if (CE->getNumArgs() == 1) {
9460 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +00009461 if (Fn) {
9462 const IdentifierInfo *FnI = Fn->getIdentifier();
9463 if (FnI && FnI->isStr("_Block_copy")) {
9464 e = CE->getArg(0)->IgnoreParenCasts();
9465 }
9466 }
Jordan Rose67e887c2012-09-17 17:54:30 +00009467 }
9468 }
9469
John McCall31168b02011-06-15 23:02:42 +00009470 BlockExpr *block = dyn_cast<BlockExpr>(e);
9471 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +00009472 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00009473
9474 FindCaptureVisitor visitor(S.Context, owner.Variable);
9475 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00009476 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +00009477}
9478
9479static void diagnoseRetainCycle(Sema &S, Expr *capturer,
9480 RetainCycleOwner &owner) {
9481 assert(capturer);
9482 assert(owner.Variable && owner.Loc.isValid());
9483
9484 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
9485 << owner.Variable << capturer->getSourceRange();
9486 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
9487 << owner.Indirect << owner.Range;
9488}
9489
9490/// Check for a keyword selector that starts with the word 'add' or
9491/// 'set'.
9492static bool isSetterLikeSelector(Selector sel) {
9493 if (sel.isUnarySelector()) return false;
9494
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009495 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +00009496 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +00009497 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +00009498 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +00009499 else if (str.startswith("add")) {
9500 // Specially whitelist 'addOperationWithBlock:'.
9501 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
9502 return false;
9503 str = str.substr(3);
9504 }
John McCall31168b02011-06-15 23:02:42 +00009505 else
9506 return false;
9507
9508 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +00009509 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +00009510}
9511
Benjamin Kramer3a743452015-03-09 15:03:32 +00009512static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
9513 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +00009514 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
9515 Message->getReceiverInterface(),
9516 NSAPI::ClassId_NSMutableArray);
9517 if (!IsMutableArray) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009518 return None;
9519 }
9520
9521 Selector Sel = Message->getSelector();
9522
9523 Optional<NSAPI::NSArrayMethodKind> MKOpt =
9524 S.NSAPIObj->getNSArrayMethodKind(Sel);
9525 if (!MKOpt) {
9526 return None;
9527 }
9528
9529 NSAPI::NSArrayMethodKind MK = *MKOpt;
9530
9531 switch (MK) {
9532 case NSAPI::NSMutableArr_addObject:
9533 case NSAPI::NSMutableArr_insertObjectAtIndex:
9534 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
9535 return 0;
9536 case NSAPI::NSMutableArr_replaceObjectAtIndex:
9537 return 1;
9538
9539 default:
9540 return None;
9541 }
9542
9543 return None;
9544}
9545
9546static
9547Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
9548 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +00009549 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
9550 Message->getReceiverInterface(),
9551 NSAPI::ClassId_NSMutableDictionary);
9552 if (!IsMutableDictionary) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009553 return None;
9554 }
9555
9556 Selector Sel = Message->getSelector();
9557
9558 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
9559 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
9560 if (!MKOpt) {
9561 return None;
9562 }
9563
9564 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
9565
9566 switch (MK) {
9567 case NSAPI::NSMutableDict_setObjectForKey:
9568 case NSAPI::NSMutableDict_setValueForKey:
9569 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
9570 return 0;
9571
9572 default:
9573 return None;
9574 }
9575
9576 return None;
9577}
9578
9579static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +00009580 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
9581 Message->getReceiverInterface(),
9582 NSAPI::ClassId_NSMutableSet);
Alex Denisove1d882c2015-03-04 17:55:52 +00009583
Alex Denisov5dfac812015-08-06 04:51:14 +00009584 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
9585 Message->getReceiverInterface(),
9586 NSAPI::ClassId_NSMutableOrderedSet);
9587 if (!IsMutableSet && !IsMutableOrderedSet) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009588 return None;
9589 }
9590
9591 Selector Sel = Message->getSelector();
9592
9593 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
9594 if (!MKOpt) {
9595 return None;
9596 }
9597
9598 NSAPI::NSSetMethodKind MK = *MKOpt;
9599
9600 switch (MK) {
9601 case NSAPI::NSMutableSet_addObject:
9602 case NSAPI::NSOrderedSet_setObjectAtIndex:
9603 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
9604 case NSAPI::NSOrderedSet_insertObjectAtIndex:
9605 return 0;
9606 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
9607 return 1;
9608 }
9609
9610 return None;
9611}
9612
9613void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
9614 if (!Message->isInstanceMessage()) {
9615 return;
9616 }
9617
9618 Optional<int> ArgOpt;
9619
9620 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
9621 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
9622 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
9623 return;
9624 }
9625
9626 int ArgIndex = *ArgOpt;
9627
Alex Denisove1d882c2015-03-04 17:55:52 +00009628 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
9629 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
9630 Arg = OE->getSourceExpr()->IgnoreImpCasts();
9631 }
9632
Alex Denisov5dfac812015-08-06 04:51:14 +00009633 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009634 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
Alex Denisov5dfac812015-08-06 04:51:14 +00009635 if (ArgRE->isObjCSelfExpr()) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009636 Diag(Message->getSourceRange().getBegin(),
9637 diag::warn_objc_circular_container)
Alex Denisov5dfac812015-08-06 04:51:14 +00009638 << ArgRE->getDecl()->getName() << StringRef("super");
Alex Denisove1d882c2015-03-04 17:55:52 +00009639 }
9640 }
Alex Denisov5dfac812015-08-06 04:51:14 +00009641 } else {
9642 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
9643
9644 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
9645 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
9646 }
9647
9648 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
9649 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
9650 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
9651 ValueDecl *Decl = ReceiverRE->getDecl();
9652 Diag(Message->getSourceRange().getBegin(),
9653 diag::warn_objc_circular_container)
9654 << Decl->getName() << Decl->getName();
9655 if (!ArgRE->isObjCSelfExpr()) {
9656 Diag(Decl->getLocation(),
9657 diag::note_objc_circular_container_declared_here)
9658 << Decl->getName();
9659 }
9660 }
9661 }
9662 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
9663 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
9664 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
9665 ObjCIvarDecl *Decl = IvarRE->getDecl();
9666 Diag(Message->getSourceRange().getBegin(),
9667 diag::warn_objc_circular_container)
9668 << Decl->getName() << Decl->getName();
9669 Diag(Decl->getLocation(),
9670 diag::note_objc_circular_container_declared_here)
9671 << Decl->getName();
9672 }
Alex Denisove1d882c2015-03-04 17:55:52 +00009673 }
9674 }
9675 }
Alex Denisove1d882c2015-03-04 17:55:52 +00009676}
9677
John McCall31168b02011-06-15 23:02:42 +00009678/// Check a message send to see if it's likely to cause a retain cycle.
9679void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
9680 // Only check instance methods whose selector looks like a setter.
9681 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
9682 return;
9683
9684 // Try to find a variable that the receiver is strongly owned by.
9685 RetainCycleOwner owner;
9686 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009687 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +00009688 return;
9689 } else {
9690 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
9691 owner.Variable = getCurMethodDecl()->getSelfDecl();
9692 owner.Loc = msg->getSuperLoc();
9693 owner.Range = msg->getSuperLoc();
9694 }
9695
9696 // Check whether the receiver is captured by any of the arguments.
9697 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
9698 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
9699 return diagnoseRetainCycle(*this, capturer, owner);
9700}
9701
9702/// Check a property assign to see if it's likely to cause a retain cycle.
9703void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
9704 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009705 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +00009706 return;
9707
9708 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
9709 diagnoseRetainCycle(*this, capturer, owner);
9710}
9711
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00009712void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
9713 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +00009714 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00009715 return;
9716
9717 // Because we don't have an expression for the variable, we have to set the
9718 // location explicitly here.
9719 Owner.Loc = Var->getLocation();
9720 Owner.Range = Var->getSourceRange();
9721
9722 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
9723 diagnoseRetainCycle(*this, Capturer, Owner);
9724}
9725
Ted Kremenek9304da92012-12-21 08:04:28 +00009726static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
9727 Expr *RHS, bool isProperty) {
9728 // Check if RHS is an Objective-C object literal, which also can get
9729 // immediately zapped in a weak reference. Note that we explicitly
9730 // allow ObjCStringLiterals, since those are designed to never really die.
9731 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00009732
Ted Kremenek64873352012-12-21 22:46:35 +00009733 // This enum needs to match with the 'select' in
9734 // warn_objc_arc_literal_assign (off-by-1).
9735 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
9736 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
9737 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00009738
9739 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +00009740 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +00009741 << (isProperty ? 0 : 1)
9742 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00009743
9744 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +00009745}
9746
Ted Kremenekc1f014a2012-12-21 19:45:30 +00009747static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
9748 Qualifiers::ObjCLifetime LT,
9749 Expr *RHS, bool isProperty) {
9750 // Strip off any implicit cast added to get to the one ARC-specific.
9751 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
9752 if (cast->getCastKind() == CK_ARCConsumeObject) {
9753 S.Diag(Loc, diag::warn_arc_retained_assign)
9754 << (LT == Qualifiers::OCL_ExplicitNone)
9755 << (isProperty ? 0 : 1)
9756 << RHS->getSourceRange();
9757 return true;
9758 }
9759 RHS = cast->getSubExpr();
9760 }
9761
9762 if (LT == Qualifiers::OCL_Weak &&
9763 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
9764 return true;
9765
9766 return false;
9767}
9768
Ted Kremenekb36234d2012-12-21 08:04:20 +00009769bool Sema::checkUnsafeAssigns(SourceLocation Loc,
9770 QualType LHS, Expr *RHS) {
9771 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
9772
9773 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
9774 return false;
9775
9776 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
9777 return true;
9778
9779 return false;
9780}
9781
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009782void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
9783 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009784 QualType LHSType;
9785 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +00009786 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009787 ObjCPropertyRefExpr *PRE
9788 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
9789 if (PRE && !PRE->isImplicitProperty()) {
9790 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
9791 if (PD)
9792 LHSType = PD->getType();
9793 }
9794
9795 if (LHSType.isNull())
9796 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +00009797
9798 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
9799
9800 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009801 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +00009802 getCurFunction()->markSafeWeakUse(LHS);
9803 }
9804
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009805 if (checkUnsafeAssigns(Loc, LHSType, RHS))
9806 return;
Jordan Rose657b5f42012-09-28 22:21:35 +00009807
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009808 // FIXME. Check for other life times.
9809 if (LT != Qualifiers::OCL_None)
9810 return;
9811
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009812 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009813 if (PRE->isImplicitProperty())
9814 return;
9815 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
9816 if (!PD)
9817 return;
9818
Bill Wendling44426052012-12-20 19:22:21 +00009819 unsigned Attributes = PD->getPropertyAttributes();
9820 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009821 // when 'assign' attribute was not explicitly specified
9822 // by user, ignore it and rely on property type itself
9823 // for lifetime info.
9824 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
9825 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
9826 LHSType->isObjCRetainableType())
9827 return;
9828
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009829 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +00009830 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009831 Diag(Loc, diag::warn_arc_retained_property_assign)
9832 << RHS->getSourceRange();
9833 return;
9834 }
9835 RHS = cast->getSubExpr();
9836 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009837 }
Bill Wendling44426052012-12-20 19:22:21 +00009838 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +00009839 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
9840 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +00009841 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009842 }
9843}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009844
9845//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
9846
9847namespace {
9848bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
9849 SourceLocation StmtLoc,
9850 const NullStmt *Body) {
9851 // Do not warn if the body is a macro that expands to nothing, e.g:
9852 //
9853 // #define CALL(x)
9854 // if (condition)
9855 // CALL(0);
9856 //
9857 if (Body->hasLeadingEmptyMacro())
9858 return false;
9859
9860 // Get line numbers of statement and body.
9861 bool StmtLineInvalid;
Dmitri Gribenkoad80af82015-03-15 01:08:23 +00009862 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009863 &StmtLineInvalid);
9864 if (StmtLineInvalid)
9865 return false;
9866
9867 bool BodyLineInvalid;
9868 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
9869 &BodyLineInvalid);
9870 if (BodyLineInvalid)
9871 return false;
9872
9873 // Warn if null statement and body are on the same line.
9874 if (StmtLine != BodyLine)
9875 return false;
9876
9877 return true;
9878}
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009879} // end anonymous namespace
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009880
9881void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
9882 const Stmt *Body,
9883 unsigned DiagID) {
9884 // Since this is a syntactic check, don't emit diagnostic for template
9885 // instantiations, this just adds noise.
9886 if (CurrentInstantiationScope)
9887 return;
9888
9889 // The body should be a null statement.
9890 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
9891 if (!NBody)
9892 return;
9893
9894 // Do the usual checks.
9895 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
9896 return;
9897
9898 Diag(NBody->getSemiLoc(), DiagID);
9899 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
9900}
9901
9902void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
9903 const Stmt *PossibleBody) {
9904 assert(!CurrentInstantiationScope); // Ensured by caller
9905
9906 SourceLocation StmtLoc;
9907 const Stmt *Body;
9908 unsigned DiagID;
9909 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
9910 StmtLoc = FS->getRParenLoc();
9911 Body = FS->getBody();
9912 DiagID = diag::warn_empty_for_body;
9913 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
9914 StmtLoc = WS->getCond()->getSourceRange().getEnd();
9915 Body = WS->getBody();
9916 DiagID = diag::warn_empty_while_body;
9917 } else
9918 return; // Neither `for' nor `while'.
9919
9920 // The body should be a null statement.
9921 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
9922 if (!NBody)
9923 return;
9924
9925 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009926 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009927 return;
9928
9929 // Do the usual checks.
9930 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
9931 return;
9932
9933 // `for(...);' and `while(...);' are popular idioms, so in order to keep
9934 // noise level low, emit diagnostics only if for/while is followed by a
9935 // CompoundStmt, e.g.:
9936 // for (int i = 0; i < n; i++);
9937 // {
9938 // a(i);
9939 // }
9940 // or if for/while is followed by a statement with more indentation
9941 // than for/while itself:
9942 // for (int i = 0; i < n; i++);
9943 // a(i);
9944 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
9945 if (!ProbableTypo) {
9946 bool BodyColInvalid;
9947 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
9948 PossibleBody->getLocStart(),
9949 &BodyColInvalid);
9950 if (BodyColInvalid)
9951 return;
9952
9953 bool StmtColInvalid;
9954 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
9955 S->getLocStart(),
9956 &StmtColInvalid);
9957 if (StmtColInvalid)
9958 return;
9959
9960 if (BodyCol > StmtCol)
9961 ProbableTypo = true;
9962 }
9963
9964 if (ProbableTypo) {
9965 Diag(NBody->getSemiLoc(), DiagID);
9966 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
9967 }
9968}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009969
Richard Trieu36d0b2b2015-01-13 02:32:02 +00009970//===--- CHECK: Warn on self move with std::move. -------------------------===//
9971
9972/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
9973void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
9974 SourceLocation OpLoc) {
Richard Trieu36d0b2b2015-01-13 02:32:02 +00009975 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
9976 return;
9977
9978 if (!ActiveTemplateInstantiations.empty())
9979 return;
9980
9981 // Strip parens and casts away.
9982 LHSExpr = LHSExpr->IgnoreParenImpCasts();
9983 RHSExpr = RHSExpr->IgnoreParenImpCasts();
9984
9985 // Check for a call expression
9986 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
9987 if (!CE || CE->getNumArgs() != 1)
9988 return;
9989
9990 // Check for a call to std::move
9991 const FunctionDecl *FD = CE->getDirectCallee();
9992 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
9993 !FD->getIdentifier()->isStr("move"))
9994 return;
9995
9996 // Get argument from std::move
9997 RHSExpr = CE->getArg(0);
9998
9999 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
10000 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
10001
10002 // Two DeclRefExpr's, check that the decls are the same.
10003 if (LHSDeclRef && RHSDeclRef) {
10004 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
10005 return;
10006 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
10007 RHSDeclRef->getDecl()->getCanonicalDecl())
10008 return;
10009
10010 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
10011 << LHSExpr->getSourceRange()
10012 << RHSExpr->getSourceRange();
10013 return;
10014 }
10015
10016 // Member variables require a different approach to check for self moves.
10017 // MemberExpr's are the same if every nested MemberExpr refers to the same
10018 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
10019 // the base Expr's are CXXThisExpr's.
10020 const Expr *LHSBase = LHSExpr;
10021 const Expr *RHSBase = RHSExpr;
10022 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
10023 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
10024 if (!LHSME || !RHSME)
10025 return;
10026
10027 while (LHSME && RHSME) {
10028 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
10029 RHSME->getMemberDecl()->getCanonicalDecl())
10030 return;
10031
10032 LHSBase = LHSME->getBase();
10033 RHSBase = RHSME->getBase();
10034 LHSME = dyn_cast<MemberExpr>(LHSBase);
10035 RHSME = dyn_cast<MemberExpr>(RHSBase);
10036 }
10037
10038 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
10039 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
10040 if (LHSDeclRef && RHSDeclRef) {
10041 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
10042 return;
10043 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
10044 RHSDeclRef->getDecl()->getCanonicalDecl())
10045 return;
10046
10047 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
10048 << LHSExpr->getSourceRange()
10049 << RHSExpr->getSourceRange();
10050 return;
10051 }
10052
10053 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
10054 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
10055 << LHSExpr->getSourceRange()
10056 << RHSExpr->getSourceRange();
10057}
10058
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010059//===--- Layout compatibility ----------------------------------------------//
10060
10061namespace {
10062
10063bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
10064
10065/// \brief Check if two enumeration types are layout-compatible.
10066bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
10067 // C++11 [dcl.enum] p8:
10068 // Two enumeration types are layout-compatible if they have the same
10069 // underlying type.
10070 return ED1->isComplete() && ED2->isComplete() &&
10071 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
10072}
10073
10074/// \brief Check if two fields are layout-compatible.
10075bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
10076 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
10077 return false;
10078
10079 if (Field1->isBitField() != Field2->isBitField())
10080 return false;
10081
10082 if (Field1->isBitField()) {
10083 // Make sure that the bit-fields are the same length.
10084 unsigned Bits1 = Field1->getBitWidthValue(C);
10085 unsigned Bits2 = Field2->getBitWidthValue(C);
10086
10087 if (Bits1 != Bits2)
10088 return false;
10089 }
10090
10091 return true;
10092}
10093
10094/// \brief Check if two standard-layout structs are layout-compatible.
10095/// (C++11 [class.mem] p17)
10096bool isLayoutCompatibleStruct(ASTContext &C,
10097 RecordDecl *RD1,
10098 RecordDecl *RD2) {
10099 // If both records are C++ classes, check that base classes match.
10100 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
10101 // If one of records is a CXXRecordDecl we are in C++ mode,
10102 // thus the other one is a CXXRecordDecl, too.
10103 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
10104 // Check number of base classes.
10105 if (D1CXX->getNumBases() != D2CXX->getNumBases())
10106 return false;
10107
10108 // Check the base classes.
10109 for (CXXRecordDecl::base_class_const_iterator
10110 Base1 = D1CXX->bases_begin(),
10111 BaseEnd1 = D1CXX->bases_end(),
10112 Base2 = D2CXX->bases_begin();
10113 Base1 != BaseEnd1;
10114 ++Base1, ++Base2) {
10115 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
10116 return false;
10117 }
10118 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
10119 // If only RD2 is a C++ class, it should have zero base classes.
10120 if (D2CXX->getNumBases() > 0)
10121 return false;
10122 }
10123
10124 // Check the fields.
10125 RecordDecl::field_iterator Field2 = RD2->field_begin(),
10126 Field2End = RD2->field_end(),
10127 Field1 = RD1->field_begin(),
10128 Field1End = RD1->field_end();
10129 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
10130 if (!isLayoutCompatible(C, *Field1, *Field2))
10131 return false;
10132 }
10133 if (Field1 != Field1End || Field2 != Field2End)
10134 return false;
10135
10136 return true;
10137}
10138
10139/// \brief Check if two standard-layout unions are layout-compatible.
10140/// (C++11 [class.mem] p18)
10141bool isLayoutCompatibleUnion(ASTContext &C,
10142 RecordDecl *RD1,
10143 RecordDecl *RD2) {
10144 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010145 for (auto *Field2 : RD2->fields())
10146 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010147
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010148 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010149 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
10150 I = UnmatchedFields.begin(),
10151 E = UnmatchedFields.end();
10152
10153 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010154 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010155 bool Result = UnmatchedFields.erase(*I);
10156 (void) Result;
10157 assert(Result);
10158 break;
10159 }
10160 }
10161 if (I == E)
10162 return false;
10163 }
10164
10165 return UnmatchedFields.empty();
10166}
10167
10168bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
10169 if (RD1->isUnion() != RD2->isUnion())
10170 return false;
10171
10172 if (RD1->isUnion())
10173 return isLayoutCompatibleUnion(C, RD1, RD2);
10174 else
10175 return isLayoutCompatibleStruct(C, RD1, RD2);
10176}
10177
10178/// \brief Check if two types are layout-compatible in C++11 sense.
10179bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
10180 if (T1.isNull() || T2.isNull())
10181 return false;
10182
10183 // C++11 [basic.types] p11:
10184 // If two types T1 and T2 are the same type, then T1 and T2 are
10185 // layout-compatible types.
10186 if (C.hasSameType(T1, T2))
10187 return true;
10188
10189 T1 = T1.getCanonicalType().getUnqualifiedType();
10190 T2 = T2.getCanonicalType().getUnqualifiedType();
10191
10192 const Type::TypeClass TC1 = T1->getTypeClass();
10193 const Type::TypeClass TC2 = T2->getTypeClass();
10194
10195 if (TC1 != TC2)
10196 return false;
10197
10198 if (TC1 == Type::Enum) {
10199 return isLayoutCompatible(C,
10200 cast<EnumType>(T1)->getDecl(),
10201 cast<EnumType>(T2)->getDecl());
10202 } else if (TC1 == Type::Record) {
10203 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
10204 return false;
10205
10206 return isLayoutCompatible(C,
10207 cast<RecordType>(T1)->getDecl(),
10208 cast<RecordType>(T2)->getDecl());
10209 }
10210
10211 return false;
10212}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010213} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010214
10215//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
10216
10217namespace {
10218/// \brief Given a type tag expression find the type tag itself.
10219///
10220/// \param TypeExpr Type tag expression, as it appears in user's code.
10221///
10222/// \param VD Declaration of an identifier that appears in a type tag.
10223///
10224/// \param MagicValue Type tag magic value.
10225bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
10226 const ValueDecl **VD, uint64_t *MagicValue) {
10227 while(true) {
10228 if (!TypeExpr)
10229 return false;
10230
10231 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
10232
10233 switch (TypeExpr->getStmtClass()) {
10234 case Stmt::UnaryOperatorClass: {
10235 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
10236 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
10237 TypeExpr = UO->getSubExpr();
10238 continue;
10239 }
10240 return false;
10241 }
10242
10243 case Stmt::DeclRefExprClass: {
10244 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
10245 *VD = DRE->getDecl();
10246 return true;
10247 }
10248
10249 case Stmt::IntegerLiteralClass: {
10250 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
10251 llvm::APInt MagicValueAPInt = IL->getValue();
10252 if (MagicValueAPInt.getActiveBits() <= 64) {
10253 *MagicValue = MagicValueAPInt.getZExtValue();
10254 return true;
10255 } else
10256 return false;
10257 }
10258
10259 case Stmt::BinaryConditionalOperatorClass:
10260 case Stmt::ConditionalOperatorClass: {
10261 const AbstractConditionalOperator *ACO =
10262 cast<AbstractConditionalOperator>(TypeExpr);
10263 bool Result;
10264 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
10265 if (Result)
10266 TypeExpr = ACO->getTrueExpr();
10267 else
10268 TypeExpr = ACO->getFalseExpr();
10269 continue;
10270 }
10271 return false;
10272 }
10273
10274 case Stmt::BinaryOperatorClass: {
10275 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
10276 if (BO->getOpcode() == BO_Comma) {
10277 TypeExpr = BO->getRHS();
10278 continue;
10279 }
10280 return false;
10281 }
10282
10283 default:
10284 return false;
10285 }
10286 }
10287}
10288
10289/// \brief Retrieve the C type corresponding to type tag TypeExpr.
10290///
10291/// \param TypeExpr Expression that specifies a type tag.
10292///
10293/// \param MagicValues Registered magic values.
10294///
10295/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
10296/// kind.
10297///
10298/// \param TypeInfo Information about the corresponding C type.
10299///
10300/// \returns true if the corresponding C type was found.
10301bool GetMatchingCType(
10302 const IdentifierInfo *ArgumentKind,
10303 const Expr *TypeExpr, const ASTContext &Ctx,
10304 const llvm::DenseMap<Sema::TypeTagMagicValue,
10305 Sema::TypeTagData> *MagicValues,
10306 bool &FoundWrongKind,
10307 Sema::TypeTagData &TypeInfo) {
10308 FoundWrongKind = false;
10309
10310 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +000010311 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010312
10313 uint64_t MagicValue;
10314
10315 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
10316 return false;
10317
10318 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +000010319 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010320 if (I->getArgumentKind() != ArgumentKind) {
10321 FoundWrongKind = true;
10322 return false;
10323 }
10324 TypeInfo.Type = I->getMatchingCType();
10325 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
10326 TypeInfo.MustBeNull = I->getMustBeNull();
10327 return true;
10328 }
10329 return false;
10330 }
10331
10332 if (!MagicValues)
10333 return false;
10334
10335 llvm::DenseMap<Sema::TypeTagMagicValue,
10336 Sema::TypeTagData>::const_iterator I =
10337 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
10338 if (I == MagicValues->end())
10339 return false;
10340
10341 TypeInfo = I->second;
10342 return true;
10343}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010344} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010345
10346void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
10347 uint64_t MagicValue, QualType Type,
10348 bool LayoutCompatible,
10349 bool MustBeNull) {
10350 if (!TypeTagForDatatypeMagicValues)
10351 TypeTagForDatatypeMagicValues.reset(
10352 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
10353
10354 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
10355 (*TypeTagForDatatypeMagicValues)[Magic] =
10356 TypeTagData(Type, LayoutCompatible, MustBeNull);
10357}
10358
10359namespace {
10360bool IsSameCharType(QualType T1, QualType T2) {
10361 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
10362 if (!BT1)
10363 return false;
10364
10365 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
10366 if (!BT2)
10367 return false;
10368
10369 BuiltinType::Kind T1Kind = BT1->getKind();
10370 BuiltinType::Kind T2Kind = BT2->getKind();
10371
10372 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
10373 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
10374 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
10375 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
10376}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010377} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010378
10379void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
10380 const Expr * const *ExprArgs) {
10381 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
10382 bool IsPointerAttr = Attr->getIsPointer();
10383
10384 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
10385 bool FoundWrongKind;
10386 TypeTagData TypeInfo;
10387 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
10388 TypeTagForDatatypeMagicValues.get(),
10389 FoundWrongKind, TypeInfo)) {
10390 if (FoundWrongKind)
10391 Diag(TypeTagExpr->getExprLoc(),
10392 diag::warn_type_tag_for_datatype_wrong_kind)
10393 << TypeTagExpr->getSourceRange();
10394 return;
10395 }
10396
10397 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
10398 if (IsPointerAttr) {
10399 // Skip implicit cast of pointer to `void *' (as a function argument).
10400 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +000010401 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +000010402 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010403 ArgumentExpr = ICE->getSubExpr();
10404 }
10405 QualType ArgumentType = ArgumentExpr->getType();
10406
10407 // Passing a `void*' pointer shouldn't trigger a warning.
10408 if (IsPointerAttr && ArgumentType->isVoidPointerType())
10409 return;
10410
10411 if (TypeInfo.MustBeNull) {
10412 // Type tag with matching void type requires a null pointer.
10413 if (!ArgumentExpr->isNullPointerConstant(Context,
10414 Expr::NPC_ValueDependentIsNotNull)) {
10415 Diag(ArgumentExpr->getExprLoc(),
10416 diag::warn_type_safety_null_pointer_required)
10417 << ArgumentKind->getName()
10418 << ArgumentExpr->getSourceRange()
10419 << TypeTagExpr->getSourceRange();
10420 }
10421 return;
10422 }
10423
10424 QualType RequiredType = TypeInfo.Type;
10425 if (IsPointerAttr)
10426 RequiredType = Context.getPointerType(RequiredType);
10427
10428 bool mismatch = false;
10429 if (!TypeInfo.LayoutCompatible) {
10430 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
10431
10432 // C++11 [basic.fundamental] p1:
10433 // Plain char, signed char, and unsigned char are three distinct types.
10434 //
10435 // But we treat plain `char' as equivalent to `signed char' or `unsigned
10436 // char' depending on the current char signedness mode.
10437 if (mismatch)
10438 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
10439 RequiredType->getPointeeType())) ||
10440 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
10441 mismatch = false;
10442 } else
10443 if (IsPointerAttr)
10444 mismatch = !isLayoutCompatible(Context,
10445 ArgumentType->getPointeeType(),
10446 RequiredType->getPointeeType());
10447 else
10448 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
10449
10450 if (mismatch)
10451 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +000010452 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010453 << TypeInfo.LayoutCompatible << RequiredType
10454 << ArgumentExpr->getSourceRange()
10455 << TypeTagExpr->getSourceRange();
10456}