blob: 062041e3771946f921285bfd1a5c361dc6a6d565 [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 Pan4415bdb2016-03-04 07:11:16 +0000328 if (!ArgTy || S.Context.hasSameType(EltTy, ArgTy->getPointeeType())) {
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000329 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000330 << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000331 << ArgIdx->getSourceRange();
332 return true;
333 }
334 return false;
335}
336
337// \brief Performs semantic analysis for the read/write_pipe call.
338// \param S Reference to the semantic analyzer.
339// \param Call A pointer to the builtin call.
340// \return True if a semantic error has been found, false otherwise.
341static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000342 // OpenCL v2.0 s6.13.16.2 - The built-in read/write
343 // functions have two forms.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000344 switch (Call->getNumArgs()) {
345 case 2: {
346 if (checkOpenCLPipeArg(S, Call))
347 return true;
348 // The call with 2 arguments should be
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000349 // read/write_pipe(pipe T, T*).
350 // Check packet type T.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000351 if (checkOpenCLPipePacketType(S, Call, 1))
352 return true;
353 } break;
354
355 case 4: {
356 if (checkOpenCLPipeArg(S, Call))
357 return true;
358 // The call with 4 arguments should be
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000359 // read/write_pipe(pipe T, reserve_id_t, uint, T*).
360 // Check reserve_id_t.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000361 if (!Call->getArg(1)->getType()->isReserveIDT()) {
362 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000363 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000364 << Call->getArg(1)->getSourceRange();
365 return true;
366 }
367
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000368 // Check the index.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000369 const Expr *Arg2 = Call->getArg(2);
370 if (!Arg2->getType()->isIntegerType() &&
371 !Arg2->getType()->isUnsignedIntegerType()) {
372 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000373 << Call->getDirectCallee() << S.Context.UnsignedIntTy
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000374 << Arg2->getSourceRange();
375 return true;
376 }
377
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000378 // Check packet type T.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000379 if (checkOpenCLPipePacketType(S, Call, 3))
380 return true;
381 } break;
382 default:
383 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000384 << Call->getDirectCallee() << Call->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000385 return true;
386 }
387
388 return false;
389}
390
391// \brief Performs a semantic analysis on the {work_group_/sub_group_
392// /_}reserve_{read/write}_pipe
393// \param S Reference to the semantic analyzer.
394// \param Call The call to the builtin function to be analyzed.
395// \return True if a semantic error was found, false otherwise.
396static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
397 if (checkArgCount(S, Call, 2))
398 return true;
399
400 if (checkOpenCLPipeArg(S, Call))
401 return true;
402
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000403 // Check the reserve size.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000404 if (!Call->getArg(1)->getType()->isIntegerType() &&
405 !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
406 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000407 << Call->getDirectCallee() << S.Context.UnsignedIntTy
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000408 << Call->getArg(1)->getSourceRange();
409 return true;
410 }
411
412 return false;
413}
414
415// \brief Performs a semantic analysis on {work_group_/sub_group_
416// /_}commit_{read/write}_pipe
417// \param S Reference to the semantic analyzer.
418// \param Call The call to the builtin function to be analyzed.
419// \return True if a semantic error was found, false otherwise.
420static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
421 if (checkArgCount(S, Call, 2))
422 return true;
423
424 if (checkOpenCLPipeArg(S, Call))
425 return true;
426
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000427 // Check reserve_id_t.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000428 if (!Call->getArg(1)->getType()->isReserveIDT()) {
429 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000430 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000431 << Call->getArg(1)->getSourceRange();
432 return true;
433 }
434
435 return false;
436}
437
438// \brief Performs a semantic analysis on the call to built-in Pipe
439// Query Functions.
440// \param S Reference to the semantic analyzer.
441// \param Call The call to the builtin function to be analyzed.
442// \return True if a semantic error was found, false otherwise.
443static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
444 if (checkArgCount(S, Call, 1))
445 return true;
446
447 if (!Call->getArg(0)->getType()->isPipeType()) {
448 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000449 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000450 return true;
451 }
452
453 return false;
454}
455
John McCalldadc5752010-08-24 06:29:42 +0000456ExprResult
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000457Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
458 CallExpr *TheCall) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000459 ExprResult TheCallResult(TheCall);
Douglas Gregorae2fbad2008-11-17 20:34:05 +0000460
Chris Lattner3be167f2010-10-01 23:23:24 +0000461 // Find out if any arguments are required to be integer constant expressions.
462 unsigned ICEArguments = 0;
463 ASTContext::GetBuiltinTypeError Error;
464 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
465 if (Error != ASTContext::GE_None)
466 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
467
468 // If any arguments are required to be ICE's, check and diagnose.
469 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
470 // Skip arguments not required to be ICE's.
471 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
472
473 llvm::APSInt Result;
474 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
475 return true;
476 ICEArguments &= ~(1 << ArgNo);
477 }
478
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000479 switch (BuiltinID) {
Chris Lattner43be2e62007-12-19 23:59:04 +0000480 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner08464942007-12-28 05:29:59 +0000481 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner2da14fb2007-12-20 00:26:33 +0000482 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner6436fb62009-02-18 06:01:06 +0000483 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000484 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000485 break;
Ted Kremeneka174c522008-07-09 17:58:53 +0000486 case Builtin::BI__builtin_stdarg_start:
Chris Lattner43be2e62007-12-19 23:59:04 +0000487 case Builtin::BI__builtin_va_start:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000488 if (SemaBuiltinVAStart(TheCall))
489 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000490 break;
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000491 case Builtin::BI__va_start: {
492 switch (Context.getTargetInfo().getTriple().getArch()) {
493 case llvm::Triple::arm:
494 case llvm::Triple::thumb:
495 if (SemaBuiltinVAStartARM(TheCall))
496 return ExprError();
497 break;
498 default:
499 if (SemaBuiltinVAStart(TheCall))
500 return ExprError();
501 break;
502 }
503 break;
504 }
Chris Lattner2da14fb2007-12-20 00:26:33 +0000505 case Builtin::BI__builtin_isgreater:
506 case Builtin::BI__builtin_isgreaterequal:
507 case Builtin::BI__builtin_isless:
508 case Builtin::BI__builtin_islessequal:
509 case Builtin::BI__builtin_islessgreater:
510 case Builtin::BI__builtin_isunordered:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000511 if (SemaBuiltinUnorderedCompare(TheCall))
512 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000513 break;
Benjamin Kramer634fc102010-02-15 22:42:31 +0000514 case Builtin::BI__builtin_fpclassify:
515 if (SemaBuiltinFPClassification(TheCall, 6))
516 return ExprError();
517 break;
Eli Friedman7e4faac2009-08-31 20:06:00 +0000518 case Builtin::BI__builtin_isfinite:
519 case Builtin::BI__builtin_isinf:
520 case Builtin::BI__builtin_isinf_sign:
521 case Builtin::BI__builtin_isnan:
522 case Builtin::BI__builtin_isnormal:
Benjamin Kramer64aae502010-02-16 10:07:31 +0000523 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman7e4faac2009-08-31 20:06:00 +0000524 return ExprError();
525 break;
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000526 case Builtin::BI__builtin_shufflevector:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000527 return SemaBuiltinShuffleVector(TheCall);
528 // TheCall will be freed by the smart pointer here, but that's fine, since
529 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbarb7257262008-07-21 22:59:13 +0000530 case Builtin::BI__builtin_prefetch:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000531 if (SemaBuiltinPrefetch(TheCall))
532 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000533 break;
Hal Finkelf0417332014-07-17 14:25:55 +0000534 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +0000535 case Builtin::BI__builtin_assume:
Hal Finkelf0417332014-07-17 14:25:55 +0000536 if (SemaBuiltinAssume(TheCall))
537 return ExprError();
538 break;
Hal Finkelbcc06082014-09-07 22:58:14 +0000539 case Builtin::BI__builtin_assume_aligned:
540 if (SemaBuiltinAssumeAligned(TheCall))
541 return ExprError();
542 break;
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000543 case Builtin::BI__builtin_object_size:
Richard Sandiford28940af2014-04-16 08:47:51 +0000544 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000545 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000546 break;
Eli Friedmaneed8ad22009-05-03 04:46:36 +0000547 case Builtin::BI__builtin_longjmp:
548 if (SemaBuiltinLongjmp(TheCall))
549 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000550 break;
Joerg Sonnenberger27173282015-03-11 23:46:32 +0000551 case Builtin::BI__builtin_setjmp:
552 if (SemaBuiltinSetjmp(TheCall))
553 return ExprError();
554 break;
David Majnemerc403a1c2015-03-20 17:03:35 +0000555 case Builtin::BI_setjmp:
556 case Builtin::BI_setjmpex:
557 if (checkArgCount(*this, TheCall, 1))
558 return true;
559 break;
John McCallbebede42011-02-26 05:39:39 +0000560
561 case Builtin::BI__builtin_classify_type:
562 if (checkArgCount(*this, TheCall, 1)) return true;
563 TheCall->setType(Context.IntTy);
564 break;
Chris Lattner17c0eac2010-10-12 17:47:42 +0000565 case Builtin::BI__builtin_constant_p:
John McCallbebede42011-02-26 05:39:39 +0000566 if (checkArgCount(*this, TheCall, 1)) return true;
567 TheCall->setType(Context.IntTy);
Chris Lattner17c0eac2010-10-12 17:47:42 +0000568 break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000569 case Builtin::BI__sync_fetch_and_add:
Douglas Gregor73722482011-11-28 16:30:08 +0000570 case Builtin::BI__sync_fetch_and_add_1:
571 case Builtin::BI__sync_fetch_and_add_2:
572 case Builtin::BI__sync_fetch_and_add_4:
573 case Builtin::BI__sync_fetch_and_add_8:
574 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000575 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregor73722482011-11-28 16:30:08 +0000576 case Builtin::BI__sync_fetch_and_sub_1:
577 case Builtin::BI__sync_fetch_and_sub_2:
578 case Builtin::BI__sync_fetch_and_sub_4:
579 case Builtin::BI__sync_fetch_and_sub_8:
580 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000581 case Builtin::BI__sync_fetch_and_or:
Douglas Gregor73722482011-11-28 16:30:08 +0000582 case Builtin::BI__sync_fetch_and_or_1:
583 case Builtin::BI__sync_fetch_and_or_2:
584 case Builtin::BI__sync_fetch_and_or_4:
585 case Builtin::BI__sync_fetch_and_or_8:
586 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000587 case Builtin::BI__sync_fetch_and_and:
Douglas Gregor73722482011-11-28 16:30:08 +0000588 case Builtin::BI__sync_fetch_and_and_1:
589 case Builtin::BI__sync_fetch_and_and_2:
590 case Builtin::BI__sync_fetch_and_and_4:
591 case Builtin::BI__sync_fetch_and_and_8:
592 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000593 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregor73722482011-11-28 16:30:08 +0000594 case Builtin::BI__sync_fetch_and_xor_1:
595 case Builtin::BI__sync_fetch_and_xor_2:
596 case Builtin::BI__sync_fetch_and_xor_4:
597 case Builtin::BI__sync_fetch_and_xor_8:
598 case Builtin::BI__sync_fetch_and_xor_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000599 case Builtin::BI__sync_fetch_and_nand:
600 case Builtin::BI__sync_fetch_and_nand_1:
601 case Builtin::BI__sync_fetch_and_nand_2:
602 case Builtin::BI__sync_fetch_and_nand_4:
603 case Builtin::BI__sync_fetch_and_nand_8:
604 case Builtin::BI__sync_fetch_and_nand_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000605 case Builtin::BI__sync_add_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000606 case Builtin::BI__sync_add_and_fetch_1:
607 case Builtin::BI__sync_add_and_fetch_2:
608 case Builtin::BI__sync_add_and_fetch_4:
609 case Builtin::BI__sync_add_and_fetch_8:
610 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000611 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000612 case Builtin::BI__sync_sub_and_fetch_1:
613 case Builtin::BI__sync_sub_and_fetch_2:
614 case Builtin::BI__sync_sub_and_fetch_4:
615 case Builtin::BI__sync_sub_and_fetch_8:
616 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000617 case Builtin::BI__sync_and_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000618 case Builtin::BI__sync_and_and_fetch_1:
619 case Builtin::BI__sync_and_and_fetch_2:
620 case Builtin::BI__sync_and_and_fetch_4:
621 case Builtin::BI__sync_and_and_fetch_8:
622 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000623 case Builtin::BI__sync_or_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000624 case Builtin::BI__sync_or_and_fetch_1:
625 case Builtin::BI__sync_or_and_fetch_2:
626 case Builtin::BI__sync_or_and_fetch_4:
627 case Builtin::BI__sync_or_and_fetch_8:
628 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000629 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000630 case Builtin::BI__sync_xor_and_fetch_1:
631 case Builtin::BI__sync_xor_and_fetch_2:
632 case Builtin::BI__sync_xor_and_fetch_4:
633 case Builtin::BI__sync_xor_and_fetch_8:
634 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000635 case Builtin::BI__sync_nand_and_fetch:
636 case Builtin::BI__sync_nand_and_fetch_1:
637 case Builtin::BI__sync_nand_and_fetch_2:
638 case Builtin::BI__sync_nand_and_fetch_4:
639 case Builtin::BI__sync_nand_and_fetch_8:
640 case Builtin::BI__sync_nand_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000641 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000642 case Builtin::BI__sync_val_compare_and_swap_1:
643 case Builtin::BI__sync_val_compare_and_swap_2:
644 case Builtin::BI__sync_val_compare_and_swap_4:
645 case Builtin::BI__sync_val_compare_and_swap_8:
646 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000647 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000648 case Builtin::BI__sync_bool_compare_and_swap_1:
649 case Builtin::BI__sync_bool_compare_and_swap_2:
650 case Builtin::BI__sync_bool_compare_and_swap_4:
651 case Builtin::BI__sync_bool_compare_and_swap_8:
652 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000653 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +0000654 case Builtin::BI__sync_lock_test_and_set_1:
655 case Builtin::BI__sync_lock_test_and_set_2:
656 case Builtin::BI__sync_lock_test_and_set_4:
657 case Builtin::BI__sync_lock_test_and_set_8:
658 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000659 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +0000660 case Builtin::BI__sync_lock_release_1:
661 case Builtin::BI__sync_lock_release_2:
662 case Builtin::BI__sync_lock_release_4:
663 case Builtin::BI__sync_lock_release_8:
664 case Builtin::BI__sync_lock_release_16:
Chris Lattner9cb59fa2011-04-09 03:57:26 +0000665 case Builtin::BI__sync_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000666 case Builtin::BI__sync_swap_1:
667 case Builtin::BI__sync_swap_2:
668 case Builtin::BI__sync_swap_4:
669 case Builtin::BI__sync_swap_8:
670 case Builtin::BI__sync_swap_16:
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000671 return SemaBuiltinAtomicOverloaded(TheCallResult);
Michael Zolotukhin84df1232015-09-08 23:52:33 +0000672 case Builtin::BI__builtin_nontemporal_load:
673 case Builtin::BI__builtin_nontemporal_store:
674 return SemaBuiltinNontemporalOverloaded(TheCallResult);
Richard Smithfeea8832012-04-12 05:08:17 +0000675#define BUILTIN(ID, TYPE, ATTRS)
676#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
677 case Builtin::BI##ID: \
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000678 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithfeea8832012-04-12 05:08:17 +0000679#include "clang/Basic/Builtins.def"
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000680 case Builtin::BI__builtin_annotation:
Julien Lerouge4a5b4442012-04-28 17:39:16 +0000681 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000682 return ExprError();
683 break;
Richard Smith6cbd65d2013-07-11 02:27:57 +0000684 case Builtin::BI__builtin_addressof:
685 if (SemaBuiltinAddressof(*this, TheCall))
686 return ExprError();
687 break;
John McCall03107a42015-10-29 20:48:01 +0000688 case Builtin::BI__builtin_add_overflow:
689 case Builtin::BI__builtin_sub_overflow:
690 case Builtin::BI__builtin_mul_overflow:
Craig Toppera86e70d2015-11-07 06:16:14 +0000691 if (SemaBuiltinOverflow(*this, TheCall))
692 return ExprError();
693 break;
Richard Smith760520b2014-06-03 23:27:44 +0000694 case Builtin::BI__builtin_operator_new:
695 case Builtin::BI__builtin_operator_delete:
696 if (!getLangOpts().CPlusPlus) {
697 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
698 << (BuiltinID == Builtin::BI__builtin_operator_new
699 ? "__builtin_operator_new"
700 : "__builtin_operator_delete")
701 << "C++";
702 return ExprError();
703 }
704 // CodeGen assumes it can find the global new and delete to call,
705 // so ensure that they are declared.
706 DeclareGlobalNewDelete();
707 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000708
709 // check secure string manipulation functions where overflows
710 // are detectable at compile time
711 case Builtin::BI__builtin___memcpy_chk:
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000712 case Builtin::BI__builtin___memmove_chk:
713 case Builtin::BI__builtin___memset_chk:
714 case Builtin::BI__builtin___strlcat_chk:
715 case Builtin::BI__builtin___strlcpy_chk:
716 case Builtin::BI__builtin___strncat_chk:
717 case Builtin::BI__builtin___strncpy_chk:
718 case Builtin::BI__builtin___stpncpy_chk:
719 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
720 break;
Steven Wu566c14e2014-09-24 04:37:33 +0000721 case Builtin::BI__builtin___memccpy_chk:
722 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
723 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000724 case Builtin::BI__builtin___snprintf_chk:
725 case Builtin::BI__builtin___vsnprintf_chk:
726 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
727 break;
Peter Collingbournef7706832014-12-12 23:41:25 +0000728 case Builtin::BI__builtin_call_with_static_chain:
729 if (SemaBuiltinCallWithStaticChain(*this, TheCall))
730 return ExprError();
731 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +0000732 case Builtin::BI__exception_code:
Eugene Zelenko1ced5092016-02-12 22:53:10 +0000733 case Builtin::BI_exception_code:
Reid Kleckner1d59f992015-01-22 01:36:17 +0000734 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
735 diag::err_seh___except_block))
736 return ExprError();
737 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +0000738 case Builtin::BI__exception_info:
Eugene Zelenko1ced5092016-02-12 22:53:10 +0000739 case Builtin::BI_exception_info:
Reid Kleckner1d59f992015-01-22 01:36:17 +0000740 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
741 diag::err_seh___except_filter))
742 return ExprError();
743 break;
David Majnemerba3e5ec2015-03-13 18:26:17 +0000744 case Builtin::BI__GetExceptionInfo:
745 if (checkArgCount(*this, TheCall, 1))
746 return ExprError();
747
748 if (CheckCXXThrowOperand(
749 TheCall->getLocStart(),
750 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
751 TheCall))
752 return ExprError();
753
754 TheCall->setType(Context.VoidPtrTy);
755 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000756 case Builtin::BIread_pipe:
757 case Builtin::BIwrite_pipe:
758 // Since those two functions are declared with var args, we need a semantic
759 // check for the argument.
760 if (SemaBuiltinRWPipe(*this, TheCall))
761 return ExprError();
762 break;
763 case Builtin::BIreserve_read_pipe:
764 case Builtin::BIreserve_write_pipe:
765 case Builtin::BIwork_group_reserve_read_pipe:
766 case Builtin::BIwork_group_reserve_write_pipe:
767 case Builtin::BIsub_group_reserve_read_pipe:
768 case Builtin::BIsub_group_reserve_write_pipe:
769 if (SemaBuiltinReserveRWPipe(*this, TheCall))
770 return ExprError();
771 // Since return type of reserve_read/write_pipe built-in function is
772 // reserve_id_t, which is not defined in the builtin def file , we used int
773 // as return type and need to override the return type of these functions.
774 TheCall->setType(Context.OCLReserveIDTy);
775 break;
776 case Builtin::BIcommit_read_pipe:
777 case Builtin::BIcommit_write_pipe:
778 case Builtin::BIwork_group_commit_read_pipe:
779 case Builtin::BIwork_group_commit_write_pipe:
780 case Builtin::BIsub_group_commit_read_pipe:
781 case Builtin::BIsub_group_commit_write_pipe:
782 if (SemaBuiltinCommitRWPipe(*this, TheCall))
783 return ExprError();
784 break;
785 case Builtin::BIget_pipe_num_packets:
786 case Builtin::BIget_pipe_max_packets:
787 if (SemaBuiltinPipePackets(*this, TheCall))
788 return ExprError();
789 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000790 }
Richard Smith760520b2014-06-03 23:27:44 +0000791
Nate Begeman4904e322010-06-08 02:47:44 +0000792 // Since the target specific builtins for each arch overlap, only check those
793 // of the arch we are compiling for.
Artem Belevich9674a642015-09-22 17:23:05 +0000794 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000795 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +0000796 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +0000797 case llvm::Triple::armeb:
Nate Begeman4904e322010-06-08 02:47:44 +0000798 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +0000799 case llvm::Triple::thumbeb:
Nate Begeman4904e322010-06-08 02:47:44 +0000800 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
801 return ExprError();
802 break;
Tim Northover25e8a672014-05-24 12:51:25 +0000803 case llvm::Triple::aarch64:
804 case llvm::Triple::aarch64_be:
Tim Northover573cbee2014-05-24 12:52:07 +0000805 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
Tim Northovera2ee4332014-03-29 15:09:45 +0000806 return ExprError();
807 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000808 case llvm::Triple::mips:
809 case llvm::Triple::mipsel:
810 case llvm::Triple::mips64:
811 case llvm::Triple::mips64el:
812 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
813 return ExprError();
814 break;
Ulrich Weigand3a610eb2015-04-01 12:54:25 +0000815 case llvm::Triple::systemz:
816 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
817 return ExprError();
818 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000819 case llvm::Triple::x86:
820 case llvm::Triple::x86_64:
821 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
822 return ExprError();
823 break;
Kit Bartone50adcb2015-03-30 19:40:59 +0000824 case llvm::Triple::ppc:
825 case llvm::Triple::ppc64:
826 case llvm::Triple::ppc64le:
827 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
828 return ExprError();
829 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000830 default:
831 break;
832 }
833 }
834
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000835 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +0000836}
837
Nate Begeman91e1fea2010-06-14 05:21:25 +0000838// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +0000839static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +0000840 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +0000841 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +0000842 switch (Type.getEltType()) {
843 case NeonTypeFlags::Int8:
844 case NeonTypeFlags::Poly8:
845 return shift ? 7 : (8 << IsQuad) - 1;
846 case NeonTypeFlags::Int16:
847 case NeonTypeFlags::Poly16:
848 return shift ? 15 : (4 << IsQuad) - 1;
849 case NeonTypeFlags::Int32:
850 return shift ? 31 : (2 << IsQuad) - 1;
851 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +0000852 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +0000853 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000854 case NeonTypeFlags::Poly128:
855 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +0000856 case NeonTypeFlags::Float16:
857 assert(!shift && "cannot shift float types!");
858 return (4 << IsQuad) - 1;
859 case NeonTypeFlags::Float32:
860 assert(!shift && "cannot shift float types!");
861 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000862 case NeonTypeFlags::Float64:
863 assert(!shift && "cannot shift float types!");
864 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000865 }
David Blaikie8a40f702012-01-17 06:56:22 +0000866 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +0000867}
868
Bob Wilsone4d77232011-11-08 05:04:11 +0000869/// getNeonEltType - Return the QualType corresponding to the elements of
870/// the vector type specified by the NeonTypeFlags. This is used to check
871/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +0000872static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Tim Northovera2ee4332014-03-29 15:09:45 +0000873 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilsone4d77232011-11-08 05:04:11 +0000874 switch (Flags.getEltType()) {
875 case NeonTypeFlags::Int8:
876 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
877 case NeonTypeFlags::Int16:
878 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
879 case NeonTypeFlags::Int32:
880 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
881 case NeonTypeFlags::Int64:
Tim Northovera2ee4332014-03-29 15:09:45 +0000882 if (IsInt64Long)
Kevin Qinad64f6d2014-02-24 02:45:03 +0000883 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
884 else
885 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
886 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000887 case NeonTypeFlags::Poly8:
Tim Northovera2ee4332014-03-29 15:09:45 +0000888 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000889 case NeonTypeFlags::Poly16:
Tim Northovera2ee4332014-03-29 15:09:45 +0000890 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qincaac85e2013-11-14 03:29:16 +0000891 case NeonTypeFlags::Poly64:
Kevin Qin78b86532015-05-14 08:18:05 +0000892 if (IsInt64Long)
893 return Context.UnsignedLongTy;
894 else
895 return Context.UnsignedLongLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000896 case NeonTypeFlags::Poly128:
897 break;
Bob Wilsone4d77232011-11-08 05:04:11 +0000898 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +0000899 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000900 case NeonTypeFlags::Float32:
901 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +0000902 case NeonTypeFlags::Float64:
903 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000904 }
David Blaikie8a40f702012-01-17 06:56:22 +0000905 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +0000906}
907
Tim Northover12670412014-02-19 10:37:05 +0000908bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +0000909 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +0000910 uint64_t mask = 0;
911 unsigned TV = 0;
912 int PtrArgNum = -1;
913 bool HasConstPtr = false;
914 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +0000915#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000916#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000917#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000918 }
919
920 // For NEON intrinsics which are overloaded on vector element type, validate
921 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +0000922 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000923 if (mask) {
924 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
925 return true;
926
927 TV = Result.getLimitedValue(64);
928 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
929 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Tim Northover12670412014-02-19 10:37:05 +0000930 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +0000931 }
932
933 if (PtrArgNum >= 0) {
934 // Check that pointer arguments have the specified type.
935 Expr *Arg = TheCall->getArg(PtrArgNum);
936 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
937 Arg = ICE->getSubExpr();
938 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
939 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +0000940
Tim Northovera2ee4332014-03-29 15:09:45 +0000941 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Tim Northover40956e62014-07-23 12:32:58 +0000942 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64;
Tim Northovera2ee4332014-03-29 15:09:45 +0000943 bool IsInt64Long =
944 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
945 QualType EltTy =
946 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northover2fe823a2013-08-01 09:23:19 +0000947 if (HasConstPtr)
948 EltTy = EltTy.withConst();
949 QualType LHSTy = Context.getPointerType(EltTy);
950 AssignConvertType ConvTy;
951 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
952 if (RHS.isInvalid())
953 return true;
954 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
955 RHS.get(), AA_Assigning))
956 return true;
957 }
958
959 // For NEON intrinsics which take an immediate value as part of the
960 // instruction, range check them here.
961 unsigned i = 0, l = 0, u = 0;
962 switch (BuiltinID) {
963 default:
964 return false;
Tim Northover12670412014-02-19 10:37:05 +0000965#define GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000966#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000967#undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000968 }
Tim Northover2fe823a2013-08-01 09:23:19 +0000969
Richard Sandiford28940af2014-04-16 08:47:51 +0000970 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northover2fe823a2013-08-01 09:23:19 +0000971}
972
Tim Northovera2ee4332014-03-29 15:09:45 +0000973bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
974 unsigned MaxWidth) {
Tim Northover6aacd492013-07-16 09:47:53 +0000975 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000976 BuiltinID == ARM::BI__builtin_arm_ldaex ||
Tim Northovera2ee4332014-03-29 15:09:45 +0000977 BuiltinID == ARM::BI__builtin_arm_strex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000978 BuiltinID == ARM::BI__builtin_arm_stlex ||
Tim Northover573cbee2014-05-24 12:52:07 +0000979 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000980 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
981 BuiltinID == AArch64::BI__builtin_arm_strex ||
982 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
Tim Northover6aacd492013-07-16 09:47:53 +0000983 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +0000984 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000985 BuiltinID == ARM::BI__builtin_arm_ldaex ||
986 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
987 BuiltinID == AArch64::BI__builtin_arm_ldaex;
Tim Northover6aacd492013-07-16 09:47:53 +0000988
989 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
990
991 // Ensure that we have the proper number of arguments.
992 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
993 return true;
994
995 // Inspect the pointer argument of the atomic builtin. This should always be
996 // a pointer type, whose element is an integral scalar or pointer type.
997 // Because it is a pointer type, we don't have to worry about any implicit
998 // casts here.
999 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1000 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1001 if (PointerArgRes.isInvalid())
1002 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001003 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001004
1005 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1006 if (!pointerType) {
1007 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1008 << PointerArg->getType() << PointerArg->getSourceRange();
1009 return true;
1010 }
1011
1012 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1013 // task is to insert the appropriate casts into the AST. First work out just
1014 // what the appropriate type is.
1015 QualType ValType = pointerType->getPointeeType();
1016 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1017 if (IsLdrex)
1018 AddrType.addConst();
1019
1020 // Issue a warning if the cast is dodgy.
1021 CastKind CastNeeded = CK_NoOp;
1022 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1023 CastNeeded = CK_BitCast;
1024 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
1025 << PointerArg->getType()
1026 << Context.getPointerType(AddrType)
1027 << AA_Passing << PointerArg->getSourceRange();
1028 }
1029
1030 // Finally, do the cast and replace the argument with the corrected version.
1031 AddrType = Context.getPointerType(AddrType);
1032 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1033 if (PointerArgRes.isInvalid())
1034 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001035 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001036
1037 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1038
1039 // In general, we allow ints, floats and pointers to be loaded and stored.
1040 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1041 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1042 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1043 << PointerArg->getType() << PointerArg->getSourceRange();
1044 return true;
1045 }
1046
1047 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +00001048 if (Context.getTypeSize(ValType) > MaxWidth) {
1049 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover6aacd492013-07-16 09:47:53 +00001050 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
1051 << PointerArg->getType() << PointerArg->getSourceRange();
1052 return true;
1053 }
1054
1055 switch (ValType.getObjCLifetime()) {
1056 case Qualifiers::OCL_None:
1057 case Qualifiers::OCL_ExplicitNone:
1058 // okay
1059 break;
1060
1061 case Qualifiers::OCL_Weak:
1062 case Qualifiers::OCL_Strong:
1063 case Qualifiers::OCL_Autoreleasing:
1064 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1065 << ValType << PointerArg->getSourceRange();
1066 return true;
1067 }
1068
Tim Northover6aacd492013-07-16 09:47:53 +00001069 if (IsLdrex) {
1070 TheCall->setType(ValType);
1071 return false;
1072 }
1073
1074 // Initialize the argument to be stored.
1075 ExprResult ValArg = TheCall->getArg(0);
1076 InitializedEntity Entity = InitializedEntity::InitializeParameter(
1077 Context, ValType, /*consume*/ false);
1078 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1079 if (ValArg.isInvalid())
1080 return true;
Tim Northover6aacd492013-07-16 09:47:53 +00001081 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +00001082
1083 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1084 // but the custom checker bypasses all default analysis.
1085 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +00001086 return false;
1087}
1088
Nate Begeman4904e322010-06-08 02:47:44 +00001089bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman55483092010-06-09 01:10:23 +00001090 llvm::APSInt Result;
1091
Tim Northover6aacd492013-07-16 09:47:53 +00001092 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001093 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1094 BuiltinID == ARM::BI__builtin_arm_strex ||
1095 BuiltinID == ARM::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001096 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +00001097 }
1098
Yi Kong26d104a2014-08-13 19:18:14 +00001099 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1100 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1101 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1102 }
1103
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001104 if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1105 BuiltinID == ARM::BI__builtin_arm_wsr64)
1106 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1107
1108 if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1109 BuiltinID == ARM::BI__builtin_arm_rsrp ||
1110 BuiltinID == ARM::BI__builtin_arm_wsr ||
1111 BuiltinID == ARM::BI__builtin_arm_wsrp)
1112 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1113
Tim Northover12670412014-02-19 10:37:05 +00001114 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1115 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +00001116
Yi Kong4efadfb2014-07-03 16:01:25 +00001117 // For intrinsics which take an immediate value as part of the instruction,
1118 // range check them here.
Nate Begeman91e1fea2010-06-14 05:21:25 +00001119 unsigned i = 0, l = 0, u = 0;
Nate Begemand773fe62010-06-13 04:47:52 +00001120 switch (BuiltinID) {
1121 default: return false;
Nate Begeman1194bd22010-07-29 22:48:34 +00001122 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
1123 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begemanf568b072010-08-03 21:32:34 +00001124 case ARM::BI__builtin_arm_vcvtr_f:
1125 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Weiming Zhao87bb4922013-11-12 21:42:50 +00001126 case ARM::BI__builtin_arm_dmb:
Yi Kong4efadfb2014-07-03 16:01:25 +00001127 case ARM::BI__builtin_arm_dsb:
Yi Kong1d268af2014-08-26 12:48:06 +00001128 case ARM::BI__builtin_arm_isb:
1129 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00001130 }
Nate Begemand773fe62010-06-13 04:47:52 +00001131
Nate Begemanf568b072010-08-03 21:32:34 +00001132 // FIXME: VFP Intrinsics should error if VFP not present.
Richard Sandiford28940af2014-04-16 08:47:51 +00001133 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001134}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001135
Tim Northover573cbee2014-05-24 12:52:07 +00001136bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +00001137 CallExpr *TheCall) {
1138 llvm::APSInt Result;
1139
Tim Northover573cbee2014-05-24 12:52:07 +00001140 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001141 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1142 BuiltinID == AArch64::BI__builtin_arm_strex ||
1143 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001144 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1145 }
1146
Yi Konga5548432014-08-13 19:18:20 +00001147 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1148 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1149 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1150 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1151 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1152 }
1153
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001154 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1155 BuiltinID == AArch64::BI__builtin_arm_wsr64)
1156 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, false);
1157
1158 if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1159 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1160 BuiltinID == AArch64::BI__builtin_arm_wsr ||
1161 BuiltinID == AArch64::BI__builtin_arm_wsrp)
1162 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1163
Tim Northovera2ee4332014-03-29 15:09:45 +00001164 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1165 return true;
1166
Yi Kong19a29ac2014-07-17 10:52:06 +00001167 // For intrinsics which take an immediate value as part of the instruction,
1168 // range check them here.
1169 unsigned i = 0, l = 0, u = 0;
1170 switch (BuiltinID) {
1171 default: return false;
1172 case AArch64::BI__builtin_arm_dmb:
1173 case AArch64::BI__builtin_arm_dsb:
1174 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1175 }
1176
Yi Kong19a29ac2014-07-17 10:52:06 +00001177 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northovera2ee4332014-03-29 15:09:45 +00001178}
1179
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001180bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1181 unsigned i = 0, l = 0, u = 0;
1182 switch (BuiltinID) {
1183 default: return false;
1184 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
1185 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +00001186 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
1187 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
1188 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
1189 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
1190 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00001191 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001192
Richard Sandiford28940af2014-04-16 08:47:51 +00001193 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001194}
1195
Kit Bartone50adcb2015-03-30 19:40:59 +00001196bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1197 unsigned i = 0, l = 0, u = 0;
Nemanja Ivanovic239eec72015-04-09 23:58:16 +00001198 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
1199 BuiltinID == PPC::BI__builtin_divdeu ||
1200 BuiltinID == PPC::BI__builtin_bpermd;
1201 bool IsTarget64Bit = Context.getTargetInfo()
1202 .getTypeWidth(Context
1203 .getTargetInfo()
1204 .getIntPtrType()) == 64;
1205 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
1206 BuiltinID == PPC::BI__builtin_divweu ||
1207 BuiltinID == PPC::BI__builtin_divde ||
1208 BuiltinID == PPC::BI__builtin_divdeu;
1209
1210 if (Is64BitBltin && !IsTarget64Bit)
1211 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
1212 << TheCall->getSourceRange();
1213
1214 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
1215 (BuiltinID == PPC::BI__builtin_bpermd &&
1216 !Context.getTargetInfo().hasFeature("bpermd")))
1217 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
1218 << TheCall->getSourceRange();
1219
Kit Bartone50adcb2015-03-30 19:40:59 +00001220 switch (BuiltinID) {
1221 default: return false;
1222 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
1223 case PPC::BI__builtin_altivec_crypto_vshasigmad:
1224 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1225 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1226 case PPC::BI__builtin_tbegin:
1227 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
1228 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
1229 case PPC::BI__builtin_tabortwc:
1230 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
1231 case PPC::BI__builtin_tabortwci:
1232 case PPC::BI__builtin_tabortdci:
1233 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
1234 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
1235 }
1236 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1237}
1238
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001239bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
1240 CallExpr *TheCall) {
1241 if (BuiltinID == SystemZ::BI__builtin_tabort) {
1242 Expr *Arg = TheCall->getArg(0);
1243 llvm::APSInt AbortCode(32);
1244 if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
1245 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
1246 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
1247 << Arg->getSourceRange();
1248 }
1249
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001250 // For intrinsics which take an immediate value as part of the instruction,
1251 // range check them here.
1252 unsigned i = 0, l = 0, u = 0;
1253 switch (BuiltinID) {
1254 default: return false;
1255 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
1256 case SystemZ::BI__builtin_s390_verimb:
1257 case SystemZ::BI__builtin_s390_verimh:
1258 case SystemZ::BI__builtin_s390_verimf:
1259 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
1260 case SystemZ::BI__builtin_s390_vfaeb:
1261 case SystemZ::BI__builtin_s390_vfaeh:
1262 case SystemZ::BI__builtin_s390_vfaef:
1263 case SystemZ::BI__builtin_s390_vfaebs:
1264 case SystemZ::BI__builtin_s390_vfaehs:
1265 case SystemZ::BI__builtin_s390_vfaefs:
1266 case SystemZ::BI__builtin_s390_vfaezb:
1267 case SystemZ::BI__builtin_s390_vfaezh:
1268 case SystemZ::BI__builtin_s390_vfaezf:
1269 case SystemZ::BI__builtin_s390_vfaezbs:
1270 case SystemZ::BI__builtin_s390_vfaezhs:
1271 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
1272 case SystemZ::BI__builtin_s390_vfidb:
1273 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1274 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1275 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
1276 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
1277 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
1278 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
1279 case SystemZ::BI__builtin_s390_vstrcb:
1280 case SystemZ::BI__builtin_s390_vstrch:
1281 case SystemZ::BI__builtin_s390_vstrcf:
1282 case SystemZ::BI__builtin_s390_vstrczb:
1283 case SystemZ::BI__builtin_s390_vstrczh:
1284 case SystemZ::BI__builtin_s390_vstrczf:
1285 case SystemZ::BI__builtin_s390_vstrcbs:
1286 case SystemZ::BI__builtin_s390_vstrchs:
1287 case SystemZ::BI__builtin_s390_vstrcfs:
1288 case SystemZ::BI__builtin_s390_vstrczbs:
1289 case SystemZ::BI__builtin_s390_vstrczhs:
1290 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
1291 }
1292 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001293}
1294
Craig Topper5ba2c502015-11-07 08:08:31 +00001295/// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
1296/// This checks that the target supports __builtin_cpu_supports and
1297/// that the string argument is constant and valid.
1298static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
1299 Expr *Arg = TheCall->getArg(0);
1300
1301 // Check if the argument is a string literal.
1302 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1303 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1304 << Arg->getSourceRange();
1305
1306 // Check the contents of the string.
1307 StringRef Feature =
1308 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1309 if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
1310 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
1311 << Arg->getSourceRange();
1312 return false;
1313}
1314
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001315bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Craig Topperdd84ec52014-12-27 07:00:08 +00001316 unsigned i = 0, l = 0, u = 0;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001317 switch (BuiltinID) {
Richard Trieucc3949d2016-02-18 22:34:54 +00001318 default:
1319 return false;
Eric Christopherd9832702015-06-29 21:00:05 +00001320 case X86::BI__builtin_cpu_supports:
Craig Topper5ba2c502015-11-07 08:08:31 +00001321 return SemaBuiltinCpuSupports(*this, TheCall);
Charles Davisc7d5c942015-09-17 20:55:33 +00001322 case X86::BI__builtin_ms_va_start:
1323 return SemaBuiltinMSVAStart(TheCall);
Richard Trieucc3949d2016-02-18 22:34:54 +00001324 case X86::BI_mm_prefetch:
1325 i = 1;
1326 l = 0;
1327 u = 3;
1328 break;
1329 case X86::BI__builtin_ia32_sha1rnds4:
1330 i = 2;
1331 l = 0;
1332 u = 3;
1333 break;
Craig Topper1a8b0472015-01-31 08:57:52 +00001334 case X86::BI__builtin_ia32_vpermil2pd:
1335 case X86::BI__builtin_ia32_vpermil2pd256:
1336 case X86::BI__builtin_ia32_vpermil2ps:
Richard Trieucc3949d2016-02-18 22:34:54 +00001337 case X86::BI__builtin_ia32_vpermil2ps256:
1338 i = 3;
1339 l = 0;
1340 u = 3;
1341 break;
Craig Topper95b0d732015-01-25 23:30:05 +00001342 case X86::BI__builtin_ia32_cmpb128_mask:
1343 case X86::BI__builtin_ia32_cmpw128_mask:
1344 case X86::BI__builtin_ia32_cmpd128_mask:
1345 case X86::BI__builtin_ia32_cmpq128_mask:
1346 case X86::BI__builtin_ia32_cmpb256_mask:
1347 case X86::BI__builtin_ia32_cmpw256_mask:
1348 case X86::BI__builtin_ia32_cmpd256_mask:
1349 case X86::BI__builtin_ia32_cmpq256_mask:
1350 case X86::BI__builtin_ia32_cmpb512_mask:
1351 case X86::BI__builtin_ia32_cmpw512_mask:
1352 case X86::BI__builtin_ia32_cmpd512_mask:
1353 case X86::BI__builtin_ia32_cmpq512_mask:
1354 case X86::BI__builtin_ia32_ucmpb128_mask:
1355 case X86::BI__builtin_ia32_ucmpw128_mask:
1356 case X86::BI__builtin_ia32_ucmpd128_mask:
1357 case X86::BI__builtin_ia32_ucmpq128_mask:
1358 case X86::BI__builtin_ia32_ucmpb256_mask:
1359 case X86::BI__builtin_ia32_ucmpw256_mask:
1360 case X86::BI__builtin_ia32_ucmpd256_mask:
1361 case X86::BI__builtin_ia32_ucmpq256_mask:
1362 case X86::BI__builtin_ia32_ucmpb512_mask:
1363 case X86::BI__builtin_ia32_ucmpw512_mask:
1364 case X86::BI__builtin_ia32_ucmpd512_mask:
Richard Trieucc3949d2016-02-18 22:34:54 +00001365 case X86::BI__builtin_ia32_ucmpq512_mask:
1366 i = 2;
1367 l = 0;
1368 u = 7;
1369 break;
Craig Topper16015252015-01-31 06:31:23 +00001370 case X86::BI__builtin_ia32_roundps:
1371 case X86::BI__builtin_ia32_roundpd:
1372 case X86::BI__builtin_ia32_roundps256:
Richard Trieucc3949d2016-02-18 22:34:54 +00001373 case X86::BI__builtin_ia32_roundpd256:
1374 i = 1;
1375 l = 0;
1376 u = 15;
1377 break;
Craig Topper16015252015-01-31 06:31:23 +00001378 case X86::BI__builtin_ia32_roundss:
Richard Trieucc3949d2016-02-18 22:34:54 +00001379 case X86::BI__builtin_ia32_roundsd:
1380 i = 2;
1381 l = 0;
1382 u = 15;
1383 break;
Craig Topper16015252015-01-31 06:31:23 +00001384 case X86::BI__builtin_ia32_cmpps:
1385 case X86::BI__builtin_ia32_cmpss:
1386 case X86::BI__builtin_ia32_cmppd:
1387 case X86::BI__builtin_ia32_cmpsd:
1388 case X86::BI__builtin_ia32_cmpps256:
1389 case X86::BI__builtin_ia32_cmppd256:
1390 case X86::BI__builtin_ia32_cmpps512_mask:
Richard Trieucc3949d2016-02-18 22:34:54 +00001391 case X86::BI__builtin_ia32_cmppd512_mask:
1392 i = 2;
1393 l = 0;
1394 u = 31;
1395 break;
Craig Topper8dd7d0d2015-02-13 06:04:48 +00001396 case X86::BI__builtin_ia32_vpcomub:
1397 case X86::BI__builtin_ia32_vpcomuw:
1398 case X86::BI__builtin_ia32_vpcomud:
1399 case X86::BI__builtin_ia32_vpcomuq:
1400 case X86::BI__builtin_ia32_vpcomb:
1401 case X86::BI__builtin_ia32_vpcomw:
1402 case X86::BI__builtin_ia32_vpcomd:
Richard Trieucc3949d2016-02-18 22:34:54 +00001403 case X86::BI__builtin_ia32_vpcomq:
1404 i = 2;
1405 l = 0;
1406 u = 7;
1407 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001408 }
Craig Topperdd84ec52014-12-27 07:00:08 +00001409 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001410}
1411
Richard Smith55ce3522012-06-25 20:30:08 +00001412/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
1413/// parameter with the FormatAttr's correct format_idx and firstDataArg.
1414/// Returns true when the format fits the function and the FormatStringInfo has
1415/// been populated.
1416bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
1417 FormatStringInfo *FSI) {
1418 FSI->HasVAListArg = Format->getFirstArg() == 0;
1419 FSI->FormatIdx = Format->getFormatIdx() - 1;
1420 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001421
Richard Smith55ce3522012-06-25 20:30:08 +00001422 // The way the format attribute works in GCC, the implicit this argument
1423 // of member functions is counted. However, it doesn't appear in our own
1424 // lists, so decrement format_idx in that case.
1425 if (IsCXXMember) {
1426 if(FSI->FormatIdx == 0)
1427 return false;
1428 --FSI->FormatIdx;
1429 if (FSI->FirstDataArg != 0)
1430 --FSI->FirstDataArg;
1431 }
1432 return true;
1433}
Mike Stump11289f42009-09-09 15:08:12 +00001434
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001435/// Checks if a the given expression evaluates to null.
1436///
1437/// \brief Returns true if the value evaluates to null.
George Burgess IV850269a2015-12-08 22:02:00 +00001438static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00001439 // If the expression has non-null type, it doesn't evaluate to null.
1440 if (auto nullability
1441 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
1442 if (*nullability == NullabilityKind::NonNull)
1443 return false;
1444 }
1445
Ted Kremeneka146db32014-01-17 06:24:47 +00001446 // As a special case, transparent unions initialized with zero are
1447 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001448 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +00001449 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
1450 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001451 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +00001452 if (const InitListExpr *ILE =
1453 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001454 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +00001455 }
1456
1457 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +00001458 return (!Expr->isValueDependent() &&
1459 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
1460 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001461}
1462
1463static void CheckNonNullArgument(Sema &S,
1464 const Expr *ArgExpr,
1465 SourceLocation CallSiteLoc) {
1466 if (CheckNonNullExpr(S, ArgExpr))
Eric Fiselier18677d52015-10-09 00:17:57 +00001467 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
1468 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
Ted Kremeneka146db32014-01-17 06:24:47 +00001469}
1470
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001471bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
1472 FormatStringInfo FSI;
1473 if ((GetFormatStringType(Format) == FST_NSString) &&
1474 getFormatStringInfo(Format, false, &FSI)) {
1475 Idx = FSI.FormatIdx;
1476 return true;
1477 }
1478 return false;
1479}
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001480/// \brief Diagnose use of %s directive in an NSString which is being passed
1481/// as formatting string to formatting method.
1482static void
1483DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
1484 const NamedDecl *FDecl,
1485 Expr **Args,
1486 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001487 unsigned Idx = 0;
1488 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001489 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
1490 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001491 Idx = 2;
1492 Format = true;
1493 }
1494 else
1495 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
1496 if (S.GetFormatNSStringIdx(I, Idx)) {
1497 Format = true;
1498 break;
1499 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001500 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001501 if (!Format || NumArgs <= Idx)
1502 return;
1503 const Expr *FormatExpr = Args[Idx];
1504 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
1505 FormatExpr = CSCE->getSubExpr();
1506 const StringLiteral *FormatString;
1507 if (const ObjCStringLiteral *OSL =
1508 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
1509 FormatString = OSL->getString();
1510 else
1511 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
1512 if (!FormatString)
1513 return;
1514 if (S.FormatStringHasSArg(FormatString)) {
1515 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
1516 << "%s" << 1 << 1;
1517 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
1518 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001519 }
1520}
1521
Douglas Gregorb4866e82015-06-19 18:13:19 +00001522/// Determine whether the given type has a non-null nullability annotation.
1523static bool isNonNullType(ASTContext &ctx, QualType type) {
1524 if (auto nullability = type->getNullability(ctx))
1525 return *nullability == NullabilityKind::NonNull;
1526
1527 return false;
1528}
1529
Ted Kremenek2bc73332014-01-17 06:24:43 +00001530static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00001531 const NamedDecl *FDecl,
Douglas Gregorb4866e82015-06-19 18:13:19 +00001532 const FunctionProtoType *Proto,
Richard Smith588bd9b2014-08-27 04:59:42 +00001533 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00001534 SourceLocation CallSiteLoc) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00001535 assert((FDecl || Proto) && "Need a function declaration or prototype");
1536
Ted Kremenek9aedc152014-01-17 06:24:56 +00001537 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00001538 llvm::SmallBitVector NonNullArgs;
Douglas Gregorb4866e82015-06-19 18:13:19 +00001539 if (FDecl) {
1540 // Handle the nonnull attribute on the function/method declaration itself.
1541 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
1542 if (!NonNull->args_size()) {
1543 // Easy case: all pointer arguments are nonnull.
1544 for (const auto *Arg : Args)
1545 if (S.isValidPointerAttrType(Arg->getType()))
1546 CheckNonNullArgument(S, Arg, CallSiteLoc);
1547 return;
1548 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001549
Douglas Gregorb4866e82015-06-19 18:13:19 +00001550 for (unsigned Val : NonNull->args()) {
1551 if (Val >= Args.size())
1552 continue;
1553 if (NonNullArgs.empty())
1554 NonNullArgs.resize(Args.size());
1555 NonNullArgs.set(Val);
1556 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001557 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00001558 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00001559
Douglas Gregorb4866e82015-06-19 18:13:19 +00001560 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
1561 // Handle the nonnull attribute on the parameters of the
1562 // function/method.
1563 ArrayRef<ParmVarDecl*> parms;
1564 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
1565 parms = FD->parameters();
1566 else
1567 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
1568
1569 unsigned ParamIndex = 0;
1570 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
1571 I != E; ++I, ++ParamIndex) {
1572 const ParmVarDecl *PVD = *I;
1573 if (PVD->hasAttr<NonNullAttr>() ||
1574 isNonNullType(S.Context, PVD->getType())) {
1575 if (NonNullArgs.empty())
1576 NonNullArgs.resize(Args.size());
Ted Kremenek9aedc152014-01-17 06:24:56 +00001577
Douglas Gregorb4866e82015-06-19 18:13:19 +00001578 NonNullArgs.set(ParamIndex);
1579 }
1580 }
1581 } else {
1582 // If we have a non-function, non-method declaration but no
1583 // function prototype, try to dig out the function prototype.
1584 if (!Proto) {
1585 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
1586 QualType type = VD->getType().getNonReferenceType();
1587 if (auto pointerType = type->getAs<PointerType>())
1588 type = pointerType->getPointeeType();
1589 else if (auto blockType = type->getAs<BlockPointerType>())
1590 type = blockType->getPointeeType();
1591 // FIXME: data member pointers?
1592
1593 // Dig out the function prototype, if there is one.
1594 Proto = type->getAs<FunctionProtoType>();
1595 }
1596 }
1597
1598 // Fill in non-null argument information from the nullability
1599 // information on the parameter types (if we have them).
1600 if (Proto) {
1601 unsigned Index = 0;
1602 for (auto paramType : Proto->getParamTypes()) {
1603 if (isNonNullType(S.Context, paramType)) {
1604 if (NonNullArgs.empty())
1605 NonNullArgs.resize(Args.size());
1606
1607 NonNullArgs.set(Index);
1608 }
1609
1610 ++Index;
1611 }
1612 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00001613 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001614
Douglas Gregorb4866e82015-06-19 18:13:19 +00001615 // Check for non-null arguments.
1616 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
1617 ArgIndex != ArgIndexEnd; ++ArgIndex) {
Richard Smith588bd9b2014-08-27 04:59:42 +00001618 if (NonNullArgs[ArgIndex])
1619 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00001620 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00001621}
1622
Richard Smith55ce3522012-06-25 20:30:08 +00001623/// Handles the checks for format strings, non-POD arguments to vararg
1624/// functions, and NULL arguments passed to non-NULL parameters.
Douglas Gregorb4866e82015-06-19 18:13:19 +00001625void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
1626 ArrayRef<const Expr *> Args, bool IsMemberFunction,
Alp Toker9cacbab2014-01-20 20:26:09 +00001627 SourceLocation Loc, SourceRange Range,
Richard Smith55ce3522012-06-25 20:30:08 +00001628 VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00001629 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00001630 if (CurContext->isDependentContext())
1631 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001632
Ted Kremenekb8176da2010-09-09 04:33:05 +00001633 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00001634 llvm::SmallBitVector CheckedVarArgs;
1635 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001636 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00001637 // Only create vector if there are format attributes.
1638 CheckedVarArgs.resize(Args.size());
1639
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001640 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00001641 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00001642 }
Richard Smithd7293d72013-08-05 18:49:43 +00001643 }
Richard Smith55ce3522012-06-25 20:30:08 +00001644
1645 // Refuse POD arguments that weren't caught by the format string
1646 // checks above.
Richard Smithd7293d72013-08-05 18:49:43 +00001647 if (CallType != VariadicDoesNotApply) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00001648 unsigned NumParams = Proto ? Proto->getNumParams()
1649 : FDecl && isa<FunctionDecl>(FDecl)
1650 ? cast<FunctionDecl>(FDecl)->getNumParams()
1651 : FDecl && isa<ObjCMethodDecl>(FDecl)
1652 ? cast<ObjCMethodDecl>(FDecl)->param_size()
1653 : 0;
1654
Alp Toker9cacbab2014-01-20 20:26:09 +00001655 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00001656 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00001657 if (const Expr *Arg = Args[ArgIdx]) {
1658 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
1659 checkVariadicArgument(Arg, CallType);
1660 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00001661 }
Richard Smithd7293d72013-08-05 18:49:43 +00001662 }
Mike Stump11289f42009-09-09 15:08:12 +00001663
Douglas Gregorb4866e82015-06-19 18:13:19 +00001664 if (FDecl || Proto) {
1665 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001666
Richard Trieu41bc0992013-06-22 00:20:41 +00001667 // Type safety checking.
Douglas Gregorb4866e82015-06-19 18:13:19 +00001668 if (FDecl) {
1669 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
1670 CheckArgumentWithTypeTag(I, Args.data());
1671 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001672 }
Richard Smith55ce3522012-06-25 20:30:08 +00001673}
1674
1675/// CheckConstructorCall - Check a constructor call for correctness and safety
1676/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00001677void Sema::CheckConstructorCall(FunctionDecl *FDecl,
1678 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00001679 const FunctionProtoType *Proto,
1680 SourceLocation Loc) {
1681 VariadicCallType CallType =
1682 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Douglas Gregorb4866e82015-06-19 18:13:19 +00001683 checkCall(FDecl, Proto, Args, /*IsMemberFunction=*/true, Loc, SourceRange(),
1684 CallType);
Richard Smith55ce3522012-06-25 20:30:08 +00001685}
1686
1687/// CheckFunctionCall - Check a direct function call for various correctness
1688/// and safety properties not strictly enforced by the C type system.
1689bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
1690 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00001691 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
1692 isa<CXXMethodDecl>(FDecl);
1693 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
1694 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00001695 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
1696 TheCall->getCallee());
Eli Friedman726d11c2012-10-11 00:30:58 +00001697 Expr** Args = TheCall->getArgs();
1698 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmanadf42182012-10-11 00:34:15 +00001699 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00001700 // If this is a call to a member operator, hide the first argument
1701 // from checkCall.
1702 // FIXME: Our choice of AST representation here is less than ideal.
1703 ++Args;
1704 --NumArgs;
1705 }
Douglas Gregorb4866e82015-06-19 18:13:19 +00001706 checkCall(FDecl, Proto, llvm::makeArrayRef(Args, NumArgs),
Richard Smith55ce3522012-06-25 20:30:08 +00001707 IsMemberFunction, TheCall->getRParenLoc(),
1708 TheCall->getCallee()->getSourceRange(), CallType);
1709
1710 IdentifierInfo *FnInfo = FDecl->getIdentifier();
1711 // None of the checks below are needed for functions that don't have
1712 // simple names (e.g., C++ conversion functions).
1713 if (!FnInfo)
1714 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001715
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00001716 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001717 if (getLangOpts().ObjC1)
1718 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00001719
Anna Zaks22122702012-01-17 00:37:07 +00001720 unsigned CMId = FDecl->getMemoryFunctionKind();
1721 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00001722 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00001723
Anna Zaks201d4892012-01-13 21:52:01 +00001724 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00001725 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00001726 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00001727 else if (CMId == Builtin::BIstrncat)
1728 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00001729 else
Anna Zaks22122702012-01-17 00:37:07 +00001730 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00001731
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001732 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00001733}
1734
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001735bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00001736 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00001737 VariadicCallType CallType =
1738 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001739
Douglas Gregorb4866e82015-06-19 18:13:19 +00001740 checkCall(Method, nullptr, Args,
1741 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
1742 CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001743
1744 return false;
1745}
1746
Richard Trieu664c4c62013-06-20 21:03:13 +00001747bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
1748 const FunctionProtoType *Proto) {
Aaron Ballmanb673c652015-04-23 16:14:19 +00001749 QualType Ty;
1750 if (const auto *V = dyn_cast<VarDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00001751 Ty = V->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00001752 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00001753 Ty = F->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00001754 else
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001755 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001756
Douglas Gregorb4866e82015-06-19 18:13:19 +00001757 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
1758 !Ty->isFunctionProtoType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001759 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001760
Richard Trieu664c4c62013-06-20 21:03:13 +00001761 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00001762 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00001763 CallType = VariadicDoesNotApply;
1764 } else if (Ty->isBlockPointerType()) {
1765 CallType = VariadicBlock;
1766 } else { // Ty->isFunctionPointerType()
1767 CallType = VariadicFunction;
1768 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001769
Douglas Gregorb4866e82015-06-19 18:13:19 +00001770 checkCall(NDecl, Proto,
1771 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
1772 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00001773 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00001774
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001775 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00001776}
1777
Richard Trieu41bc0992013-06-22 00:20:41 +00001778/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
1779/// such as function pointers returned from functions.
1780bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001781 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00001782 TheCall->getCallee());
Douglas Gregorb4866e82015-06-19 18:13:19 +00001783 checkCall(/*FDecl=*/nullptr, Proto,
Craig Topper8c2a2a02014-08-30 16:55:39 +00001784 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Douglas Gregorb4866e82015-06-19 18:13:19 +00001785 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00001786 TheCall->getCallee()->getSourceRange(), CallType);
1787
1788 return false;
1789}
1790
Tim Northovere94a34c2014-03-11 10:49:14 +00001791static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
1792 if (Ordering < AtomicExpr::AO_ABI_memory_order_relaxed ||
1793 Ordering > AtomicExpr::AO_ABI_memory_order_seq_cst)
1794 return false;
1795
1796 switch (Op) {
1797 case AtomicExpr::AO__c11_atomic_init:
1798 llvm_unreachable("There is no ordering argument for an init");
1799
1800 case AtomicExpr::AO__c11_atomic_load:
1801 case AtomicExpr::AO__atomic_load_n:
1802 case AtomicExpr::AO__atomic_load:
1803 return Ordering != AtomicExpr::AO_ABI_memory_order_release &&
1804 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1805
1806 case AtomicExpr::AO__c11_atomic_store:
1807 case AtomicExpr::AO__atomic_store:
1808 case AtomicExpr::AO__atomic_store_n:
1809 return Ordering != AtomicExpr::AO_ABI_memory_order_consume &&
1810 Ordering != AtomicExpr::AO_ABI_memory_order_acquire &&
1811 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1812
1813 default:
1814 return true;
1815 }
1816}
1817
Richard Smithfeea8832012-04-12 05:08:17 +00001818ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
1819 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001820 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
1821 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001822
Richard Smithfeea8832012-04-12 05:08:17 +00001823 // All these operations take one of the following forms:
1824 enum {
1825 // C __c11_atomic_init(A *, C)
1826 Init,
1827 // C __c11_atomic_load(A *, int)
1828 Load,
1829 // void __atomic_load(A *, CP, int)
1830 Copy,
1831 // C __c11_atomic_add(A *, M, int)
1832 Arithmetic,
1833 // C __atomic_exchange_n(A *, CP, int)
1834 Xchg,
1835 // void __atomic_exchange(A *, C *, CP, int)
1836 GNUXchg,
1837 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
1838 C11CmpXchg,
1839 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
1840 GNUCmpXchg
1841 } Form = Init;
1842 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
1843 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
1844 // where:
1845 // C is an appropriate type,
1846 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
1847 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
1848 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
1849 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001850
Gabor Horvath98bd0982015-03-16 09:59:54 +00001851 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
1852 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
1853 AtomicExpr::AO__atomic_load,
1854 "need to update code for modified C11 atomics");
Richard Smithfeea8832012-04-12 05:08:17 +00001855 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
1856 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
1857 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
1858 Op == AtomicExpr::AO__atomic_store_n ||
1859 Op == AtomicExpr::AO__atomic_exchange_n ||
1860 Op == AtomicExpr::AO__atomic_compare_exchange_n;
1861 bool IsAddSub = false;
1862
1863 switch (Op) {
1864 case AtomicExpr::AO__c11_atomic_init:
1865 Form = Init;
1866 break;
1867
1868 case AtomicExpr::AO__c11_atomic_load:
1869 case AtomicExpr::AO__atomic_load_n:
1870 Form = Load;
1871 break;
1872
1873 case AtomicExpr::AO__c11_atomic_store:
1874 case AtomicExpr::AO__atomic_load:
1875 case AtomicExpr::AO__atomic_store:
1876 case AtomicExpr::AO__atomic_store_n:
1877 Form = Copy;
1878 break;
1879
1880 case AtomicExpr::AO__c11_atomic_fetch_add:
1881 case AtomicExpr::AO__c11_atomic_fetch_sub:
1882 case AtomicExpr::AO__atomic_fetch_add:
1883 case AtomicExpr::AO__atomic_fetch_sub:
1884 case AtomicExpr::AO__atomic_add_fetch:
1885 case AtomicExpr::AO__atomic_sub_fetch:
1886 IsAddSub = true;
1887 // Fall through.
1888 case AtomicExpr::AO__c11_atomic_fetch_and:
1889 case AtomicExpr::AO__c11_atomic_fetch_or:
1890 case AtomicExpr::AO__c11_atomic_fetch_xor:
1891 case AtomicExpr::AO__atomic_fetch_and:
1892 case AtomicExpr::AO__atomic_fetch_or:
1893 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00001894 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00001895 case AtomicExpr::AO__atomic_and_fetch:
1896 case AtomicExpr::AO__atomic_or_fetch:
1897 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00001898 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00001899 Form = Arithmetic;
1900 break;
1901
1902 case AtomicExpr::AO__c11_atomic_exchange:
1903 case AtomicExpr::AO__atomic_exchange_n:
1904 Form = Xchg;
1905 break;
1906
1907 case AtomicExpr::AO__atomic_exchange:
1908 Form = GNUXchg;
1909 break;
1910
1911 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1912 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1913 Form = C11CmpXchg;
1914 break;
1915
1916 case AtomicExpr::AO__atomic_compare_exchange:
1917 case AtomicExpr::AO__atomic_compare_exchange_n:
1918 Form = GNUCmpXchg;
1919 break;
1920 }
1921
1922 // Check we have the right number of arguments.
1923 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001924 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001925 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001926 << TheCall->getCallee()->getSourceRange();
1927 return ExprError();
Richard Smithfeea8832012-04-12 05:08:17 +00001928 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
1929 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001930 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001931 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001932 << TheCall->getCallee()->getSourceRange();
1933 return ExprError();
1934 }
1935
Richard Smithfeea8832012-04-12 05:08:17 +00001936 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001937 Expr *Ptr = TheCall->getArg(0);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001938 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1939 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1940 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00001941 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001942 << Ptr->getType() << Ptr->getSourceRange();
1943 return ExprError();
1944 }
1945
Richard Smithfeea8832012-04-12 05:08:17 +00001946 // For a __c11 builtin, this should be a pointer to an _Atomic type.
1947 QualType AtomTy = pointerType->getPointeeType(); // 'A'
1948 QualType ValType = AtomTy; // 'C'
1949 if (IsC11) {
1950 if (!AtomTy->isAtomicType()) {
1951 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1952 << Ptr->getType() << Ptr->getSourceRange();
1953 return ExprError();
1954 }
Richard Smithe00921a2012-09-15 06:09:58 +00001955 if (AtomTy.isConstQualified()) {
1956 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1957 << Ptr->getType() << Ptr->getSourceRange();
1958 return ExprError();
1959 }
Richard Smithfeea8832012-04-12 05:08:17 +00001960 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eric Fiseliera3a7c562015-10-04 00:11:02 +00001961 } else if (Form != Load && Op != AtomicExpr::AO__atomic_load) {
1962 if (ValType.isConstQualified()) {
1963 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
1964 << Ptr->getType() << Ptr->getSourceRange();
1965 return ExprError();
1966 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001967 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001968
Richard Smithfeea8832012-04-12 05:08:17 +00001969 // For an arithmetic operation, the implied arithmetic must be well-formed.
1970 if (Form == Arithmetic) {
1971 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1972 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1973 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1974 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1975 return ExprError();
1976 }
1977 if (!IsAddSub && !ValType->isIntegerType()) {
1978 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1979 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1980 return ExprError();
1981 }
David Majnemere85cff82015-01-28 05:48:06 +00001982 if (IsC11 && ValType->isPointerType() &&
1983 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
1984 diag::err_incomplete_type)) {
1985 return ExprError();
1986 }
Richard Smithfeea8832012-04-12 05:08:17 +00001987 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1988 // For __atomic_*_n operations, the value type must be a scalar integral or
1989 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001990 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00001991 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1992 return ExprError();
1993 }
1994
Eli Friedmanaa769812013-09-11 03:49:34 +00001995 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1996 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00001997 // For GNU atomics, require a trivially-copyable type. This is not part of
1998 // the GNU atomics specification, but we enforce it for sanity.
1999 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002000 << Ptr->getType() << Ptr->getSourceRange();
2001 return ExprError();
2002 }
2003
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002004 switch (ValType.getObjCLifetime()) {
2005 case Qualifiers::OCL_None:
2006 case Qualifiers::OCL_ExplicitNone:
2007 // okay
2008 break;
2009
2010 case Qualifiers::OCL_Weak:
2011 case Qualifiers::OCL_Strong:
2012 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00002013 // FIXME: Can this happen? By this point, ValType should be known
2014 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002015 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
2016 << ValType << Ptr->getSourceRange();
2017 return ExprError();
2018 }
2019
David Majnemerc6eb6502015-06-03 00:26:35 +00002020 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the
2021 // volatile-ness of the pointee-type inject itself into the result or the
2022 // other operands.
2023 ValType.removeLocalVolatile();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002024 QualType ResultType = ValType;
Richard Smithfeea8832012-04-12 05:08:17 +00002025 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002026 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00002027 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002028 ResultType = Context.BoolTy;
2029
Richard Smithfeea8832012-04-12 05:08:17 +00002030 // The type of a parameter passed 'by value'. In the GNU atomics, such
2031 // arguments are actually passed as pointers.
2032 QualType ByValType = ValType; // 'CP'
2033 if (!IsC11 && !IsN)
2034 ByValType = Ptr->getType();
2035
Eric Fiseliera3a7c562015-10-04 00:11:02 +00002036 // FIXME: __atomic_load allows the first argument to be a a pointer to const
2037 // but not the second argument. We need to manually remove possible const
2038 // qualifiers.
2039
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002040 // The first argument --- the pointer --- has a fixed type; we
2041 // deduce the types of the rest of the arguments accordingly. Walk
2042 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00002043 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002044 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00002045 if (i < NumVals[Form] + 1) {
2046 switch (i) {
2047 case 1:
2048 // The second argument is the non-atomic operand. For arithmetic, this
2049 // is always passed by value, and for a compare_exchange it is always
2050 // passed by address. For the rest, GNU uses by-address and C11 uses
2051 // by-value.
2052 assert(Form != Load);
2053 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
2054 Ty = ValType;
2055 else if (Form == Copy || Form == Xchg)
2056 Ty = ByValType;
2057 else if (Form == Arithmetic)
2058 Ty = Context.getPointerDiffType();
Anastasia Stulova76fd1052015-12-22 15:14:54 +00002059 else {
2060 Expr *ValArg = TheCall->getArg(i);
2061 unsigned AS = 0;
2062 // Keep address space of non-atomic pointer type.
2063 if (const PointerType *PtrTy =
2064 ValArg->getType()->getAs<PointerType>()) {
2065 AS = PtrTy->getPointeeType().getAddressSpace();
2066 }
2067 Ty = Context.getPointerType(
2068 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
2069 }
Richard Smithfeea8832012-04-12 05:08:17 +00002070 break;
2071 case 2:
2072 // The third argument to compare_exchange / GNU exchange is a
2073 // (pointer to a) desired value.
2074 Ty = ByValType;
2075 break;
2076 case 3:
2077 // The fourth argument to GNU compare_exchange is a 'weak' flag.
2078 Ty = Context.BoolTy;
2079 break;
2080 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002081 } else {
2082 // The order(s) are always converted to int.
2083 Ty = Context.IntTy;
2084 }
Richard Smithfeea8832012-04-12 05:08:17 +00002085
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002086 InitializedEntity Entity =
2087 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00002088 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002089 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2090 if (Arg.isInvalid())
2091 return true;
2092 TheCall->setArg(i, Arg.get());
2093 }
2094
Richard Smithfeea8832012-04-12 05:08:17 +00002095 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002096 SmallVector<Expr*, 5> SubExprs;
2097 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00002098 switch (Form) {
2099 case Init:
2100 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00002101 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00002102 break;
2103 case Load:
2104 SubExprs.push_back(TheCall->getArg(1)); // Order
2105 break;
2106 case Copy:
2107 case Arithmetic:
2108 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002109 SubExprs.push_back(TheCall->getArg(2)); // Order
2110 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00002111 break;
2112 case GNUXchg:
2113 // Note, AtomicExpr::getVal2() has a special case for this atomic.
2114 SubExprs.push_back(TheCall->getArg(3)); // Order
2115 SubExprs.push_back(TheCall->getArg(1)); // Val1
2116 SubExprs.push_back(TheCall->getArg(2)); // Val2
2117 break;
2118 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002119 SubExprs.push_back(TheCall->getArg(3)); // Order
2120 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002121 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00002122 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00002123 break;
2124 case GNUCmpXchg:
2125 SubExprs.push_back(TheCall->getArg(4)); // Order
2126 SubExprs.push_back(TheCall->getArg(1)); // Val1
2127 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
2128 SubExprs.push_back(TheCall->getArg(2)); // Val2
2129 SubExprs.push_back(TheCall->getArg(3)); // Weak
2130 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002131 }
Tim Northovere94a34c2014-03-11 10:49:14 +00002132
2133 if (SubExprs.size() >= 2 && Form != Init) {
2134 llvm::APSInt Result(32);
2135 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
2136 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00002137 Diag(SubExprs[1]->getLocStart(),
2138 diag::warn_atomic_op_has_invalid_memory_order)
2139 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00002140 }
2141
Fariborz Jahanian615de762013-05-28 17:37:39 +00002142 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
2143 SubExprs, ResultType, Op,
2144 TheCall->getRParenLoc());
2145
2146 if ((Op == AtomicExpr::AO__c11_atomic_load ||
2147 (Op == AtomicExpr::AO__c11_atomic_store)) &&
2148 Context.AtomicUsesUnsupportedLibcall(AE))
2149 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
2150 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002151
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002152 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002153}
2154
John McCall29ad95b2011-08-27 01:09:30 +00002155/// checkBuiltinArgument - Given a call to a builtin function, perform
2156/// normal type-checking on the given argument, updating the call in
2157/// place. This is useful when a builtin function requires custom
2158/// type-checking for some of its arguments but not necessarily all of
2159/// them.
2160///
2161/// Returns true on error.
2162static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
2163 FunctionDecl *Fn = E->getDirectCallee();
2164 assert(Fn && "builtin call without direct callee!");
2165
2166 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
2167 InitializedEntity Entity =
2168 InitializedEntity::InitializeParameter(S.Context, Param);
2169
2170 ExprResult Arg = E->getArg(0);
2171 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
2172 if (Arg.isInvalid())
2173 return true;
2174
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002175 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00002176 return false;
2177}
2178
Chris Lattnerdc046542009-05-08 06:58:22 +00002179/// SemaBuiltinAtomicOverloaded - We have a call to a function like
2180/// __sync_fetch_and_add, which is an overloaded function based on the pointer
2181/// type of its first argument. The main ActOnCallExpr routines have already
2182/// promoted the types of arguments because all of these calls are prototyped as
2183/// void(...).
2184///
2185/// This function goes through and does final semantic checking for these
2186/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00002187ExprResult
2188Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002189 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00002190 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2191 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2192
2193 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002194 if (TheCall->getNumArgs() < 1) {
2195 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
2196 << 0 << 1 << TheCall->getNumArgs()
2197 << TheCall->getCallee()->getSourceRange();
2198 return ExprError();
2199 }
Mike Stump11289f42009-09-09 15:08:12 +00002200
Chris Lattnerdc046542009-05-08 06:58:22 +00002201 // Inspect the first argument of the atomic builtin. This should always be
2202 // a pointer type, whose element is an integral scalar or pointer type.
2203 // Because it is a pointer type, we don't have to worry about any implicit
2204 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002205 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00002206 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00002207 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
2208 if (FirstArgResult.isInvalid())
2209 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002210 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00002211 TheCall->setArg(0, FirstArg);
2212
John McCall31168b02011-06-15 23:02:42 +00002213 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
2214 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002215 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
2216 << FirstArg->getType() << FirstArg->getSourceRange();
2217 return ExprError();
2218 }
Mike Stump11289f42009-09-09 15:08:12 +00002219
John McCall31168b02011-06-15 23:02:42 +00002220 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00002221 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002222 !ValType->isBlockPointerType()) {
2223 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
2224 << FirstArg->getType() << FirstArg->getSourceRange();
2225 return ExprError();
2226 }
Chris Lattnerdc046542009-05-08 06:58:22 +00002227
John McCall31168b02011-06-15 23:02:42 +00002228 switch (ValType.getObjCLifetime()) {
2229 case Qualifiers::OCL_None:
2230 case Qualifiers::OCL_ExplicitNone:
2231 // okay
2232 break;
2233
2234 case Qualifiers::OCL_Weak:
2235 case Qualifiers::OCL_Strong:
2236 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00002237 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00002238 << ValType << FirstArg->getSourceRange();
2239 return ExprError();
2240 }
2241
John McCallb50451a2011-10-05 07:41:44 +00002242 // Strip any qualifiers off ValType.
2243 ValType = ValType.getUnqualifiedType();
2244
Chandler Carruth3973af72010-07-18 20:54:12 +00002245 // The majority of builtins return a value, but a few have special return
2246 // types, so allow them to override appropriately below.
2247 QualType ResultType = ValType;
2248
Chris Lattnerdc046542009-05-08 06:58:22 +00002249 // We need to figure out which concrete builtin this maps onto. For example,
2250 // __sync_fetch_and_add with a 2 byte object turns into
2251 // __sync_fetch_and_add_2.
2252#define BUILTIN_ROW(x) \
2253 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
2254 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00002255
Chris Lattnerdc046542009-05-08 06:58:22 +00002256 static const unsigned BuiltinIndices[][5] = {
2257 BUILTIN_ROW(__sync_fetch_and_add),
2258 BUILTIN_ROW(__sync_fetch_and_sub),
2259 BUILTIN_ROW(__sync_fetch_and_or),
2260 BUILTIN_ROW(__sync_fetch_and_and),
2261 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00002262 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00002263
Chris Lattnerdc046542009-05-08 06:58:22 +00002264 BUILTIN_ROW(__sync_add_and_fetch),
2265 BUILTIN_ROW(__sync_sub_and_fetch),
2266 BUILTIN_ROW(__sync_and_and_fetch),
2267 BUILTIN_ROW(__sync_or_and_fetch),
2268 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00002269 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00002270
Chris Lattnerdc046542009-05-08 06:58:22 +00002271 BUILTIN_ROW(__sync_val_compare_and_swap),
2272 BUILTIN_ROW(__sync_bool_compare_and_swap),
2273 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00002274 BUILTIN_ROW(__sync_lock_release),
2275 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00002276 };
Mike Stump11289f42009-09-09 15:08:12 +00002277#undef BUILTIN_ROW
2278
Chris Lattnerdc046542009-05-08 06:58:22 +00002279 // Determine the index of the size.
2280 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00002281 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00002282 case 1: SizeIndex = 0; break;
2283 case 2: SizeIndex = 1; break;
2284 case 4: SizeIndex = 2; break;
2285 case 8: SizeIndex = 3; break;
2286 case 16: SizeIndex = 4; break;
2287 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002288 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
2289 << FirstArg->getType() << FirstArg->getSourceRange();
2290 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00002291 }
Mike Stump11289f42009-09-09 15:08:12 +00002292
Chris Lattnerdc046542009-05-08 06:58:22 +00002293 // Each of these builtins has one pointer argument, followed by some number of
2294 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
2295 // that we ignore. Find out which row of BuiltinIndices to read from as well
2296 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00002297 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00002298 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00002299 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00002300 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00002301 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00002302 case Builtin::BI__sync_fetch_and_add:
2303 case Builtin::BI__sync_fetch_and_add_1:
2304 case Builtin::BI__sync_fetch_and_add_2:
2305 case Builtin::BI__sync_fetch_and_add_4:
2306 case Builtin::BI__sync_fetch_and_add_8:
2307 case Builtin::BI__sync_fetch_and_add_16:
2308 BuiltinIndex = 0;
2309 break;
2310
2311 case Builtin::BI__sync_fetch_and_sub:
2312 case Builtin::BI__sync_fetch_and_sub_1:
2313 case Builtin::BI__sync_fetch_and_sub_2:
2314 case Builtin::BI__sync_fetch_and_sub_4:
2315 case Builtin::BI__sync_fetch_and_sub_8:
2316 case Builtin::BI__sync_fetch_and_sub_16:
2317 BuiltinIndex = 1;
2318 break;
2319
2320 case Builtin::BI__sync_fetch_and_or:
2321 case Builtin::BI__sync_fetch_and_or_1:
2322 case Builtin::BI__sync_fetch_and_or_2:
2323 case Builtin::BI__sync_fetch_and_or_4:
2324 case Builtin::BI__sync_fetch_and_or_8:
2325 case Builtin::BI__sync_fetch_and_or_16:
2326 BuiltinIndex = 2;
2327 break;
2328
2329 case Builtin::BI__sync_fetch_and_and:
2330 case Builtin::BI__sync_fetch_and_and_1:
2331 case Builtin::BI__sync_fetch_and_and_2:
2332 case Builtin::BI__sync_fetch_and_and_4:
2333 case Builtin::BI__sync_fetch_and_and_8:
2334 case Builtin::BI__sync_fetch_and_and_16:
2335 BuiltinIndex = 3;
2336 break;
Mike Stump11289f42009-09-09 15:08:12 +00002337
Douglas Gregor73722482011-11-28 16:30:08 +00002338 case Builtin::BI__sync_fetch_and_xor:
2339 case Builtin::BI__sync_fetch_and_xor_1:
2340 case Builtin::BI__sync_fetch_and_xor_2:
2341 case Builtin::BI__sync_fetch_and_xor_4:
2342 case Builtin::BI__sync_fetch_and_xor_8:
2343 case Builtin::BI__sync_fetch_and_xor_16:
2344 BuiltinIndex = 4;
2345 break;
2346
Hal Finkeld2208b52014-10-02 20:53:50 +00002347 case Builtin::BI__sync_fetch_and_nand:
2348 case Builtin::BI__sync_fetch_and_nand_1:
2349 case Builtin::BI__sync_fetch_and_nand_2:
2350 case Builtin::BI__sync_fetch_and_nand_4:
2351 case Builtin::BI__sync_fetch_and_nand_8:
2352 case Builtin::BI__sync_fetch_and_nand_16:
2353 BuiltinIndex = 5;
2354 WarnAboutSemanticsChange = true;
2355 break;
2356
Douglas Gregor73722482011-11-28 16:30:08 +00002357 case Builtin::BI__sync_add_and_fetch:
2358 case Builtin::BI__sync_add_and_fetch_1:
2359 case Builtin::BI__sync_add_and_fetch_2:
2360 case Builtin::BI__sync_add_and_fetch_4:
2361 case Builtin::BI__sync_add_and_fetch_8:
2362 case Builtin::BI__sync_add_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002363 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00002364 break;
2365
2366 case Builtin::BI__sync_sub_and_fetch:
2367 case Builtin::BI__sync_sub_and_fetch_1:
2368 case Builtin::BI__sync_sub_and_fetch_2:
2369 case Builtin::BI__sync_sub_and_fetch_4:
2370 case Builtin::BI__sync_sub_and_fetch_8:
2371 case Builtin::BI__sync_sub_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002372 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00002373 break;
2374
2375 case Builtin::BI__sync_and_and_fetch:
2376 case Builtin::BI__sync_and_and_fetch_1:
2377 case Builtin::BI__sync_and_and_fetch_2:
2378 case Builtin::BI__sync_and_and_fetch_4:
2379 case Builtin::BI__sync_and_and_fetch_8:
2380 case Builtin::BI__sync_and_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002381 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00002382 break;
2383
2384 case Builtin::BI__sync_or_and_fetch:
2385 case Builtin::BI__sync_or_and_fetch_1:
2386 case Builtin::BI__sync_or_and_fetch_2:
2387 case Builtin::BI__sync_or_and_fetch_4:
2388 case Builtin::BI__sync_or_and_fetch_8:
2389 case Builtin::BI__sync_or_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002390 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00002391 break;
2392
2393 case Builtin::BI__sync_xor_and_fetch:
2394 case Builtin::BI__sync_xor_and_fetch_1:
2395 case Builtin::BI__sync_xor_and_fetch_2:
2396 case Builtin::BI__sync_xor_and_fetch_4:
2397 case Builtin::BI__sync_xor_and_fetch_8:
2398 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002399 BuiltinIndex = 10;
2400 break;
2401
2402 case Builtin::BI__sync_nand_and_fetch:
2403 case Builtin::BI__sync_nand_and_fetch_1:
2404 case Builtin::BI__sync_nand_and_fetch_2:
2405 case Builtin::BI__sync_nand_and_fetch_4:
2406 case Builtin::BI__sync_nand_and_fetch_8:
2407 case Builtin::BI__sync_nand_and_fetch_16:
2408 BuiltinIndex = 11;
2409 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00002410 break;
Mike Stump11289f42009-09-09 15:08:12 +00002411
Chris Lattnerdc046542009-05-08 06:58:22 +00002412 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00002413 case Builtin::BI__sync_val_compare_and_swap_1:
2414 case Builtin::BI__sync_val_compare_and_swap_2:
2415 case Builtin::BI__sync_val_compare_and_swap_4:
2416 case Builtin::BI__sync_val_compare_and_swap_8:
2417 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002418 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00002419 NumFixed = 2;
2420 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002421
Chris Lattnerdc046542009-05-08 06:58:22 +00002422 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00002423 case Builtin::BI__sync_bool_compare_and_swap_1:
2424 case Builtin::BI__sync_bool_compare_and_swap_2:
2425 case Builtin::BI__sync_bool_compare_and_swap_4:
2426 case Builtin::BI__sync_bool_compare_and_swap_8:
2427 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002428 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00002429 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00002430 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00002431 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002432
2433 case Builtin::BI__sync_lock_test_and_set:
2434 case Builtin::BI__sync_lock_test_and_set_1:
2435 case Builtin::BI__sync_lock_test_and_set_2:
2436 case Builtin::BI__sync_lock_test_and_set_4:
2437 case Builtin::BI__sync_lock_test_and_set_8:
2438 case Builtin::BI__sync_lock_test_and_set_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002439 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00002440 break;
2441
Chris Lattnerdc046542009-05-08 06:58:22 +00002442 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00002443 case Builtin::BI__sync_lock_release_1:
2444 case Builtin::BI__sync_lock_release_2:
2445 case Builtin::BI__sync_lock_release_4:
2446 case Builtin::BI__sync_lock_release_8:
2447 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002448 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00002449 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00002450 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00002451 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002452
2453 case Builtin::BI__sync_swap:
2454 case Builtin::BI__sync_swap_1:
2455 case Builtin::BI__sync_swap_2:
2456 case Builtin::BI__sync_swap_4:
2457 case Builtin::BI__sync_swap_8:
2458 case Builtin::BI__sync_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002459 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00002460 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00002461 }
Mike Stump11289f42009-09-09 15:08:12 +00002462
Chris Lattnerdc046542009-05-08 06:58:22 +00002463 // Now that we know how many fixed arguments we expect, first check that we
2464 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002465 if (TheCall->getNumArgs() < 1+NumFixed) {
2466 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
2467 << 0 << 1+NumFixed << TheCall->getNumArgs()
2468 << TheCall->getCallee()->getSourceRange();
2469 return ExprError();
2470 }
Mike Stump11289f42009-09-09 15:08:12 +00002471
Hal Finkeld2208b52014-10-02 20:53:50 +00002472 if (WarnAboutSemanticsChange) {
2473 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
2474 << TheCall->getCallee()->getSourceRange();
2475 }
2476
Chris Lattner5b9241b2009-05-08 15:36:58 +00002477 // Get the decl for the concrete builtin from this, we can tell what the
2478 // concrete integer type we should convert to is.
2479 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
Eric Christopher02d5d862015-08-06 01:01:12 +00002480 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00002481 FunctionDecl *NewBuiltinDecl;
2482 if (NewBuiltinID == BuiltinID)
2483 NewBuiltinDecl = FDecl;
2484 else {
2485 // Perform builtin lookup to avoid redeclaring it.
2486 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
2487 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
2488 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
2489 assert(Res.getFoundDecl());
2490 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00002491 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00002492 return ExprError();
2493 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002494
John McCallcf142162010-08-07 06:22:56 +00002495 // The first argument --- the pointer --- has a fixed type; we
2496 // deduce the types of the rest of the arguments accordingly. Walk
2497 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00002498 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00002499 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00002500
Chris Lattnerdc046542009-05-08 06:58:22 +00002501 // GCC does an implicit conversion to the pointer or integer ValType. This
2502 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00002503 // Initialize the argument.
2504 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
2505 ValType, /*consume*/ false);
2506 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00002507 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002508 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002509
Chris Lattnerdc046542009-05-08 06:58:22 +00002510 // Okay, we have something that *can* be converted to the right type. Check
2511 // to see if there is a potentially weird extension going on here. This can
2512 // happen when you do an atomic operation on something like an char* and
2513 // pass in 42. The 42 gets converted to char. This is even more strange
2514 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00002515 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002516 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00002517 }
Mike Stump11289f42009-09-09 15:08:12 +00002518
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002519 ASTContext& Context = this->getASTContext();
2520
2521 // Create a new DeclRefExpr to refer to the new decl.
2522 DeclRefExpr* NewDRE = DeclRefExpr::Create(
2523 Context,
2524 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00002525 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002526 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00002527 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002528 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00002529 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002530 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00002531
Chris Lattnerdc046542009-05-08 06:58:22 +00002532 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00002533 // FIXME: This loses syntactic information.
2534 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
2535 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
2536 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002537 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00002538
Chandler Carruthbc8cab12010-07-18 07:23:17 +00002539 // Change the result type of the call to match the original value type. This
2540 // is arbitrary, but the codegen for these builtins ins design to handle it
2541 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00002542 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002543
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002544 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00002545}
2546
Michael Zolotukhin84df1232015-09-08 23:52:33 +00002547/// SemaBuiltinNontemporalOverloaded - We have a call to
2548/// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
2549/// overloaded function based on the pointer type of its last argument.
2550///
2551/// This function goes through and does final semantic checking for these
2552/// builtins.
2553ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
2554 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
2555 DeclRefExpr *DRE =
2556 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2557 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2558 unsigned BuiltinID = FDecl->getBuiltinID();
2559 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
2560 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
2561 "Unexpected nontemporal load/store builtin!");
2562 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
2563 unsigned numArgs = isStore ? 2 : 1;
2564
2565 // Ensure that we have the proper number of arguments.
2566 if (checkArgCount(*this, TheCall, numArgs))
2567 return ExprError();
2568
2569 // Inspect the last argument of the nontemporal builtin. This should always
2570 // be a pointer type, from which we imply the type of the memory access.
2571 // Because it is a pointer type, we don't have to worry about any implicit
2572 // casts here.
2573 Expr *PointerArg = TheCall->getArg(numArgs - 1);
2574 ExprResult PointerArgResult =
2575 DefaultFunctionArrayLvalueConversion(PointerArg);
2576
2577 if (PointerArgResult.isInvalid())
2578 return ExprError();
2579 PointerArg = PointerArgResult.get();
2580 TheCall->setArg(numArgs - 1, PointerArg);
2581
2582 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
2583 if (!pointerType) {
2584 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
2585 << PointerArg->getType() << PointerArg->getSourceRange();
2586 return ExprError();
2587 }
2588
2589 QualType ValType = pointerType->getPointeeType();
2590
2591 // Strip any qualifiers off ValType.
2592 ValType = ValType.getUnqualifiedType();
2593 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2594 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
2595 !ValType->isVectorType()) {
2596 Diag(DRE->getLocStart(),
2597 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
2598 << PointerArg->getType() << PointerArg->getSourceRange();
2599 return ExprError();
2600 }
2601
2602 if (!isStore) {
2603 TheCall->setType(ValType);
2604 return TheCallResult;
2605 }
2606
2607 ExprResult ValArg = TheCall->getArg(0);
2608 InitializedEntity Entity = InitializedEntity::InitializeParameter(
2609 Context, ValType, /*consume*/ false);
2610 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
2611 if (ValArg.isInvalid())
2612 return ExprError();
2613
2614 TheCall->setArg(0, ValArg.get());
2615 TheCall->setType(Context.VoidTy);
2616 return TheCallResult;
2617}
2618
Chris Lattner6436fb62009-02-18 06:01:06 +00002619/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00002620/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00002621/// Note: It might also make sense to do the UTF-16 conversion here (would
2622/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00002623bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00002624 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00002625 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
2626
Douglas Gregorfb65e592011-07-27 05:40:30 +00002627 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00002628 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
2629 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00002630 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00002631 }
Mike Stump11289f42009-09-09 15:08:12 +00002632
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002633 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002634 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002635 unsigned NumBytes = String.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002636 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divackye6377112012-09-06 15:59:27 +00002637 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002638 UTF16 *ToPtr = &ToBuf[0];
2639
2640 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
2641 &ToPtr, ToPtr + NumBytes,
2642 strictConversion);
2643 // Check for conversion failure.
2644 if (Result != conversionOK)
2645 Diag(Arg->getLocStart(),
2646 diag::warn_cfstring_truncated) << Arg->getSourceRange();
2647 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00002648 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002649}
2650
Charles Davisc7d5c942015-09-17 20:55:33 +00002651/// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
2652/// for validity. Emit an error and return true on failure; return false
2653/// on success.
2654bool Sema::SemaBuiltinVAStartImpl(CallExpr *TheCall) {
Chris Lattner08464942007-12-28 05:29:59 +00002655 Expr *Fn = TheCall->getCallee();
2656 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00002657 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002658 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002659 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2660 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00002661 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002662 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00002663 return true;
2664 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00002665
2666 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00002667 return Diag(TheCall->getLocEnd(),
2668 diag::err_typecheck_call_too_few_args_at_least)
2669 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00002670 }
2671
John McCall29ad95b2011-08-27 01:09:30 +00002672 // Type-check the first argument normally.
2673 if (checkBuiltinArgument(*this, TheCall, 0))
2674 return true;
2675
Chris Lattnere202e6a2007-12-20 00:05:45 +00002676 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +00002677 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +00002678 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +00002679 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +00002680 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +00002681 else if (FunctionDecl *FD = getCurFunctionDecl())
2682 isVariadic = FD->isVariadic();
2683 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00002684 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +00002685
Chris Lattnere202e6a2007-12-20 00:05:45 +00002686 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +00002687 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2688 return true;
2689 }
Mike Stump11289f42009-09-09 15:08:12 +00002690
Chris Lattner43be2e62007-12-19 23:59:04 +00002691 // Verify that the second argument to the builtin is the last argument of the
2692 // current function or method.
2693 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00002694 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00002695
Nico Weber9eea7642013-05-24 23:31:57 +00002696 // These are valid if SecondArgIsLastNamedArgument is false after the next
2697 // block.
2698 QualType Type;
2699 SourceLocation ParamLoc;
2700
Anders Carlsson6a8350b2008-02-11 04:20:54 +00002701 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
2702 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +00002703 // FIXME: This isn't correct for methods (results in bogus warning).
2704 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +00002705 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +00002706 if (CurBlock)
2707 LastArg = *(CurBlock->TheDecl->param_end()-1);
2708 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner79413952008-12-04 23:50:19 +00002709 LastArg = *(FD->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00002710 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00002711 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00002712 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weber9eea7642013-05-24 23:31:57 +00002713
2714 Type = PV->getType();
2715 ParamLoc = PV->getLocation();
Chris Lattner43be2e62007-12-19 23:59:04 +00002716 }
2717 }
Mike Stump11289f42009-09-09 15:08:12 +00002718
Chris Lattner43be2e62007-12-19 23:59:04 +00002719 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00002720 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner43be2e62007-12-19 23:59:04 +00002721 diag::warn_second_parameter_of_va_start_not_last_named_argument);
Nico Weber9eea7642013-05-24 23:31:57 +00002722 else if (Type->isReferenceType()) {
2723 Diag(Arg->getLocStart(),
2724 diag::warn_va_start_of_reference_type_is_undefined);
2725 Diag(ParamLoc, diag::note_parameter_type) << Type;
2726 }
2727
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00002728 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00002729 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00002730}
Chris Lattner43be2e62007-12-19 23:59:04 +00002731
Charles Davisc7d5c942015-09-17 20:55:33 +00002732/// Check the arguments to '__builtin_va_start' for validity, and that
2733/// it was called from a function of the native ABI.
2734/// Emit an error and return true on failure; return false on success.
2735bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
2736 // On x86-64 Unix, don't allow this in Win64 ABI functions.
2737 // On x64 Windows, don't allow this in System V ABI functions.
2738 // (Yes, that means there's no corresponding way to support variadic
2739 // System V ABI functions on Windows.)
2740 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64) {
2741 unsigned OS = Context.getTargetInfo().getTriple().getOS();
2742 clang::CallingConv CC = CC_C;
2743 if (const FunctionDecl *FD = getCurFunctionDecl())
2744 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
2745 if ((OS == llvm::Triple::Win32 && CC == CC_X86_64SysV) ||
2746 (OS != llvm::Triple::Win32 && CC == CC_X86_64Win64))
2747 return Diag(TheCall->getCallee()->getLocStart(),
2748 diag::err_va_start_used_in_wrong_abi_function)
2749 << (OS != llvm::Triple::Win32);
2750 }
2751 return SemaBuiltinVAStartImpl(TheCall);
2752}
2753
2754/// Check the arguments to '__builtin_ms_va_start' for validity, and that
2755/// it was called from a Win64 ABI function.
2756/// Emit an error and return true on failure; return false on success.
2757bool Sema::SemaBuiltinMSVAStart(CallExpr *TheCall) {
2758 // This only makes sense for x86-64.
2759 const llvm::Triple &TT = Context.getTargetInfo().getTriple();
2760 Expr *Callee = TheCall->getCallee();
2761 if (TT.getArch() != llvm::Triple::x86_64)
2762 return Diag(Callee->getLocStart(), diag::err_x86_builtin_32_bit_tgt);
2763 // Don't allow this in System V ABI functions.
2764 clang::CallingConv CC = CC_C;
2765 if (const FunctionDecl *FD = getCurFunctionDecl())
2766 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
2767 if (CC == CC_X86_64SysV ||
2768 (TT.getOS() != llvm::Triple::Win32 && CC != CC_X86_64Win64))
2769 return Diag(Callee->getLocStart(),
2770 diag::err_ms_va_start_used_in_sysv_function);
2771 return SemaBuiltinVAStartImpl(TheCall);
2772}
2773
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00002774bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
2775 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
2776 // const char *named_addr);
2777
2778 Expr *Func = Call->getCallee();
2779
2780 if (Call->getNumArgs() < 3)
2781 return Diag(Call->getLocEnd(),
2782 diag::err_typecheck_call_too_few_args_at_least)
2783 << 0 /*function call*/ << 3 << Call->getNumArgs();
2784
2785 // Determine whether the current function is variadic or not.
2786 bool IsVariadic;
2787 if (BlockScopeInfo *CurBlock = getCurBlock())
2788 IsVariadic = CurBlock->TheDecl->isVariadic();
2789 else if (FunctionDecl *FD = getCurFunctionDecl())
2790 IsVariadic = FD->isVariadic();
2791 else if (ObjCMethodDecl *MD = getCurMethodDecl())
2792 IsVariadic = MD->isVariadic();
2793 else
2794 llvm_unreachable("unexpected statement type");
2795
2796 if (!IsVariadic) {
2797 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2798 return true;
2799 }
2800
2801 // Type-check the first argument normally.
2802 if (checkBuiltinArgument(*this, Call, 0))
2803 return true;
2804
Benjamin Kramere0ca6e12015-03-01 18:09:50 +00002805 const struct {
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00002806 unsigned ArgNo;
2807 QualType Type;
2808 } ArgumentTypes[] = {
2809 { 1, Context.getPointerType(Context.CharTy.withConst()) },
2810 { 2, Context.getSizeType() },
2811 };
2812
2813 for (const auto &AT : ArgumentTypes) {
2814 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
2815 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
2816 continue;
2817 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
2818 << Arg->getType() << AT.Type << 1 /* different class */
2819 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
2820 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
2821 }
2822
2823 return false;
2824}
2825
Chris Lattner2da14fb2007-12-20 00:26:33 +00002826/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
2827/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00002828bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
2829 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00002830 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00002831 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00002832 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00002833 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002834 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002835 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00002836 << SourceRange(TheCall->getArg(2)->getLocStart(),
2837 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00002838
John Wiegley01296292011-04-08 18:41:53 +00002839 ExprResult OrigArg0 = TheCall->getArg(0);
2840 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00002841
Chris Lattner2da14fb2007-12-20 00:26:33 +00002842 // Do standard promotions between the two arguments, returning their common
2843 // type.
Chris Lattner08464942007-12-28 05:29:59 +00002844 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00002845 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
2846 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00002847
2848 // Make sure any conversions are pushed back into the call; this is
2849 // type safe since unordered compare builtins are declared as "_Bool
2850 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00002851 TheCall->setArg(0, OrigArg0.get());
2852 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00002853
John Wiegley01296292011-04-08 18:41:53 +00002854 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00002855 return false;
2856
Chris Lattner2da14fb2007-12-20 00:26:33 +00002857 // If the common type isn't a real floating type, then the arguments were
2858 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00002859 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00002860 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002861 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00002862 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
2863 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00002864
Chris Lattner2da14fb2007-12-20 00:26:33 +00002865 return false;
2866}
2867
Benjamin Kramer634fc102010-02-15 22:42:31 +00002868/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
2869/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00002870/// to check everything. We expect the last argument to be a floating point
2871/// value.
2872bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
2873 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00002874 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00002875 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00002876 if (TheCall->getNumArgs() > NumArgs)
2877 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002878 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002879 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00002880 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002881 (*(TheCall->arg_end()-1))->getLocEnd());
2882
Benjamin Kramer64aae502010-02-16 10:07:31 +00002883 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00002884
Eli Friedman7e4faac2009-08-31 20:06:00 +00002885 if (OrigArg->isTypeDependent())
2886 return false;
2887
Chris Lattner68784ef2010-05-06 05:50:07 +00002888 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00002889 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00002890 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002891 diag::err_typecheck_call_invalid_unary_fp)
2892 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002893
Chris Lattner68784ef2010-05-06 05:50:07 +00002894 // If this is an implicit conversion from float -> double, remove it.
2895 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
2896 Expr *CastArg = Cast->getSubExpr();
2897 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
2898 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
2899 "promotion from float to double is the only expected cast here");
Craig Topperc3ec1492014-05-26 06:22:03 +00002900 Cast->setSubExpr(nullptr);
Chris Lattner68784ef2010-05-06 05:50:07 +00002901 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner68784ef2010-05-06 05:50:07 +00002902 }
2903 }
2904
Eli Friedman7e4faac2009-08-31 20:06:00 +00002905 return false;
2906}
2907
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002908/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
2909// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00002910ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00002911 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002912 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00002913 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00002914 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2915 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002916
Nate Begemana0110022010-06-08 00:16:34 +00002917 // Determine which of the following types of shufflevector we're checking:
2918 // 1) unary, vector mask: (lhs, mask)
2919 // 2) binary, vector mask: (lhs, rhs, mask)
2920 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
2921 QualType resType = TheCall->getArg(0)->getType();
2922 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00002923
Douglas Gregorc25f7662009-05-19 22:10:17 +00002924 if (!TheCall->getArg(0)->isTypeDependent() &&
2925 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00002926 QualType LHSType = TheCall->getArg(0)->getType();
2927 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00002928
Craig Topperbaca3892013-07-29 06:47:04 +00002929 if (!LHSType->isVectorType() || !RHSType->isVectorType())
2930 return ExprError(Diag(TheCall->getLocStart(),
2931 diag::err_shufflevector_non_vector)
2932 << SourceRange(TheCall->getArg(0)->getLocStart(),
2933 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00002934
Nate Begemana0110022010-06-08 00:16:34 +00002935 numElements = LHSType->getAs<VectorType>()->getNumElements();
2936 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00002937
Nate Begemana0110022010-06-08 00:16:34 +00002938 // Check to see if we have a call with 2 vector arguments, the unary shuffle
2939 // with mask. If so, verify that RHS is an integer vector type with the
2940 // same number of elts as lhs.
2941 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00002942 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00002943 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00002944 return ExprError(Diag(TheCall->getLocStart(),
2945 diag::err_shufflevector_incompatible_vector)
2946 << SourceRange(TheCall->getArg(1)->getLocStart(),
2947 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00002948 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00002949 return ExprError(Diag(TheCall->getLocStart(),
2950 diag::err_shufflevector_incompatible_vector)
2951 << SourceRange(TheCall->getArg(0)->getLocStart(),
2952 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00002953 } else if (numElements != numResElements) {
2954 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00002955 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002956 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00002957 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002958 }
2959
2960 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00002961 if (TheCall->getArg(i)->isTypeDependent() ||
2962 TheCall->getArg(i)->isValueDependent())
2963 continue;
2964
Nate Begemana0110022010-06-08 00:16:34 +00002965 llvm::APSInt Result(32);
2966 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
2967 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00002968 diag::err_shufflevector_nonconstant_argument)
2969 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002970
Craig Topper50ad5b72013-08-03 17:40:38 +00002971 // Allow -1 which will be translated to undef in the IR.
2972 if (Result.isSigned() && Result.isAllOnesValue())
2973 continue;
2974
Chris Lattner7ab824e2008-08-10 02:05:13 +00002975 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002976 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00002977 diag::err_shufflevector_argument_too_large)
2978 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002979 }
2980
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002981 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002982
Chris Lattner7ab824e2008-08-10 02:05:13 +00002983 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002984 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00002985 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002986 }
2987
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002988 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
2989 TheCall->getCallee()->getLocStart(),
2990 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002991}
Chris Lattner43be2e62007-12-19 23:59:04 +00002992
Hal Finkelc4d7c822013-09-18 03:29:45 +00002993/// SemaConvertVectorExpr - Handle __builtin_convertvector
2994ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
2995 SourceLocation BuiltinLoc,
2996 SourceLocation RParenLoc) {
2997 ExprValueKind VK = VK_RValue;
2998 ExprObjectKind OK = OK_Ordinary;
2999 QualType DstTy = TInfo->getType();
3000 QualType SrcTy = E->getType();
3001
3002 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
3003 return ExprError(Diag(BuiltinLoc,
3004 diag::err_convertvector_non_vector)
3005 << E->getSourceRange());
3006 if (!DstTy->isVectorType() && !DstTy->isDependentType())
3007 return ExprError(Diag(BuiltinLoc,
3008 diag::err_convertvector_non_vector_type));
3009
3010 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
3011 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
3012 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
3013 if (SrcElts != DstElts)
3014 return ExprError(Diag(BuiltinLoc,
3015 diag::err_convertvector_incompatible_vector)
3016 << E->getSourceRange());
3017 }
3018
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003019 return new (Context)
3020 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00003021}
3022
Daniel Dunbarb7257262008-07-21 22:59:13 +00003023/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
3024// This is declared to take (const void*, ...) and can take two
3025// optional constant int args.
3026bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00003027 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00003028
Chris Lattner3b054132008-11-19 05:08:23 +00003029 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003030 return Diag(TheCall->getLocEnd(),
3031 diag::err_typecheck_call_too_many_args_at_most)
3032 << 0 /*function call*/ << 3 << NumArgs
3033 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00003034
3035 // Argument 0 is checked for us and the remaining arguments must be
3036 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00003037 for (unsigned i = 1; i != NumArgs; ++i)
3038 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00003039 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003040
Warren Hunt20e4a5d2014-02-21 23:08:53 +00003041 return false;
3042}
3043
Hal Finkelf0417332014-07-17 14:25:55 +00003044/// SemaBuiltinAssume - Handle __assume (MS Extension).
3045// __assume does not evaluate its arguments, and should warn if its argument
3046// has side effects.
3047bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
3048 Expr *Arg = TheCall->getArg(0);
3049 if (Arg->isInstantiationDependent()) return false;
3050
3051 if (Arg->HasSideEffects(Context))
David Majnemer51236642015-02-26 00:57:33 +00003052 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00003053 << Arg->getSourceRange()
3054 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
3055
3056 return false;
3057}
3058
3059/// Handle __builtin_assume_aligned. This is declared
3060/// as (const void*, size_t, ...) and can take one optional constant int arg.
3061bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
3062 unsigned NumArgs = TheCall->getNumArgs();
3063
3064 if (NumArgs > 3)
3065 return Diag(TheCall->getLocEnd(),
3066 diag::err_typecheck_call_too_many_args_at_most)
3067 << 0 /*function call*/ << 3 << NumArgs
3068 << TheCall->getSourceRange();
3069
3070 // The alignment must be a constant integer.
3071 Expr *Arg = TheCall->getArg(1);
3072
3073 // We can't check the value of a dependent argument.
3074 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
3075 llvm::APSInt Result;
3076 if (SemaBuiltinConstantArg(TheCall, 1, Result))
3077 return true;
3078
3079 if (!Result.isPowerOf2())
3080 return Diag(TheCall->getLocStart(),
3081 diag::err_alignment_not_power_of_two)
3082 << Arg->getSourceRange();
3083 }
3084
3085 if (NumArgs > 2) {
3086 ExprResult Arg(TheCall->getArg(2));
3087 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3088 Context.getSizeType(), false);
3089 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3090 if (Arg.isInvalid()) return true;
3091 TheCall->setArg(2, Arg.get());
3092 }
Hal Finkelf0417332014-07-17 14:25:55 +00003093
3094 return false;
3095}
3096
Eric Christopher8d0c6212010-04-17 02:26:23 +00003097/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
3098/// TheCall is a constant expression.
3099bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
3100 llvm::APSInt &Result) {
3101 Expr *Arg = TheCall->getArg(ArgNum);
3102 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3103 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3104
3105 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
3106
3107 if (!Arg->isIntegerConstantExpr(Result, Context))
3108 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00003109 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00003110
Chris Lattnerd545ad12009-09-23 06:06:36 +00003111 return false;
3112}
3113
Richard Sandiford28940af2014-04-16 08:47:51 +00003114/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
3115/// TheCall is a constant expression in the range [Low, High].
3116bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
3117 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00003118 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00003119
3120 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00003121 Expr *Arg = TheCall->getArg(ArgNum);
3122 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00003123 return false;
3124
Eric Christopher8d0c6212010-04-17 02:26:23 +00003125 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00003126 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00003127 return true;
3128
Richard Sandiford28940af2014-04-16 08:47:51 +00003129 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00003130 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00003131 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00003132
3133 return false;
3134}
3135
Luke Cheeseman59b2d832015-06-15 17:51:01 +00003136/// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
3137/// TheCall is an ARM/AArch64 special register string literal.
3138bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
3139 int ArgNum, unsigned ExpectedFieldNum,
3140 bool AllowName) {
3141 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
3142 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
3143 BuiltinID == ARM::BI__builtin_arm_rsr ||
3144 BuiltinID == ARM::BI__builtin_arm_rsrp ||
3145 BuiltinID == ARM::BI__builtin_arm_wsr ||
3146 BuiltinID == ARM::BI__builtin_arm_wsrp;
3147 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
3148 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
3149 BuiltinID == AArch64::BI__builtin_arm_rsr ||
3150 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
3151 BuiltinID == AArch64::BI__builtin_arm_wsr ||
3152 BuiltinID == AArch64::BI__builtin_arm_wsrp;
3153 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
3154
3155 // We can't check the value of a dependent argument.
3156 Expr *Arg = TheCall->getArg(ArgNum);
3157 if (Arg->isTypeDependent() || Arg->isValueDependent())
3158 return false;
3159
3160 // Check if the argument is a string literal.
3161 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3162 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
3163 << Arg->getSourceRange();
3164
3165 // Check the type of special register given.
3166 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3167 SmallVector<StringRef, 6> Fields;
3168 Reg.split(Fields, ":");
3169
3170 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
3171 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
3172 << Arg->getSourceRange();
3173
3174 // If the string is the name of a register then we cannot check that it is
3175 // valid here but if the string is of one the forms described in ACLE then we
3176 // can check that the supplied fields are integers and within the valid
3177 // ranges.
3178 if (Fields.size() > 1) {
3179 bool FiveFields = Fields.size() == 5;
3180
3181 bool ValidString = true;
3182 if (IsARMBuiltin) {
3183 ValidString &= Fields[0].startswith_lower("cp") ||
3184 Fields[0].startswith_lower("p");
3185 if (ValidString)
3186 Fields[0] =
3187 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
3188
3189 ValidString &= Fields[2].startswith_lower("c");
3190 if (ValidString)
3191 Fields[2] = Fields[2].drop_front(1);
3192
3193 if (FiveFields) {
3194 ValidString &= Fields[3].startswith_lower("c");
3195 if (ValidString)
3196 Fields[3] = Fields[3].drop_front(1);
3197 }
3198 }
3199
3200 SmallVector<int, 5> Ranges;
3201 if (FiveFields)
3202 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 7, 15, 15});
3203 else
3204 Ranges.append({15, 7, 15});
3205
3206 for (unsigned i=0; i<Fields.size(); ++i) {
3207 int IntField;
3208 ValidString &= !Fields[i].getAsInteger(10, IntField);
3209 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
3210 }
3211
3212 if (!ValidString)
3213 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
3214 << Arg->getSourceRange();
3215
3216 } else if (IsAArch64Builtin && Fields.size() == 1) {
3217 // If the register name is one of those that appear in the condition below
3218 // and the special register builtin being used is one of the write builtins,
3219 // then we require that the argument provided for writing to the register
3220 // is an integer constant expression. This is because it will be lowered to
3221 // an MSR (immediate) instruction, so we need to know the immediate at
3222 // compile time.
3223 if (TheCall->getNumArgs() != 2)
3224 return false;
3225
3226 std::string RegLower = Reg.lower();
3227 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
3228 RegLower != "pan" && RegLower != "uao")
3229 return false;
3230
3231 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
3232 }
3233
3234 return false;
3235}
3236
Eli Friedmanc97d0142009-05-03 06:04:26 +00003237/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Joerg Sonnenberger27173282015-03-11 23:46:32 +00003238/// This checks that the target supports __builtin_longjmp and
3239/// that val is a constant 1.
Eli Friedmaneed8ad22009-05-03 04:46:36 +00003240bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Joerg Sonnenberger27173282015-03-11 23:46:32 +00003241 if (!Context.getTargetInfo().hasSjLjLowering())
3242 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
3243 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
3244
Eli Friedmaneed8ad22009-05-03 04:46:36 +00003245 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00003246 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00003247
Eric Christopher8d0c6212010-04-17 02:26:23 +00003248 // TODO: This is less than ideal. Overload this to take a value.
3249 if (SemaBuiltinConstantArg(TheCall, 1, Result))
3250 return true;
3251
3252 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00003253 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
3254 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
3255
3256 return false;
3257}
3258
Joerg Sonnenberger27173282015-03-11 23:46:32 +00003259/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
3260/// This checks that the target supports __builtin_setjmp.
3261bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
3262 if (!Context.getTargetInfo().hasSjLjLowering())
3263 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
3264 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
3265 return false;
3266}
3267
Richard Smithd7293d72013-08-05 18:49:43 +00003268namespace {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003269class UncoveredArgHandler {
3270 enum { Unknown = -1, AllCovered = -2 };
3271 signed FirstUncoveredArg;
3272 SmallVector<const Expr *, 4> DiagnosticExprs;
3273
3274public:
3275 UncoveredArgHandler() : FirstUncoveredArg(Unknown) { }
3276
3277 bool hasUncoveredArg() const {
3278 return (FirstUncoveredArg >= 0);
3279 }
3280
3281 unsigned getUncoveredArg() const {
3282 assert(hasUncoveredArg() && "no uncovered argument");
3283 return FirstUncoveredArg;
3284 }
3285
3286 void setAllCovered() {
3287 // A string has been found with all arguments covered, so clear out
3288 // the diagnostics.
3289 DiagnosticExprs.clear();
3290 FirstUncoveredArg = AllCovered;
3291 }
3292
3293 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
3294 assert(NewFirstUncoveredArg >= 0 && "Outside range");
3295
3296 // Don't update if a previous string covers all arguments.
3297 if (FirstUncoveredArg == AllCovered)
3298 return;
3299
3300 // UncoveredArgHandler tracks the highest uncovered argument index
3301 // and with it all the strings that match this index.
3302 if (NewFirstUncoveredArg == FirstUncoveredArg)
3303 DiagnosticExprs.push_back(StrExpr);
3304 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
3305 DiagnosticExprs.clear();
3306 DiagnosticExprs.push_back(StrExpr);
3307 FirstUncoveredArg = NewFirstUncoveredArg;
3308 }
3309 }
3310
3311 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
3312};
3313
Richard Smithd7293d72013-08-05 18:49:43 +00003314enum StringLiteralCheckType {
3315 SLCT_NotALiteral,
3316 SLCT_UncheckedLiteral,
3317 SLCT_CheckedLiteral
3318};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00003319} // end anonymous namespace
Richard Smithd7293d72013-08-05 18:49:43 +00003320
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00003321static void CheckFormatString(Sema &S, const StringLiteral *FExpr,
3322 const Expr *OrigFormatExpr,
3323 ArrayRef<const Expr *> Args,
3324 bool HasVAListArg, unsigned format_idx,
3325 unsigned firstDataArg,
3326 Sema::FormatStringType Type,
3327 bool inFunctionCall,
3328 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003329 llvm::SmallBitVector &CheckedVarArgs,
3330 UncoveredArgHandler &UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00003331
Richard Smith55ce3522012-06-25 20:30:08 +00003332// Determine if an expression is a string literal or constant string.
3333// If this function returns false on the arguments to a function expecting a
3334// format string, we will usually need to emit a warning.
3335// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00003336static StringLiteralCheckType
3337checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
3338 bool HasVAListArg, unsigned format_idx,
3339 unsigned firstDataArg, Sema::FormatStringType Type,
3340 Sema::VariadicCallType CallType, bool InFunctionCall,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003341 llvm::SmallBitVector &CheckedVarArgs,
3342 UncoveredArgHandler &UncoveredArg) {
Ted Kremenek808829352010-09-09 03:51:39 +00003343 tryAgain:
Douglas Gregorc25f7662009-05-19 22:10:17 +00003344 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00003345 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003346
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003347 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00003348
Richard Smithd7293d72013-08-05 18:49:43 +00003349 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00003350 // Technically -Wformat-nonliteral does not warn about this case.
3351 // The behavior of printf and friends in this case is implementation
3352 // dependent. Ideally if the format string cannot be null then
3353 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00003354 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00003355
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003356 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00003357 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003358 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00003359 // The expression is a literal if both sub-expressions were, and it was
3360 // completely checked only if both sub-expressions were checked.
3361 const AbstractConditionalOperator *C =
3362 cast<AbstractConditionalOperator>(E);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003363
3364 // Determine whether it is necessary to check both sub-expressions, for
3365 // example, because the condition expression is a constant that can be
3366 // evaluated at compile time.
3367 bool CheckLeft = true, CheckRight = true;
3368
3369 bool Cond;
3370 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
3371 if (Cond)
3372 CheckRight = false;
3373 else
3374 CheckLeft = false;
3375 }
3376
3377 StringLiteralCheckType Left;
3378 if (!CheckLeft)
3379 Left = SLCT_UncheckedLiteral;
3380 else {
3381 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
3382 HasVAListArg, format_idx, firstDataArg,
3383 Type, CallType, InFunctionCall,
3384 CheckedVarArgs, UncoveredArg);
3385 if (Left == SLCT_NotALiteral || !CheckRight)
3386 return Left;
3387 }
3388
Richard Smith55ce3522012-06-25 20:30:08 +00003389 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00003390 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003391 HasVAListArg, format_idx, firstDataArg,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003392 Type, CallType, InFunctionCall, CheckedVarArgs,
3393 UncoveredArg);
3394
3395 return (CheckLeft && Left < Right) ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003396 }
3397
3398 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00003399 E = cast<ImplicitCastExpr>(E)->getSubExpr();
3400 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003401 }
3402
John McCallc07a0c72011-02-17 10:25:35 +00003403 case Stmt::OpaqueValueExprClass:
3404 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
3405 E = src;
3406 goto tryAgain;
3407 }
Richard Smith55ce3522012-06-25 20:30:08 +00003408 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00003409
Ted Kremeneka8890832011-02-24 23:03:04 +00003410 case Stmt::PredefinedExprClass:
3411 // While __func__, etc., are technically not string literals, they
3412 // cannot contain format specifiers and thus are not a security
3413 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00003414 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00003415
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003416 case Stmt::DeclRefExprClass: {
3417 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00003418
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003419 // As an exception, do not flag errors for variables binding to
3420 // const string literals.
3421 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
3422 bool isConstant = false;
3423 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003424
Richard Smithd7293d72013-08-05 18:49:43 +00003425 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
3426 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00003427 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00003428 isConstant = T.isConstant(S.Context) &&
3429 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00003430 } else if (T->isObjCObjectPointerType()) {
3431 // In ObjC, there is usually no "const ObjectPointer" type,
3432 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00003433 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003434 }
Mike Stump11289f42009-09-09 15:08:12 +00003435
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003436 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00003437 if (const Expr *Init = VD->getAnyInitializer()) {
3438 // Look through initializers like const char c[] = { "foo" }
3439 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
3440 if (InitList->isStringLiteralInit())
3441 Init = InitList->getInit(0)->IgnoreParenImpCasts();
3442 }
Richard Smithd7293d72013-08-05 18:49:43 +00003443 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003444 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003445 firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003446 /*InFunctionCall*/false, CheckedVarArgs,
3447 UncoveredArg);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00003448 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003449 }
Mike Stump11289f42009-09-09 15:08:12 +00003450
Anders Carlssonb012ca92009-06-28 19:55:58 +00003451 // For vprintf* functions (i.e., HasVAListArg==true), we add a
3452 // special check to see if the format string is a function parameter
3453 // of the function calling the printf function. If the function
3454 // has an attribute indicating it is a printf-like function, then we
3455 // should suppress warnings concerning non-literals being used in a call
3456 // to a vprintf function. For example:
3457 //
3458 // void
3459 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
3460 // va_list ap;
3461 // va_start(ap, fmt);
3462 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
3463 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00003464 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00003465 if (HasVAListArg) {
3466 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
3467 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
3468 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00003469 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00003470 // adjust for implicit parameter
3471 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
3472 if (MD->isInstance())
3473 ++PVIndex;
3474 // We also check if the formats are compatible.
3475 // We can't pass a 'scanf' string to a 'printf' function.
3476 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00003477 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00003478 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00003479 }
3480 }
3481 }
3482 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003483 }
Mike Stump11289f42009-09-09 15:08:12 +00003484
Richard Smith55ce3522012-06-25 20:30:08 +00003485 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003486 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003487
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00003488 case Stmt::CallExprClass:
3489 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00003490 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00003491 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
3492 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
3493 unsigned ArgIndex = FA->getFormatIdx();
3494 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
3495 if (MD->isInstance())
3496 --ArgIndex;
3497 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00003498
Richard Smithd7293d72013-08-05 18:49:43 +00003499 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003500 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00003501 Type, CallType, InFunctionCall,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003502 CheckedVarArgs, UncoveredArg);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003503 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
3504 unsigned BuiltinID = FD->getBuiltinID();
3505 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
3506 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
3507 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00003508 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003509 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003510 firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003511 InFunctionCall, CheckedVarArgs,
3512 UncoveredArg);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003513 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00003514 }
3515 }
Mike Stump11289f42009-09-09 15:08:12 +00003516
Richard Smith55ce3522012-06-25 20:30:08 +00003517 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00003518 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003519 case Stmt::ObjCStringLiteralClass:
3520 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00003521 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003522
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003523 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003524 StrE = ObjCFExpr->getString();
3525 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003526 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00003527
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003528 if (StrE) {
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00003529 CheckFormatString(S, StrE, E, Args, HasVAListArg, format_idx,
3530 firstDataArg, Type, InFunctionCall, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003531 CheckedVarArgs, UncoveredArg);
Richard Smith55ce3522012-06-25 20:30:08 +00003532 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003533 }
Mike Stump11289f42009-09-09 15:08:12 +00003534
Richard Smith55ce3522012-06-25 20:30:08 +00003535 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003536 }
Mike Stump11289f42009-09-09 15:08:12 +00003537
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003538 default:
Richard Smith55ce3522012-06-25 20:30:08 +00003539 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003540 }
3541}
3542
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003543Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00003544 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003545 .Case("scanf", FST_Scanf)
3546 .Cases("printf", "printf0", FST_Printf)
3547 .Cases("NSString", "CFString", FST_NSString)
3548 .Case("strftime", FST_Strftime)
3549 .Case("strfmon", FST_Strfmon)
3550 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
Dimitry Andric6b5ed342015-02-19 22:32:33 +00003551 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00003552 .Case("os_trace", FST_OSTrace)
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003553 .Default(FST_Unknown);
3554}
3555
Jordan Rose3e0ec582012-07-19 18:10:23 +00003556/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00003557/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00003558/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003559bool Sema::CheckFormatArguments(const FormatAttr *Format,
3560 ArrayRef<const Expr *> Args,
3561 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003562 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00003563 SourceLocation Loc, SourceRange Range,
3564 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00003565 FormatStringInfo FSI;
3566 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003567 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00003568 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00003569 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00003570 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003571}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00003572
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003573bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003574 bool HasVAListArg, unsigned format_idx,
3575 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003576 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00003577 SourceLocation Loc, SourceRange Range,
3578 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00003579 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003580 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003581 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00003582 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00003583 }
Mike Stump11289f42009-09-09 15:08:12 +00003584
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003585 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00003586
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003587 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00003588 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00003589 // Dynamically generated format strings are difficult to
3590 // automatically vet at compile time. Requiring that format strings
3591 // are string literals: (1) permits the checking of format strings by
3592 // the compiler and thereby (2) can practically remove the source of
3593 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00003594
Mike Stump11289f42009-09-09 15:08:12 +00003595 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00003596 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00003597 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00003598 // the same format string checking logic for both ObjC and C strings.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003599 UncoveredArgHandler UncoveredArg;
Richard Smith55ce3522012-06-25 20:30:08 +00003600 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00003601 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
3602 format_idx, firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003603 /*IsFunctionCall*/true, CheckedVarArgs,
3604 UncoveredArg);
3605
3606 // Generate a diagnostic where an uncovered argument is detected.
3607 if (UncoveredArg.hasUncoveredArg()) {
3608 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
3609 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
3610 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
3611 }
3612
Richard Smith55ce3522012-06-25 20:30:08 +00003613 if (CT != SLCT_NotALiteral)
3614 // Literal format string found, check done!
3615 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00003616
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00003617 // Strftime is particular as it always uses a single 'time' argument,
3618 // so it is safe to pass a non-literal string.
3619 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00003620 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00003621
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00003622 // Do not emit diag when the string param is a macro expansion and the
3623 // format is either NSString or CFString. This is a hack to prevent
3624 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
3625 // which are usually used in place of NS and CF string literals.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00003626 SourceLocation FormatLoc = Args[format_idx]->getLocStart();
3627 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
Richard Smith55ce3522012-06-25 20:30:08 +00003628 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00003629
Chris Lattnercc5d1c22009-04-29 04:59:47 +00003630 // If there are no arguments specified, warn with -Wformat-security, otherwise
3631 // warn only with -Wformat-nonliteral.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00003632 if (Args.size() == firstDataArg) {
Bob Wilson57819fc2016-03-15 20:56:38 +00003633 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
3634 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00003635 switch (Type) {
3636 default:
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00003637 break;
3638 case FST_Kprintf:
3639 case FST_FreeBSDKPrintf:
3640 case FST_Printf:
Bob Wilson57819fc2016-03-15 20:56:38 +00003641 Diag(FormatLoc, diag::note_format_security_fixit)
3642 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00003643 break;
3644 case FST_NSString:
Bob Wilson57819fc2016-03-15 20:56:38 +00003645 Diag(FormatLoc, diag::note_format_security_fixit)
3646 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00003647 break;
3648 }
3649 } else {
3650 Diag(FormatLoc, diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00003651 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00003652 }
Richard Smith55ce3522012-06-25 20:30:08 +00003653 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003654}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00003655
Ted Kremenekab278de2010-01-28 23:39:18 +00003656namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00003657class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
3658protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00003659 Sema &S;
3660 const StringLiteral *FExpr;
3661 const Expr *OrigFormatExpr;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00003662 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00003663 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00003664 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00003665 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003666 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00003667 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00003668 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00003669 bool usesPositionalArgs;
3670 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00003671 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00003672 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00003673 llvm::SmallBitVector &CheckedVarArgs;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003674 UncoveredArgHandler &UncoveredArg;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00003675
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003676public:
Ted Kremenek02087932010-07-16 02:11:22 +00003677 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek4d745dd2010-03-25 03:59:12 +00003678 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003679 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003680 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003681 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003682 Sema::VariadicCallType callType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003683 llvm::SmallBitVector &CheckedVarArgs,
3684 UncoveredArgHandler &UncoveredArg)
Ted Kremenekab278de2010-01-28 23:39:18 +00003685 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003686 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
3687 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003688 Args(Args), FormatIdx(formatIdx),
Richard Trieu03cf7b72011-10-28 00:41:25 +00003689 usesPositionalArgs(false), atFirstArg(true),
Richard Smithd7293d72013-08-05 18:49:43 +00003690 inFunctionCall(inFunctionCall), CallType(callType),
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003691 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
Richard Smithd7293d72013-08-05 18:49:43 +00003692 CoveredArgs.resize(numDataArgs);
3693 CoveredArgs.reset();
3694 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003695
Ted Kremenek019d2242010-01-29 01:50:07 +00003696 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003697
Ted Kremenek02087932010-07-16 02:11:22 +00003698 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003699 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003700
Jordan Rose92303592012-09-08 04:00:03 +00003701 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00003702 const analyze_format_string::FormatSpecifier &FS,
3703 const analyze_format_string::ConversionSpecifier &CS,
3704 const char *startSpecifier, unsigned specifierLen,
3705 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00003706
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003707 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00003708 const analyze_format_string::FormatSpecifier &FS,
3709 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003710
3711 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00003712 const analyze_format_string::ConversionSpecifier &CS,
3713 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003714
Craig Toppere14c0f82014-03-12 04:55:44 +00003715 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00003716
Craig Toppere14c0f82014-03-12 04:55:44 +00003717 void HandleInvalidPosition(const char *startSpecifier,
3718 unsigned specifierLen,
3719 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00003720
Craig Toppere14c0f82014-03-12 04:55:44 +00003721 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00003722
Craig Toppere14c0f82014-03-12 04:55:44 +00003723 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003724
Richard Trieu03cf7b72011-10-28 00:41:25 +00003725 template <typename Range>
3726 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
3727 const Expr *ArgumentExpr,
3728 PartialDiagnostic PDiag,
3729 SourceLocation StringLoc,
3730 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00003731 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00003732
Ted Kremenek02087932010-07-16 02:11:22 +00003733protected:
Ted Kremenekce815422010-07-19 21:25:57 +00003734 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
3735 const char *startSpec,
3736 unsigned specifierLen,
3737 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00003738
3739 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
3740 const char *startSpec,
3741 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00003742
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003743 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00003744 CharSourceRange getSpecifierRange(const char *startSpecifier,
3745 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00003746 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003747
Ted Kremenek5739de72010-01-29 01:06:55 +00003748 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003749
3750 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
3751 const analyze_format_string::ConversionSpecifier &CS,
3752 const char *startSpecifier, unsigned specifierLen,
3753 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00003754
3755 template <typename Range>
3756 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
3757 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00003758 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00003759};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00003760} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00003761
Ted Kremenek02087932010-07-16 02:11:22 +00003762SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00003763 return OrigFormatExpr->getSourceRange();
3764}
3765
Ted Kremenek02087932010-07-16 02:11:22 +00003766CharSourceRange CheckFormatHandler::
3767getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00003768 SourceLocation Start = getLocationOfByte(startSpecifier);
3769 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
3770
3771 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003772 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00003773
3774 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003775}
3776
Ted Kremenek02087932010-07-16 02:11:22 +00003777SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003778 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremenekab278de2010-01-28 23:39:18 +00003779}
3780
Ted Kremenek02087932010-07-16 02:11:22 +00003781void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
3782 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00003783 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
3784 getLocationOfByte(startSpecifier),
3785 /*IsStringLocation*/true,
3786 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00003787}
3788
Jordan Rose92303592012-09-08 04:00:03 +00003789void CheckFormatHandler::HandleInvalidLengthModifier(
3790 const analyze_format_string::FormatSpecifier &FS,
3791 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00003792 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00003793 using namespace analyze_format_string;
3794
3795 const LengthModifier &LM = FS.getLengthModifier();
3796 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
3797
3798 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00003799 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00003800 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00003801 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00003802 getLocationOfByte(LM.getStart()),
3803 /*IsStringLocation*/true,
3804 getSpecifierRange(startSpecifier, specifierLen));
3805
3806 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
3807 << FixedLM->toString()
3808 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
3809
3810 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00003811 FixItHint Hint;
3812 if (DiagID == diag::warn_format_nonsensical_length)
3813 Hint = FixItHint::CreateRemoval(LMRange);
3814
3815 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00003816 getLocationOfByte(LM.getStart()),
3817 /*IsStringLocation*/true,
3818 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00003819 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00003820 }
3821}
3822
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003823void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00003824 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003825 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00003826 using namespace analyze_format_string;
3827
3828 const LengthModifier &LM = FS.getLengthModifier();
3829 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
3830
3831 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00003832 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00003833 if (FixedLM) {
3834 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3835 << LM.toString() << 0,
3836 getLocationOfByte(LM.getStart()),
3837 /*IsStringLocation*/true,
3838 getSpecifierRange(startSpecifier, specifierLen));
3839
3840 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
3841 << FixedLM->toString()
3842 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
3843
3844 } else {
3845 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3846 << LM.toString() << 0,
3847 getLocationOfByte(LM.getStart()),
3848 /*IsStringLocation*/true,
3849 getSpecifierRange(startSpecifier, specifierLen));
3850 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003851}
3852
3853void CheckFormatHandler::HandleNonStandardConversionSpecifier(
3854 const analyze_format_string::ConversionSpecifier &CS,
3855 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00003856 using namespace analyze_format_string;
3857
3858 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00003859 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00003860 if (FixedCS) {
3861 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3862 << CS.toString() << /*conversion specifier*/1,
3863 getLocationOfByte(CS.getStart()),
3864 /*IsStringLocation*/true,
3865 getSpecifierRange(startSpecifier, specifierLen));
3866
3867 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
3868 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
3869 << FixedCS->toString()
3870 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
3871 } else {
3872 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3873 << CS.toString() << /*conversion specifier*/1,
3874 getLocationOfByte(CS.getStart()),
3875 /*IsStringLocation*/true,
3876 getSpecifierRange(startSpecifier, specifierLen));
3877 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003878}
3879
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00003880void CheckFormatHandler::HandlePosition(const char *startPos,
3881 unsigned posLen) {
3882 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
3883 getLocationOfByte(startPos),
3884 /*IsStringLocation*/true,
3885 getSpecifierRange(startPos, posLen));
3886}
3887
Ted Kremenekd1668192010-02-27 01:41:03 +00003888void
Ted Kremenek02087932010-07-16 02:11:22 +00003889CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
3890 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003891 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
3892 << (unsigned) p,
3893 getLocationOfByte(startPos), /*IsStringLocation*/true,
3894 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00003895}
3896
Ted Kremenek02087932010-07-16 02:11:22 +00003897void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00003898 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003899 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
3900 getLocationOfByte(startPos),
3901 /*IsStringLocation*/true,
3902 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00003903}
3904
Ted Kremenek02087932010-07-16 02:11:22 +00003905void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003906 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00003907 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003908 EmitFormatDiagnostic(
3909 S.PDiag(diag::warn_printf_format_string_contains_null_char),
3910 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
3911 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00003912 }
Ted Kremenek02087932010-07-16 02:11:22 +00003913}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003914
Jordan Rose58bbe422012-07-19 18:10:08 +00003915// Note that this may return NULL if there was an error parsing or building
3916// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00003917const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003918 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00003919}
3920
3921void CheckFormatHandler::DoneProcessing() {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003922 // Does the number of data arguments exceed the number of
3923 // format conversions in the format string?
Ted Kremenek02087932010-07-16 02:11:22 +00003924 if (!HasVAListArg) {
3925 // Find any arguments that weren't covered.
3926 CoveredArgs.flip();
3927 signed notCoveredArg = CoveredArgs.find_first();
3928 if (notCoveredArg >= 0) {
3929 assert((unsigned)notCoveredArg < NumDataArgs);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003930 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
3931 } else {
3932 UncoveredArg.setAllCovered();
Ted Kremenek02087932010-07-16 02:11:22 +00003933 }
3934 }
3935}
3936
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003937void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
3938 const Expr *ArgExpr) {
3939 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
3940 "Invalid state");
3941
3942 if (!ArgExpr)
3943 return;
3944
3945 SourceLocation Loc = ArgExpr->getLocStart();
3946
3947 if (S.getSourceManager().isInSystemMacro(Loc))
3948 return;
3949
3950 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
3951 for (auto E : DiagnosticExprs)
3952 PDiag << E->getSourceRange();
3953
3954 CheckFormatHandler::EmitFormatDiagnostic(
3955 S, IsFunctionCall, DiagnosticExprs[0],
3956 PDiag, Loc, /*IsStringLocation*/false,
3957 DiagnosticExprs[0]->getSourceRange());
3958}
3959
Ted Kremenekce815422010-07-19 21:25:57 +00003960bool
3961CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
3962 SourceLocation Loc,
3963 const char *startSpec,
3964 unsigned specifierLen,
3965 const char *csStart,
3966 unsigned csLen) {
Ted Kremenekce815422010-07-19 21:25:57 +00003967 bool keepGoing = true;
3968 if (argIndex < NumDataArgs) {
3969 // Consider the argument coverered, even though the specifier doesn't
3970 // make sense.
3971 CoveredArgs.set(argIndex);
3972 }
3973 else {
3974 // If argIndex exceeds the number of data arguments we
3975 // don't issue a warning because that is just a cascade of warnings (and
3976 // they may have intended '%%' anyway). We don't want to continue processing
3977 // the format string after this point, however, as we will like just get
3978 // gibberish when trying to match arguments.
3979 keepGoing = false;
3980 }
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00003981
3982 StringRef Specifier(csStart, csLen);
3983
3984 // If the specifier in non-printable, it could be the first byte of a UTF-8
3985 // sequence. In that case, print the UTF-8 code point. If not, print the byte
3986 // hex value.
3987 std::string CodePointStr;
3988 if (!llvm::sys::locale::isPrint(*csStart)) {
3989 UTF32 CodePoint;
3990 const UTF8 **B = reinterpret_cast<const UTF8 **>(&csStart);
3991 const UTF8 *E =
3992 reinterpret_cast<const UTF8 *>(csStart + csLen);
3993 ConversionResult Result =
3994 llvm::convertUTF8Sequence(B, E, &CodePoint, strictConversion);
3995
3996 if (Result != conversionOK) {
3997 unsigned char FirstChar = *csStart;
3998 CodePoint = (UTF32)FirstChar;
3999 }
4000
4001 llvm::raw_string_ostream OS(CodePointStr);
4002 if (CodePoint < 256)
4003 OS << "\\x" << llvm::format("%02x", CodePoint);
4004 else if (CodePoint <= 0xFFFF)
4005 OS << "\\u" << llvm::format("%04x", CodePoint);
4006 else
4007 OS << "\\U" << llvm::format("%08x", CodePoint);
4008 OS.flush();
4009 Specifier = CodePointStr;
4010 }
4011
4012 EmitFormatDiagnostic(
4013 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
4014 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
4015
Ted Kremenekce815422010-07-19 21:25:57 +00004016 return keepGoing;
4017}
4018
Richard Trieu03cf7b72011-10-28 00:41:25 +00004019void
4020CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
4021 const char *startSpec,
4022 unsigned specifierLen) {
4023 EmitFormatDiagnostic(
4024 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
4025 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
4026}
4027
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004028bool
4029CheckFormatHandler::CheckNumArgs(
4030 const analyze_format_string::FormatSpecifier &FS,
4031 const analyze_format_string::ConversionSpecifier &CS,
4032 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
4033
4034 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004035 PartialDiagnostic PDiag = FS.usesPositionalArg()
4036 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
4037 << (argIndex+1) << NumDataArgs)
4038 : S.PDiag(diag::warn_printf_insufficient_data_args);
4039 EmitFormatDiagnostic(
4040 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
4041 getSpecifierRange(startSpecifier, specifierLen));
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004042
4043 // Since more arguments than conversion tokens are given, by extension
4044 // all arguments are covered, so mark this as so.
4045 UncoveredArg.setAllCovered();
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004046 return false;
4047 }
4048 return true;
4049}
4050
Richard Trieu03cf7b72011-10-28 00:41:25 +00004051template<typename Range>
4052void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
4053 SourceLocation Loc,
4054 bool IsStringLocation,
4055 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00004056 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004057 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00004058 Loc, IsStringLocation, StringRange, FixIt);
4059}
4060
4061/// \brief If the format string is not within the funcion call, emit a note
4062/// so that the function call and string are in diagnostic messages.
4063///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00004064/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00004065/// call and only one diagnostic message will be produced. Otherwise, an
4066/// extra note will be emitted pointing to location of the format string.
4067///
4068/// \param ArgumentExpr the expression that is passed as the format string
4069/// argument in the function call. Used for getting locations when two
4070/// diagnostics are emitted.
4071///
4072/// \param PDiag the callee should already have provided any strings for the
4073/// diagnostic message. This function only adds locations and fixits
4074/// to diagnostics.
4075///
4076/// \param Loc primary location for diagnostic. If two diagnostics are
4077/// required, one will be at Loc and a new SourceLocation will be created for
4078/// the other one.
4079///
4080/// \param IsStringLocation if true, Loc points to the format string should be
4081/// used for the note. Otherwise, Loc points to the argument list and will
4082/// be used with PDiag.
4083///
4084/// \param StringRange some or all of the string to highlight. This is
4085/// templated so it can accept either a CharSourceRange or a SourceRange.
4086///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00004087/// \param FixIt optional fix it hint for the format string.
Richard Trieu03cf7b72011-10-28 00:41:25 +00004088template<typename Range>
4089void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
4090 const Expr *ArgumentExpr,
4091 PartialDiagnostic PDiag,
4092 SourceLocation Loc,
4093 bool IsStringLocation,
4094 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00004095 ArrayRef<FixItHint> FixIt) {
4096 if (InFunctionCall) {
4097 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
4098 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00004099 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00004100 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004101 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
4102 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00004103
4104 const Sema::SemaDiagnosticBuilder &Note =
4105 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
4106 diag::note_format_string_defined);
4107
4108 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00004109 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00004110 }
4111}
4112
Ted Kremenek02087932010-07-16 02:11:22 +00004113//===--- CHECK: Printf format string checking ------------------------------===//
4114
4115namespace {
4116class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004117 bool ObjCContext;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004118
Ted Kremenek02087932010-07-16 02:11:22 +00004119public:
4120 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
4121 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004122 unsigned numDataArgs, bool isObjC,
Ted Kremenek02087932010-07-16 02:11:22 +00004123 const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004124 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004125 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00004126 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004127 llvm::SmallBitVector &CheckedVarArgs,
4128 UncoveredArgHandler &UncoveredArg)
Richard Smithd7293d72013-08-05 18:49:43 +00004129 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
4130 numDataArgs, beg, hasVAListArg, Args,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004131 formatIdx, inFunctionCall, CallType, CheckedVarArgs,
4132 UncoveredArg),
Richard Smithd7293d72013-08-05 18:49:43 +00004133 ObjCContext(isObjC)
Jordan Rose3e0ec582012-07-19 18:10:23 +00004134 {}
4135
Ted Kremenek02087932010-07-16 02:11:22 +00004136 bool HandleInvalidPrintfConversionSpecifier(
4137 const analyze_printf::PrintfSpecifier &FS,
4138 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004139 unsigned specifierLen) override;
4140
Ted Kremenek02087932010-07-16 02:11:22 +00004141 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
4142 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004143 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00004144 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
4145 const char *StartSpecifier,
4146 unsigned SpecifierLen,
4147 const Expr *E);
4148
Ted Kremenek02087932010-07-16 02:11:22 +00004149 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
4150 const char *startSpecifier, unsigned specifierLen);
4151 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
4152 const analyze_printf::OptionalAmount &Amt,
4153 unsigned type,
4154 const char *startSpecifier, unsigned specifierLen);
4155 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
4156 const analyze_printf::OptionalFlag &flag,
4157 const char *startSpecifier, unsigned specifierLen);
4158 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
4159 const analyze_printf::OptionalFlag &ignoredFlag,
4160 const analyze_printf::OptionalFlag &flag,
4161 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004162 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00004163 const Expr *E);
Ted Kremenek2b417712015-07-02 05:39:16 +00004164
4165 void HandleEmptyObjCModifierFlag(const char *startFlag,
4166 unsigned flagLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00004167
Ted Kremenek2b417712015-07-02 05:39:16 +00004168 void HandleInvalidObjCModifierFlag(const char *startFlag,
4169 unsigned flagLen) override;
4170
4171 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
4172 const char *flagsEnd,
4173 const char *conversionPosition)
4174 override;
4175};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004176} // end anonymous namespace
Ted Kremenek02087932010-07-16 02:11:22 +00004177
4178bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
4179 const analyze_printf::PrintfSpecifier &FS,
4180 const char *startSpecifier,
4181 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004182 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00004183 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00004184
Ted Kremenekce815422010-07-19 21:25:57 +00004185 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
4186 getLocationOfByte(CS.getStart()),
4187 startSpecifier, specifierLen,
4188 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00004189}
4190
Ted Kremenek02087932010-07-16 02:11:22 +00004191bool CheckPrintfHandler::HandleAmount(
4192 const analyze_format_string::OptionalAmount &Amt,
4193 unsigned k, const char *startSpecifier,
4194 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00004195 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00004196 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00004197 unsigned argIndex = Amt.getArgIndex();
4198 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004199 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
4200 << k,
4201 getLocationOfByte(Amt.getStart()),
4202 /*IsStringLocation*/true,
4203 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00004204 // Don't do any more checking. We will just emit
4205 // spurious errors.
4206 return false;
4207 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004208
Ted Kremenek5739de72010-01-29 01:06:55 +00004209 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00004210 // Although not in conformance with C99, we also allow the argument to be
4211 // an 'unsigned int' as that is a reasonably safe case. GCC also
4212 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00004213 CoveredArgs.set(argIndex);
4214 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00004215 if (!Arg)
4216 return false;
4217
Ted Kremenek5739de72010-01-29 01:06:55 +00004218 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004219
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004220 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
4221 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004222
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004223 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004224 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004225 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00004226 << T << Arg->getSourceRange(),
4227 getLocationOfByte(Amt.getStart()),
4228 /*IsStringLocation*/true,
4229 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00004230 // Don't do any more checking. We will just emit
4231 // spurious errors.
4232 return false;
4233 }
4234 }
4235 }
4236 return true;
4237}
Ted Kremenek5739de72010-01-29 01:06:55 +00004238
Tom Careb49ec692010-06-17 19:00:27 +00004239void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00004240 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00004241 const analyze_printf::OptionalAmount &Amt,
4242 unsigned type,
4243 const char *startSpecifier,
4244 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004245 const analyze_printf::PrintfConversionSpecifier &CS =
4246 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00004247
Richard Trieu03cf7b72011-10-28 00:41:25 +00004248 FixItHint fixit =
4249 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
4250 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
4251 Amt.getConstantLength()))
4252 : FixItHint();
4253
4254 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
4255 << type << CS.toString(),
4256 getLocationOfByte(Amt.getStart()),
4257 /*IsStringLocation*/true,
4258 getSpecifierRange(startSpecifier, specifierLen),
4259 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00004260}
4261
Ted Kremenek02087932010-07-16 02:11:22 +00004262void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00004263 const analyze_printf::OptionalFlag &flag,
4264 const char *startSpecifier,
4265 unsigned specifierLen) {
4266 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004267 const analyze_printf::PrintfConversionSpecifier &CS =
4268 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00004269 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
4270 << flag.toString() << CS.toString(),
4271 getLocationOfByte(flag.getPosition()),
4272 /*IsStringLocation*/true,
4273 getSpecifierRange(startSpecifier, specifierLen),
4274 FixItHint::CreateRemoval(
4275 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00004276}
4277
4278void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00004279 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00004280 const analyze_printf::OptionalFlag &ignoredFlag,
4281 const analyze_printf::OptionalFlag &flag,
4282 const char *startSpecifier,
4283 unsigned specifierLen) {
4284 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00004285 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
4286 << ignoredFlag.toString() << flag.toString(),
4287 getLocationOfByte(ignoredFlag.getPosition()),
4288 /*IsStringLocation*/true,
4289 getSpecifierRange(startSpecifier, specifierLen),
4290 FixItHint::CreateRemoval(
4291 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00004292}
4293
Ted Kremenek2b417712015-07-02 05:39:16 +00004294// void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
4295// bool IsStringLocation, Range StringRange,
4296// ArrayRef<FixItHint> Fixit = None);
4297
4298void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
4299 unsigned flagLen) {
4300 // Warn about an empty flag.
4301 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
4302 getLocationOfByte(startFlag),
4303 /*IsStringLocation*/true,
4304 getSpecifierRange(startFlag, flagLen));
4305}
4306
4307void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
4308 unsigned flagLen) {
4309 // Warn about an invalid flag.
4310 auto Range = getSpecifierRange(startFlag, flagLen);
4311 StringRef flag(startFlag, flagLen);
4312 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
4313 getLocationOfByte(startFlag),
4314 /*IsStringLocation*/true,
4315 Range, FixItHint::CreateRemoval(Range));
4316}
4317
4318void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
4319 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
4320 // Warn about using '[...]' without a '@' conversion.
4321 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
4322 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
4323 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
4324 getLocationOfByte(conversionPosition),
4325 /*IsStringLocation*/true,
4326 Range, FixItHint::CreateRemoval(Range));
4327}
4328
Richard Smith55ce3522012-06-25 20:30:08 +00004329// Determines if the specified is a C++ class or struct containing
4330// a member with the specified name and kind (e.g. a CXXMethodDecl named
4331// "c_str()").
4332template<typename MemberKind>
4333static llvm::SmallPtrSet<MemberKind*, 1>
4334CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
4335 const RecordType *RT = Ty->getAs<RecordType>();
4336 llvm::SmallPtrSet<MemberKind*, 1> Results;
4337
4338 if (!RT)
4339 return Results;
4340 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00004341 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00004342 return Results;
4343
Alp Tokerb6cc5922014-05-03 03:45:55 +00004344 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00004345 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00004346 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00004347
4348 // We just need to include all members of the right kind turned up by the
4349 // filter, at this point.
4350 if (S.LookupQualifiedName(R, RT->getDecl()))
4351 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
4352 NamedDecl *decl = (*I)->getUnderlyingDecl();
4353 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
4354 Results.insert(FK);
4355 }
4356 return Results;
4357}
4358
Richard Smith2868a732014-02-28 01:36:39 +00004359/// Check if we could call '.c_str()' on an object.
4360///
4361/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
4362/// allow the call, or if it would be ambiguous).
4363bool Sema::hasCStrMethod(const Expr *E) {
4364 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
4365 MethodSet Results =
4366 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
4367 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
4368 MI != ME; ++MI)
4369 if ((*MI)->getMinRequiredArguments() == 0)
4370 return true;
4371 return false;
4372}
4373
Richard Smith55ce3522012-06-25 20:30:08 +00004374// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004375// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00004376// Returns true when a c_str() conversion method is found.
4377bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00004378 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00004379 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
4380
4381 MethodSet Results =
4382 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
4383
4384 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
4385 MI != ME; ++MI) {
4386 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00004387 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00004388 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00004389 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00004390 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00004391 S.Diag(E->getLocStart(), diag::note_printf_c_str)
4392 << "c_str()"
4393 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
4394 return true;
4395 }
4396 }
4397
4398 return false;
4399}
4400
Ted Kremenekab278de2010-01-28 23:39:18 +00004401bool
Ted Kremenek02087932010-07-16 02:11:22 +00004402CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00004403 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00004404 const char *startSpecifier,
4405 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004406 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00004407 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004408 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00004409
Ted Kremenek6cd69422010-07-19 22:01:06 +00004410 if (FS.consumesDataArgument()) {
4411 if (atFirstArg) {
4412 atFirstArg = false;
4413 usesPositionalArgs = FS.usesPositionalArg();
4414 }
4415 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004416 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
4417 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00004418 return false;
4419 }
Ted Kremenek5739de72010-01-29 01:06:55 +00004420 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004421
Ted Kremenekd1668192010-02-27 01:41:03 +00004422 // First check if the field width, precision, and conversion specifier
4423 // have matching data arguments.
4424 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
4425 startSpecifier, specifierLen)) {
4426 return false;
4427 }
4428
4429 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
4430 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00004431 return false;
4432 }
4433
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004434 if (!CS.consumesDataArgument()) {
4435 // FIXME: Technically specifying a precision or field width here
4436 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00004437 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004438 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004439
Ted Kremenek4a49d982010-02-26 19:18:41 +00004440 // Consume the argument.
4441 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00004442 if (argIndex < NumDataArgs) {
4443 // The check to see if the argIndex is valid will come later.
4444 // We set the bit here because we may exit early from this
4445 // function if we encounter some other error.
4446 CoveredArgs.set(argIndex);
4447 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00004448
Dimitry Andric6b5ed342015-02-19 22:32:33 +00004449 // FreeBSD kernel extensions.
4450 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
4451 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
4452 // We need at least two arguments.
4453 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
4454 return false;
4455
4456 // Claim the second argument.
4457 CoveredArgs.set(argIndex + 1);
4458
4459 // Type check the first argument (int for %b, pointer for %D)
4460 const Expr *Ex = getDataArg(argIndex);
4461 const analyze_printf::ArgType &AT =
4462 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
4463 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
4464 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
4465 EmitFormatDiagnostic(
4466 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4467 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
4468 << false << Ex->getSourceRange(),
4469 Ex->getLocStart(), /*IsStringLocation*/false,
4470 getSpecifierRange(startSpecifier, specifierLen));
4471
4472 // Type check the second argument (char * for both %b and %D)
4473 Ex = getDataArg(argIndex + 1);
4474 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
4475 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
4476 EmitFormatDiagnostic(
4477 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4478 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
4479 << false << Ex->getSourceRange(),
4480 Ex->getLocStart(), /*IsStringLocation*/false,
4481 getSpecifierRange(startSpecifier, specifierLen));
4482
4483 return true;
4484 }
4485
Ted Kremenek4a49d982010-02-26 19:18:41 +00004486 // Check for using an Objective-C specific conversion specifier
4487 // in a non-ObjC literal.
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004488 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00004489 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
4490 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00004491 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004492
Tom Careb49ec692010-06-17 19:00:27 +00004493 // Check for invalid use of field width
4494 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00004495 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00004496 startSpecifier, specifierLen);
4497 }
4498
4499 // Check for invalid use of precision
4500 if (!FS.hasValidPrecision()) {
4501 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
4502 startSpecifier, specifierLen);
4503 }
4504
4505 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00004506 if (!FS.hasValidThousandsGroupingPrefix())
4507 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00004508 if (!FS.hasValidLeadingZeros())
4509 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
4510 if (!FS.hasValidPlusPrefix())
4511 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00004512 if (!FS.hasValidSpacePrefix())
4513 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00004514 if (!FS.hasValidAlternativeForm())
4515 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
4516 if (!FS.hasValidLeftJustified())
4517 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
4518
4519 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00004520 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
4521 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
4522 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00004523 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
4524 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
4525 startSpecifier, specifierLen);
4526
4527 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00004528 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00004529 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4530 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00004531 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004532 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00004533 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004534 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4535 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00004536
Jordan Rose92303592012-09-08 04:00:03 +00004537 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
4538 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
4539
Ted Kremenek9fcd8302010-01-29 01:43:31 +00004540 // The remaining checks depend on the data arguments.
4541 if (HasVAListArg)
4542 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004543
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004544 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00004545 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004546
Jordan Rose58bbe422012-07-19 18:10:08 +00004547 const Expr *Arg = getDataArg(argIndex);
4548 if (!Arg)
4549 return true;
4550
4551 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00004552}
4553
Jordan Roseaee34382012-09-05 22:56:26 +00004554static bool requiresParensToAddCast(const Expr *E) {
4555 // FIXME: We should have a general way to reason about operator
4556 // precedence and whether parens are actually needed here.
4557 // Take care of a few common cases where they aren't.
4558 const Expr *Inside = E->IgnoreImpCasts();
4559 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
4560 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
4561
4562 switch (Inside->getStmtClass()) {
4563 case Stmt::ArraySubscriptExprClass:
4564 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004565 case Stmt::CharacterLiteralClass:
4566 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004567 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004568 case Stmt::FloatingLiteralClass:
4569 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004570 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004571 case Stmt::ObjCArrayLiteralClass:
4572 case Stmt::ObjCBoolLiteralExprClass:
4573 case Stmt::ObjCBoxedExprClass:
4574 case Stmt::ObjCDictionaryLiteralClass:
4575 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004576 case Stmt::ObjCIvarRefExprClass:
4577 case Stmt::ObjCMessageExprClass:
4578 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004579 case Stmt::ObjCStringLiteralClass:
4580 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004581 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004582 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004583 case Stmt::UnaryOperatorClass:
4584 return false;
4585 default:
4586 return true;
4587 }
4588}
4589
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004590static std::pair<QualType, StringRef>
4591shouldNotPrintDirectly(const ASTContext &Context,
4592 QualType IntendedTy,
4593 const Expr *E) {
4594 // Use a 'while' to peel off layers of typedefs.
4595 QualType TyTy = IntendedTy;
4596 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
4597 StringRef Name = UserTy->getDecl()->getName();
4598 QualType CastTy = llvm::StringSwitch<QualType>(Name)
4599 .Case("NSInteger", Context.LongTy)
4600 .Case("NSUInteger", Context.UnsignedLongTy)
4601 .Case("SInt32", Context.IntTy)
4602 .Case("UInt32", Context.UnsignedIntTy)
4603 .Default(QualType());
4604
4605 if (!CastTy.isNull())
4606 return std::make_pair(CastTy, Name);
4607
4608 TyTy = UserTy->desugar();
4609 }
4610
4611 // Strip parens if necessary.
4612 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
4613 return shouldNotPrintDirectly(Context,
4614 PE->getSubExpr()->getType(),
4615 PE->getSubExpr());
4616
4617 // If this is a conditional expression, then its result type is constructed
4618 // via usual arithmetic conversions and thus there might be no necessary
4619 // typedef sugar there. Recurse to operands to check for NSInteger &
4620 // Co. usage condition.
4621 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
4622 QualType TrueTy, FalseTy;
4623 StringRef TrueName, FalseName;
4624
4625 std::tie(TrueTy, TrueName) =
4626 shouldNotPrintDirectly(Context,
4627 CO->getTrueExpr()->getType(),
4628 CO->getTrueExpr());
4629 std::tie(FalseTy, FalseName) =
4630 shouldNotPrintDirectly(Context,
4631 CO->getFalseExpr()->getType(),
4632 CO->getFalseExpr());
4633
4634 if (TrueTy == FalseTy)
4635 return std::make_pair(TrueTy, TrueName);
4636 else if (TrueTy.isNull())
4637 return std::make_pair(FalseTy, FalseName);
4638 else if (FalseTy.isNull())
4639 return std::make_pair(TrueTy, TrueName);
4640 }
4641
4642 return std::make_pair(QualType(), StringRef());
4643}
4644
Richard Smith55ce3522012-06-25 20:30:08 +00004645bool
4646CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
4647 const char *StartSpecifier,
4648 unsigned SpecifierLen,
4649 const Expr *E) {
4650 using namespace analyze_format_string;
4651 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004652 // Now type check the data expression that matches the
4653 // format specifier.
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004654 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
4655 ObjCContext);
Jordan Rose22b74712012-09-05 22:56:19 +00004656 if (!AT.isValid())
4657 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00004658
Jordan Rose598ec092012-12-05 18:44:40 +00004659 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00004660 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
4661 ExprTy = TET->getUnderlyingExpr()->getType();
4662 }
4663
Seth Cantrellb4802962015-03-04 03:12:10 +00004664 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
4665
4666 if (match == analyze_printf::ArgType::Match) {
Jordan Rose22b74712012-09-05 22:56:19 +00004667 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00004668 }
Jordan Rose98709982012-06-04 22:48:57 +00004669
Jordan Rose22b74712012-09-05 22:56:19 +00004670 // Look through argument promotions for our error message's reported type.
4671 // This includes the integral and floating promotions, but excludes array
4672 // and function pointer decay; seeing that an argument intended to be a
4673 // string has type 'char [6]' is probably more confusing than 'char *'.
4674 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
4675 if (ICE->getCastKind() == CK_IntegralCast ||
4676 ICE->getCastKind() == CK_FloatingCast) {
4677 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00004678 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00004679
4680 // Check if we didn't match because of an implicit cast from a 'char'
4681 // or 'short' to an 'int'. This is done because printf is a varargs
4682 // function.
4683 if (ICE->getType() == S.Context.IntTy ||
4684 ICE->getType() == S.Context.UnsignedIntTy) {
4685 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00004686 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00004687 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00004688 }
Jordan Rose98709982012-06-04 22:48:57 +00004689 }
Jordan Rose598ec092012-12-05 18:44:40 +00004690 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
4691 // Special case for 'a', which has type 'int' in C.
4692 // Note, however, that we do /not/ want to treat multibyte constants like
4693 // 'MooV' as characters! This form is deprecated but still exists.
4694 if (ExprTy == S.Context.IntTy)
4695 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
4696 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00004697 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004698
Jordan Rosebc53ed12014-05-31 04:12:14 +00004699 // Look through enums to their underlying type.
4700 bool IsEnum = false;
4701 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
4702 ExprTy = EnumTy->getDecl()->getIntegerType();
4703 IsEnum = true;
4704 }
4705
Jordan Rose0e5badd2012-12-05 18:44:49 +00004706 // %C in an Objective-C context prints a unichar, not a wchar_t.
4707 // If the argument is an integer of some kind, believe the %C and suggest
4708 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00004709 QualType IntendedTy = ExprTy;
Jordan Rose0e5badd2012-12-05 18:44:49 +00004710 if (ObjCContext &&
4711 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
4712 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
4713 !ExprTy->isCharType()) {
4714 // 'unichar' is defined as a typedef of unsigned short, but we should
4715 // prefer using the typedef if it is visible.
4716 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00004717
4718 // While we are here, check if the value is an IntegerLiteral that happens
4719 // to be within the valid range.
4720 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
4721 const llvm::APInt &V = IL->getValue();
4722 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
4723 return true;
4724 }
4725
Jordan Rose0e5badd2012-12-05 18:44:49 +00004726 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
4727 Sema::LookupOrdinaryName);
4728 if (S.LookupName(Result, S.getCurScope())) {
4729 NamedDecl *ND = Result.getFoundDecl();
4730 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
4731 if (TD->getUnderlyingType() == IntendedTy)
4732 IntendedTy = S.Context.getTypedefType(TD);
4733 }
4734 }
4735 }
4736
4737 // Special-case some of Darwin's platform-independence types by suggesting
4738 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004739 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00004740 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004741 QualType CastTy;
4742 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
4743 if (!CastTy.isNull()) {
4744 IntendedTy = CastTy;
4745 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00004746 }
4747 }
4748
Jordan Rose22b74712012-09-05 22:56:19 +00004749 // We may be able to offer a FixItHint if it is a supported type.
4750 PrintfSpecifier fixedFS = FS;
Jordan Roseaee34382012-09-05 22:56:26 +00004751 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose22b74712012-09-05 22:56:19 +00004752 S.Context, ObjCContext);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004753
Jordan Rose22b74712012-09-05 22:56:19 +00004754 if (success) {
4755 // Get the fix string from the fixed format specifier
4756 SmallString<16> buf;
4757 llvm::raw_svector_ostream os(buf);
4758 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004759
Jordan Roseaee34382012-09-05 22:56:26 +00004760 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
4761
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004762 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Daniel Jasperad8d8492015-03-04 14:18:20 +00004763 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4764 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
4765 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4766 }
Jordan Rose0e5badd2012-12-05 18:44:49 +00004767 // In this case, the specifier is wrong and should be changed to match
4768 // the argument.
Daniel Jasperad8d8492015-03-04 14:18:20 +00004769 EmitFormatDiagnostic(S.PDiag(diag)
4770 << AT.getRepresentativeTypeName(S.Context)
4771 << IntendedTy << IsEnum << E->getSourceRange(),
4772 E->getLocStart(),
4773 /*IsStringLocation*/ false, SpecRange,
4774 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00004775 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00004776 // The canonical type for formatting this value is different from the
4777 // actual type of the expression. (This occurs, for example, with Darwin's
4778 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
4779 // should be printed as 'long' for 64-bit compatibility.)
4780 // Rather than emitting a normal format/argument mismatch, we want to
4781 // add a cast to the recommended type (and correct the format string
4782 // if necessary).
4783 SmallString<16> CastBuf;
4784 llvm::raw_svector_ostream CastFix(CastBuf);
4785 CastFix << "(";
4786 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
4787 CastFix << ")";
4788
4789 SmallVector<FixItHint,4> Hints;
4790 if (!AT.matchesType(S.Context, IntendedTy))
4791 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
4792
4793 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
4794 // If there's already a cast present, just replace it.
4795 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
4796 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
4797
4798 } else if (!requiresParensToAddCast(E)) {
4799 // If the expression has high enough precedence,
4800 // just write the C-style cast.
4801 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
4802 CastFix.str()));
4803 } else {
4804 // Otherwise, add parens around the expression as well as the cast.
4805 CastFix << "(";
4806 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
4807 CastFix.str()));
4808
Alp Tokerb6cc5922014-05-03 03:45:55 +00004809 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00004810 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
4811 }
4812
Jordan Rose0e5badd2012-12-05 18:44:49 +00004813 if (ShouldNotPrintDirectly) {
4814 // The expression has a type that should not be printed directly.
4815 // We extract the name from the typedef because we don't want to show
4816 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004817 StringRef Name;
4818 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
4819 Name = TypedefTy->getDecl()->getName();
4820 else
4821 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00004822 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00004823 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00004824 << E->getSourceRange(),
4825 E->getLocStart(), /*IsStringLocation=*/false,
4826 SpecRange, Hints);
4827 } else {
4828 // In this case, the expression could be printed using a different
4829 // specifier, but we've decided that the specifier is probably correct
4830 // and we should cast instead. Just use the normal warning message.
4831 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00004832 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4833 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00004834 << E->getSourceRange(),
4835 E->getLocStart(), /*IsStringLocation*/false,
4836 SpecRange, Hints);
4837 }
Jordan Roseaee34382012-09-05 22:56:26 +00004838 }
Jordan Rose22b74712012-09-05 22:56:19 +00004839 } else {
4840 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
4841 SpecifierLen);
4842 // Since the warning for passing non-POD types to variadic functions
4843 // was deferred until now, we emit a warning for non-POD
4844 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00004845 switch (S.isValidVarArgType(ExprTy)) {
4846 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00004847 case Sema::VAK_ValidInCXX11: {
4848 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4849 if (match == analyze_printf::ArgType::NoMatchPedantic) {
4850 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4851 }
Richard Smithd7293d72013-08-05 18:49:43 +00004852
Seth Cantrellb4802962015-03-04 03:12:10 +00004853 EmitFormatDiagnostic(
4854 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
4855 << IsEnum << CSR << E->getSourceRange(),
4856 E->getLocStart(), /*IsStringLocation*/ false, CSR);
4857 break;
4858 }
Richard Smithd7293d72013-08-05 18:49:43 +00004859 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00004860 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00004861 EmitFormatDiagnostic(
4862 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004863 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00004864 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00004865 << CallType
4866 << AT.getRepresentativeTypeName(S.Context)
4867 << CSR
4868 << E->getSourceRange(),
4869 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00004870 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00004871 break;
4872
4873 case Sema::VAK_Invalid:
4874 if (ExprTy->isObjCObjectType())
4875 EmitFormatDiagnostic(
4876 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
4877 << S.getLangOpts().CPlusPlus11
4878 << ExprTy
4879 << CallType
4880 << AT.getRepresentativeTypeName(S.Context)
4881 << CSR
4882 << E->getSourceRange(),
4883 E->getLocStart(), /*IsStringLocation*/false, CSR);
4884 else
4885 // FIXME: If this is an initializer list, suggest removing the braces
4886 // or inserting a cast to the target type.
4887 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
4888 << isa<InitListExpr>(E) << ExprTy << CallType
4889 << AT.getRepresentativeTypeName(S.Context)
4890 << E->getSourceRange();
4891 break;
4892 }
4893
4894 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
4895 "format string specifier index out of range");
4896 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004897 }
4898
Ted Kremenekab278de2010-01-28 23:39:18 +00004899 return true;
4900}
4901
Ted Kremenek02087932010-07-16 02:11:22 +00004902//===--- CHECK: Scanf format string checking ------------------------------===//
4903
4904namespace {
4905class CheckScanfHandler : public CheckFormatHandler {
4906public:
4907 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
4908 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004909 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004910 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004911 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00004912 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004913 llvm::SmallBitVector &CheckedVarArgs,
4914 UncoveredArgHandler &UncoveredArg)
Richard Smithd7293d72013-08-05 18:49:43 +00004915 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
4916 numDataArgs, beg, hasVAListArg,
4917 Args, formatIdx, inFunctionCall, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004918 CheckedVarArgs, UncoveredArg)
Jordan Rose3e0ec582012-07-19 18:10:23 +00004919 {}
Ted Kremenek02087932010-07-16 02:11:22 +00004920
4921 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
4922 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004923 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00004924
4925 bool HandleInvalidScanfConversionSpecifier(
4926 const analyze_scanf::ScanfSpecifier &FS,
4927 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004928 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00004929
Craig Toppere14c0f82014-03-12 04:55:44 +00004930 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00004931};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004932} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00004933
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00004934void CheckScanfHandler::HandleIncompleteScanList(const char *start,
4935 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004936 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
4937 getLocationOfByte(end), /*IsStringLocation*/true,
4938 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00004939}
4940
Ted Kremenekce815422010-07-19 21:25:57 +00004941bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
4942 const analyze_scanf::ScanfSpecifier &FS,
4943 const char *startSpecifier,
4944 unsigned specifierLen) {
4945
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004946 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00004947 FS.getConversionSpecifier();
4948
4949 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
4950 getLocationOfByte(CS.getStart()),
4951 startSpecifier, specifierLen,
4952 CS.getStart(), CS.getLength());
4953}
4954
Ted Kremenek02087932010-07-16 02:11:22 +00004955bool CheckScanfHandler::HandleScanfSpecifier(
4956 const analyze_scanf::ScanfSpecifier &FS,
4957 const char *startSpecifier,
4958 unsigned specifierLen) {
Ted Kremenek02087932010-07-16 02:11:22 +00004959 using namespace analyze_scanf;
4960 using namespace analyze_format_string;
4961
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004962 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00004963
Ted Kremenek6cd69422010-07-19 22:01:06 +00004964 // Handle case where '%' and '*' don't consume an argument. These shouldn't
4965 // be used to decide if we are using positional arguments consistently.
4966 if (FS.consumesDataArgument()) {
4967 if (atFirstArg) {
4968 atFirstArg = false;
4969 usesPositionalArgs = FS.usesPositionalArg();
4970 }
4971 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004972 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
4973 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00004974 return false;
4975 }
Ted Kremenek02087932010-07-16 02:11:22 +00004976 }
4977
4978 // Check if the field with is non-zero.
4979 const OptionalAmount &Amt = FS.getFieldWidth();
4980 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
4981 if (Amt.getConstantAmount() == 0) {
4982 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
4983 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00004984 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
4985 getLocationOfByte(Amt.getStart()),
4986 /*IsStringLocation*/true, R,
4987 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00004988 }
4989 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004990
Ted Kremenek02087932010-07-16 02:11:22 +00004991 if (!FS.consumesDataArgument()) {
4992 // FIXME: Technically specifying a precision or field width here
4993 // makes no sense. Worth issuing a warning at some point.
4994 return true;
4995 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004996
Ted Kremenek02087932010-07-16 02:11:22 +00004997 // Consume the argument.
4998 unsigned argIndex = FS.getArgIndex();
4999 if (argIndex < NumDataArgs) {
5000 // The check to see if the argIndex is valid will come later.
5001 // We set the bit here because we may exit early from this
5002 // function if we encounter some other error.
5003 CoveredArgs.set(argIndex);
5004 }
Seth Cantrellb4802962015-03-04 03:12:10 +00005005
Ted Kremenek4407ea42010-07-20 20:04:47 +00005006 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00005007 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00005008 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5009 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00005010 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00005011 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00005012 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00005013 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5014 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005015
Jordan Rose92303592012-09-08 04:00:03 +00005016 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
5017 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
5018
Ted Kremenek02087932010-07-16 02:11:22 +00005019 // The remaining checks depend on the data arguments.
5020 if (HasVAListArg)
5021 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00005022
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005023 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00005024 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00005025
Hans Wennborgb1a5e092011-12-10 13:20:11 +00005026 // Check that the argument type matches the format specifier.
5027 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00005028 if (!Ex)
5029 return true;
5030
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00005031 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00005032
5033 if (!AT.isValid()) {
5034 return true;
5035 }
5036
Seth Cantrellb4802962015-03-04 03:12:10 +00005037 analyze_format_string::ArgType::MatchKind match =
5038 AT.matchesType(S.Context, Ex->getType());
Seth Cantrell79340072015-03-04 05:58:08 +00005039 if (match == analyze_format_string::ArgType::Match) {
5040 return true;
5041 }
Seth Cantrellb4802962015-03-04 03:12:10 +00005042
Seth Cantrell79340072015-03-04 05:58:08 +00005043 ScanfSpecifier fixedFS = FS;
5044 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
5045 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00005046
Seth Cantrell79340072015-03-04 05:58:08 +00005047 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
5048 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
5049 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
5050 }
Hans Wennborgb1a5e092011-12-10 13:20:11 +00005051
Seth Cantrell79340072015-03-04 05:58:08 +00005052 if (success) {
5053 // Get the fix string from the fixed format specifier.
5054 SmallString<128> buf;
5055 llvm::raw_svector_ostream os(buf);
5056 fixedFS.toString(os);
5057
5058 EmitFormatDiagnostic(
5059 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
5060 << Ex->getType() << false << Ex->getSourceRange(),
5061 Ex->getLocStart(),
5062 /*IsStringLocation*/ false,
5063 getSpecifierRange(startSpecifier, specifierLen),
5064 FixItHint::CreateReplacement(
5065 getSpecifierRange(startSpecifier, specifierLen), os.str()));
5066 } else {
5067 EmitFormatDiagnostic(S.PDiag(diag)
5068 << AT.getRepresentativeTypeName(S.Context)
5069 << Ex->getType() << false << Ex->getSourceRange(),
5070 Ex->getLocStart(),
5071 /*IsStringLocation*/ false,
5072 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00005073 }
5074
Ted Kremenek02087932010-07-16 02:11:22 +00005075 return true;
5076}
5077
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005078static void CheckFormatString(Sema &S, const StringLiteral *FExpr,
5079 const Expr *OrigFormatExpr,
5080 ArrayRef<const Expr *> Args,
5081 bool HasVAListArg, unsigned format_idx,
5082 unsigned firstDataArg,
5083 Sema::FormatStringType Type,
5084 bool inFunctionCall,
5085 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005086 llvm::SmallBitVector &CheckedVarArgs,
5087 UncoveredArgHandler &UncoveredArg) {
Ted Kremenekab278de2010-01-28 23:39:18 +00005088 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00005089 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005090 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005091 S, inFunctionCall, Args[format_idx],
5092 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00005093 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00005094 return;
5095 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005096
Ted Kremenekab278de2010-01-28 23:39:18 +00005097 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005098 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00005099 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00005100 // Account for cases where the string literal is truncated in a declaration.
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005101 const ConstantArrayType *T =
5102 S.Context.getAsConstantArrayType(FExpr->getType());
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00005103 assert(T && "String literal not of constant array type!");
5104 size_t TypeSize = T->getSize().getZExtValue();
5105 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005106 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00005107
5108 // Emit a warning if the string literal is truncated and does not contain an
5109 // embedded null character.
5110 if (TypeSize <= StrRef.size() &&
5111 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
5112 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005113 S, inFunctionCall, Args[format_idx],
5114 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00005115 FExpr->getLocStart(),
5116 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
5117 return;
5118 }
5119
Ted Kremenekab278de2010-01-28 23:39:18 +00005120 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00005121 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005122 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005123 S, inFunctionCall, Args[format_idx],
5124 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00005125 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00005126 return;
5127 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005128
5129 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
5130 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSTrace) {
5131 CheckPrintfHandler H(S, FExpr, OrigFormatExpr, firstDataArg,
5132 numDataArgs, (Type == Sema::FST_NSString ||
5133 Type == Sema::FST_OSTrace),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005134 Str, HasVAListArg, Args, format_idx,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005135 inFunctionCall, CallType, CheckedVarArgs,
5136 UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005137
Hans Wennborg23926bd2011-12-15 10:25:47 +00005138 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005139 S.getLangOpts(),
5140 S.Context.getTargetInfo(),
5141 Type == Sema::FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00005142 H.DoneProcessing();
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005143 } else if (Type == Sema::FST_Scanf) {
5144 CheckScanfHandler H(S, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005145 Str, HasVAListArg, Args, format_idx,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005146 inFunctionCall, CallType, CheckedVarArgs,
5147 UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005148
Hans Wennborg23926bd2011-12-15 10:25:47 +00005149 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005150 S.getLangOpts(),
5151 S.Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00005152 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005153 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00005154}
5155
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00005156bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
5157 // Str - The format string. NOTE: this is NOT null-terminated!
5158 StringRef StrRef = FExpr->getString();
5159 const char *Str = StrRef.data();
5160 // Account for cases where the string literal is truncated in a declaration.
5161 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
5162 assert(T && "String literal not of constant array type!");
5163 size_t TypeSize = T->getSize().getZExtValue();
5164 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
5165 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
5166 getLangOpts(),
5167 Context.getTargetInfo());
5168}
5169
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005170//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
5171
5172// Returns the related absolute value function that is larger, of 0 if one
5173// does not exist.
5174static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
5175 switch (AbsFunction) {
5176 default:
5177 return 0;
5178
5179 case Builtin::BI__builtin_abs:
5180 return Builtin::BI__builtin_labs;
5181 case Builtin::BI__builtin_labs:
5182 return Builtin::BI__builtin_llabs;
5183 case Builtin::BI__builtin_llabs:
5184 return 0;
5185
5186 case Builtin::BI__builtin_fabsf:
5187 return Builtin::BI__builtin_fabs;
5188 case Builtin::BI__builtin_fabs:
5189 return Builtin::BI__builtin_fabsl;
5190 case Builtin::BI__builtin_fabsl:
5191 return 0;
5192
5193 case Builtin::BI__builtin_cabsf:
5194 return Builtin::BI__builtin_cabs;
5195 case Builtin::BI__builtin_cabs:
5196 return Builtin::BI__builtin_cabsl;
5197 case Builtin::BI__builtin_cabsl:
5198 return 0;
5199
5200 case Builtin::BIabs:
5201 return Builtin::BIlabs;
5202 case Builtin::BIlabs:
5203 return Builtin::BIllabs;
5204 case Builtin::BIllabs:
5205 return 0;
5206
5207 case Builtin::BIfabsf:
5208 return Builtin::BIfabs;
5209 case Builtin::BIfabs:
5210 return Builtin::BIfabsl;
5211 case Builtin::BIfabsl:
5212 return 0;
5213
5214 case Builtin::BIcabsf:
5215 return Builtin::BIcabs;
5216 case Builtin::BIcabs:
5217 return Builtin::BIcabsl;
5218 case Builtin::BIcabsl:
5219 return 0;
5220 }
5221}
5222
5223// Returns the argument type of the absolute value function.
5224static QualType getAbsoluteValueArgumentType(ASTContext &Context,
5225 unsigned AbsType) {
5226 if (AbsType == 0)
5227 return QualType();
5228
5229 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
5230 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
5231 if (Error != ASTContext::GE_None)
5232 return QualType();
5233
5234 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
5235 if (!FT)
5236 return QualType();
5237
5238 if (FT->getNumParams() != 1)
5239 return QualType();
5240
5241 return FT->getParamType(0);
5242}
5243
5244// Returns the best absolute value function, or zero, based on type and
5245// current absolute value function.
5246static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
5247 unsigned AbsFunctionKind) {
5248 unsigned BestKind = 0;
5249 uint64_t ArgSize = Context.getTypeSize(ArgType);
5250 for (unsigned Kind = AbsFunctionKind; Kind != 0;
5251 Kind = getLargerAbsoluteValueFunction(Kind)) {
5252 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
5253 if (Context.getTypeSize(ParamType) >= ArgSize) {
5254 if (BestKind == 0)
5255 BestKind = Kind;
5256 else if (Context.hasSameType(ParamType, ArgType)) {
5257 BestKind = Kind;
5258 break;
5259 }
5260 }
5261 }
5262 return BestKind;
5263}
5264
5265enum AbsoluteValueKind {
5266 AVK_Integer,
5267 AVK_Floating,
5268 AVK_Complex
5269};
5270
5271static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
5272 if (T->isIntegralOrEnumerationType())
5273 return AVK_Integer;
5274 if (T->isRealFloatingType())
5275 return AVK_Floating;
5276 if (T->isAnyComplexType())
5277 return AVK_Complex;
5278
5279 llvm_unreachable("Type not integer, floating, or complex");
5280}
5281
5282// Changes the absolute value function to a different type. Preserves whether
5283// the function is a builtin.
5284static unsigned changeAbsFunction(unsigned AbsKind,
5285 AbsoluteValueKind ValueKind) {
5286 switch (ValueKind) {
5287 case AVK_Integer:
5288 switch (AbsKind) {
5289 default:
5290 return 0;
5291 case Builtin::BI__builtin_fabsf:
5292 case Builtin::BI__builtin_fabs:
5293 case Builtin::BI__builtin_fabsl:
5294 case Builtin::BI__builtin_cabsf:
5295 case Builtin::BI__builtin_cabs:
5296 case Builtin::BI__builtin_cabsl:
5297 return Builtin::BI__builtin_abs;
5298 case Builtin::BIfabsf:
5299 case Builtin::BIfabs:
5300 case Builtin::BIfabsl:
5301 case Builtin::BIcabsf:
5302 case Builtin::BIcabs:
5303 case Builtin::BIcabsl:
5304 return Builtin::BIabs;
5305 }
5306 case AVK_Floating:
5307 switch (AbsKind) {
5308 default:
5309 return 0;
5310 case Builtin::BI__builtin_abs:
5311 case Builtin::BI__builtin_labs:
5312 case Builtin::BI__builtin_llabs:
5313 case Builtin::BI__builtin_cabsf:
5314 case Builtin::BI__builtin_cabs:
5315 case Builtin::BI__builtin_cabsl:
5316 return Builtin::BI__builtin_fabsf;
5317 case Builtin::BIabs:
5318 case Builtin::BIlabs:
5319 case Builtin::BIllabs:
5320 case Builtin::BIcabsf:
5321 case Builtin::BIcabs:
5322 case Builtin::BIcabsl:
5323 return Builtin::BIfabsf;
5324 }
5325 case AVK_Complex:
5326 switch (AbsKind) {
5327 default:
5328 return 0;
5329 case Builtin::BI__builtin_abs:
5330 case Builtin::BI__builtin_labs:
5331 case Builtin::BI__builtin_llabs:
5332 case Builtin::BI__builtin_fabsf:
5333 case Builtin::BI__builtin_fabs:
5334 case Builtin::BI__builtin_fabsl:
5335 return Builtin::BI__builtin_cabsf;
5336 case Builtin::BIabs:
5337 case Builtin::BIlabs:
5338 case Builtin::BIllabs:
5339 case Builtin::BIfabsf:
5340 case Builtin::BIfabs:
5341 case Builtin::BIfabsl:
5342 return Builtin::BIcabsf;
5343 }
5344 }
5345 llvm_unreachable("Unable to convert function");
5346}
5347
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00005348static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005349 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
5350 if (!FnInfo)
5351 return 0;
5352
5353 switch (FDecl->getBuiltinID()) {
5354 default:
5355 return 0;
5356 case Builtin::BI__builtin_abs:
5357 case Builtin::BI__builtin_fabs:
5358 case Builtin::BI__builtin_fabsf:
5359 case Builtin::BI__builtin_fabsl:
5360 case Builtin::BI__builtin_labs:
5361 case Builtin::BI__builtin_llabs:
5362 case Builtin::BI__builtin_cabs:
5363 case Builtin::BI__builtin_cabsf:
5364 case Builtin::BI__builtin_cabsl:
5365 case Builtin::BIabs:
5366 case Builtin::BIlabs:
5367 case Builtin::BIllabs:
5368 case Builtin::BIfabs:
5369 case Builtin::BIfabsf:
5370 case Builtin::BIfabsl:
5371 case Builtin::BIcabs:
5372 case Builtin::BIcabsf:
5373 case Builtin::BIcabsl:
5374 return FDecl->getBuiltinID();
5375 }
5376 llvm_unreachable("Unknown Builtin type");
5377}
5378
5379// If the replacement is valid, emit a note with replacement function.
5380// Additionally, suggest including the proper header if not already included.
5381static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00005382 unsigned AbsKind, QualType ArgType) {
5383 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00005384 const char *HeaderName = nullptr;
5385 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00005386 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
5387 FunctionName = "std::abs";
5388 if (ArgType->isIntegralOrEnumerationType()) {
5389 HeaderName = "cstdlib";
5390 } else if (ArgType->isRealFloatingType()) {
5391 HeaderName = "cmath";
5392 } else {
5393 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005394 }
Richard Trieubeffb832014-04-15 23:47:53 +00005395
5396 // Lookup all std::abs
5397 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00005398 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00005399 R.suppressDiagnostics();
5400 S.LookupQualifiedName(R, Std);
5401
5402 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005403 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00005404 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
5405 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
5406 } else {
5407 FDecl = dyn_cast<FunctionDecl>(I);
5408 }
5409 if (!FDecl)
5410 continue;
5411
5412 // Found std::abs(), check that they are the right ones.
5413 if (FDecl->getNumParams() != 1)
5414 continue;
5415
5416 // Check that the parameter type can handle the argument.
5417 QualType ParamType = FDecl->getParamDecl(0)->getType();
5418 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
5419 S.Context.getTypeSize(ArgType) <=
5420 S.Context.getTypeSize(ParamType)) {
5421 // Found a function, don't need the header hint.
5422 EmitHeaderHint = false;
5423 break;
5424 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005425 }
Richard Trieubeffb832014-04-15 23:47:53 +00005426 }
5427 } else {
Eric Christopher02d5d862015-08-06 01:01:12 +00005428 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
Richard Trieubeffb832014-04-15 23:47:53 +00005429 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
5430
5431 if (HeaderName) {
5432 DeclarationName DN(&S.Context.Idents.get(FunctionName));
5433 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
5434 R.suppressDiagnostics();
5435 S.LookupName(R, S.getCurScope());
5436
5437 if (R.isSingleResult()) {
5438 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
5439 if (FD && FD->getBuiltinID() == AbsKind) {
5440 EmitHeaderHint = false;
5441 } else {
5442 return;
5443 }
5444 } else if (!R.empty()) {
5445 return;
5446 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005447 }
5448 }
5449
5450 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00005451 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005452
Richard Trieubeffb832014-04-15 23:47:53 +00005453 if (!HeaderName)
5454 return;
5455
5456 if (!EmitHeaderHint)
5457 return;
5458
Alp Toker5d96e0a2014-07-11 20:53:51 +00005459 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
5460 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00005461}
5462
5463static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
5464 if (!FDecl)
5465 return false;
5466
5467 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
5468 return false;
5469
5470 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
5471
5472 while (ND && ND->isInlineNamespace()) {
5473 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005474 }
Richard Trieubeffb832014-04-15 23:47:53 +00005475
5476 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
5477 return false;
5478
5479 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
5480 return false;
5481
5482 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005483}
5484
5485// Warn when using the wrong abs() function.
5486void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
5487 const FunctionDecl *FDecl,
5488 IdentifierInfo *FnInfo) {
5489 if (Call->getNumArgs() != 1)
5490 return;
5491
5492 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieubeffb832014-04-15 23:47:53 +00005493 bool IsStdAbs = IsFunctionStdAbs(FDecl);
5494 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005495 return;
5496
5497 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
5498 QualType ParamType = Call->getArg(0)->getType();
5499
Alp Toker5d96e0a2014-07-11 20:53:51 +00005500 // Unsigned types cannot be negative. Suggest removing the absolute value
5501 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005502 if (ArgType->isUnsignedIntegerType()) {
Richard Trieubeffb832014-04-15 23:47:53 +00005503 const char *FunctionName =
Eric Christopher02d5d862015-08-06 01:01:12 +00005504 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005505 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
5506 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00005507 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005508 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
5509 return;
5510 }
5511
David Majnemer7f77eb92015-11-15 03:04:34 +00005512 // Taking the absolute value of a pointer is very suspicious, they probably
5513 // wanted to index into an array, dereference a pointer, call a function, etc.
5514 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
5515 unsigned DiagType = 0;
5516 if (ArgType->isFunctionType())
5517 DiagType = 1;
5518 else if (ArgType->isArrayType())
5519 DiagType = 2;
5520
5521 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
5522 return;
5523 }
5524
Richard Trieubeffb832014-04-15 23:47:53 +00005525 // std::abs has overloads which prevent most of the absolute value problems
5526 // from occurring.
5527 if (IsStdAbs)
5528 return;
5529
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005530 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
5531 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
5532
5533 // The argument and parameter are the same kind. Check if they are the right
5534 // size.
5535 if (ArgValueKind == ParamValueKind) {
5536 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
5537 return;
5538
5539 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
5540 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
5541 << FDecl << ArgType << ParamType;
5542
5543 if (NewAbsKind == 0)
5544 return;
5545
5546 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00005547 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005548 return;
5549 }
5550
5551 // ArgValueKind != ParamValueKind
5552 // The wrong type of absolute value function was used. Attempt to find the
5553 // proper one.
5554 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
5555 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
5556 if (NewAbsKind == 0)
5557 return;
5558
5559 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
5560 << FDecl << ParamValueKind << ArgValueKind;
5561
5562 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00005563 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005564}
5565
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005566//===--- CHECK: Standard memory functions ---------------------------------===//
5567
Nico Weber0e6daef2013-12-26 23:38:39 +00005568/// \brief Takes the expression passed to the size_t parameter of functions
5569/// such as memcmp, strncat, etc and warns if it's a comparison.
5570///
5571/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
5572static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
5573 IdentifierInfo *FnName,
5574 SourceLocation FnLoc,
5575 SourceLocation RParenLoc) {
5576 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
5577 if (!Size)
5578 return false;
5579
5580 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
5581 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
5582 return false;
5583
Nico Weber0e6daef2013-12-26 23:38:39 +00005584 SourceRange SizeRange = Size->getSourceRange();
5585 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
5586 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00005587 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00005588 << FnName << FixItHint::CreateInsertion(
5589 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00005590 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00005591 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00005592 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00005593 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
5594 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00005595
5596 return true;
5597}
5598
Reid Kleckner5fb5b122014-06-27 23:58:21 +00005599/// \brief Determine whether the given type is or contains a dynamic class type
5600/// (e.g., whether it has a vtable).
5601static const CXXRecordDecl *getContainedDynamicClass(QualType T,
5602 bool &IsContained) {
5603 // Look through array types while ignoring qualifiers.
5604 const Type *Ty = T->getBaseElementTypeUnsafe();
5605 IsContained = false;
5606
5607 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
5608 RD = RD ? RD->getDefinition() : nullptr;
5609 if (!RD)
5610 return nullptr;
5611
5612 if (RD->isDynamicClass())
5613 return RD;
5614
5615 // Check all the fields. If any bases were dynamic, the class is dynamic.
5616 // It's impossible for a class to transitively contain itself by value, so
5617 // infinite recursion is impossible.
5618 for (auto *FD : RD->fields()) {
5619 bool SubContained;
5620 if (const CXXRecordDecl *ContainedRD =
5621 getContainedDynamicClass(FD->getType(), SubContained)) {
5622 IsContained = true;
5623 return ContainedRD;
5624 }
5625 }
5626
5627 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00005628}
5629
Chandler Carruth889ed862011-06-21 23:04:20 +00005630/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005631/// otherwise returns NULL.
Nico Weberc44b35e2015-03-21 17:37:46 +00005632static const Expr *getSizeOfExprArg(const Expr *E) {
Nico Weberc5e73862011-06-14 16:14:58 +00005633 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005634 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
5635 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
5636 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00005637
Craig Topperc3ec1492014-05-26 06:22:03 +00005638 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005639}
5640
Chandler Carruth889ed862011-06-21 23:04:20 +00005641/// \brief If E is a sizeof expression, returns its argument type.
Nico Weberc44b35e2015-03-21 17:37:46 +00005642static QualType getSizeOfArgType(const Expr *E) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005643 if (const UnaryExprOrTypeTraitExpr *SizeOf =
5644 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
5645 if (SizeOf->getKind() == clang::UETT_SizeOf)
5646 return SizeOf->getTypeOfArgument();
5647
5648 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00005649}
5650
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005651/// \brief Check for dangerous or invalid arguments to memset().
5652///
Chandler Carruthac687262011-06-03 06:23:57 +00005653/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00005654/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
5655/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005656///
5657/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00005658void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00005659 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00005660 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00005661 assert(BId != 0);
5662
Ted Kremenekb5fabb22011-04-28 01:38:02 +00005663 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00005664 // we have enough arguments, and if not, abort further checking.
Anna Zaks22122702012-01-17 00:37:07 +00005665 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00005666 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00005667 return;
5668
Anna Zaks22122702012-01-17 00:37:07 +00005669 unsigned LastArg = (BId == Builtin::BImemset ||
5670 BId == Builtin::BIstrndup ? 1 : 2);
5671 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00005672 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005673
Nico Weber0e6daef2013-12-26 23:38:39 +00005674 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
5675 Call->getLocStart(), Call->getRParenLoc()))
5676 return;
5677
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005678 // We have special checking when the length is a sizeof expression.
5679 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
5680 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
5681 llvm::FoldingSetNodeID SizeOfArgID;
5682
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005683 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
5684 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00005685 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005686
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005687 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00005688 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005689 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00005690 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00005691
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005692 // Never warn about void type pointers. This can be used to suppress
5693 // false positives.
5694 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005695 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005696
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005697 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
5698 // actually comparing the expressions for equality. Because computing the
5699 // expression IDs can be expensive, we only do this if the diagnostic is
5700 // enabled.
5701 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00005702 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
5703 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005704 // We only compute IDs for expressions if the warning is enabled, and
5705 // cache the sizeof arg's ID.
5706 if (SizeOfArgID == llvm::FoldingSetNodeID())
5707 SizeOfArg->Profile(SizeOfArgID, Context, true);
5708 llvm::FoldingSetNodeID DestID;
5709 Dest->Profile(DestID, Context, true);
5710 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00005711 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
5712 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005713 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00005714 StringRef ReadableName = FnName->getName();
5715
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005716 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00005717 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005718 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00005719 if (!PointeeTy->isIncompleteType() &&
5720 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005721 ActionIdx = 2; // If the pointee's size is sizeof(char),
5722 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00005723
5724 // If the function is defined as a builtin macro, do not show macro
5725 // expansion.
5726 SourceLocation SL = SizeOfArg->getExprLoc();
5727 SourceRange DSR = Dest->getSourceRange();
5728 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00005729 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00005730
5731 if (SM.isMacroArgExpansion(SL)) {
5732 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
5733 SL = SM.getSpellingLoc(SL);
5734 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
5735 SM.getSpellingLoc(DSR.getEnd()));
5736 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
5737 SM.getSpellingLoc(SSR.getEnd()));
5738 }
5739
Anna Zaksd08d9152012-05-30 23:14:52 +00005740 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005741 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00005742 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00005743 << PointeeTy
5744 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00005745 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00005746 << SSR);
5747 DiagRuntimeBehavior(SL, SizeOfArg,
5748 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
5749 << ActionIdx
5750 << SSR);
5751
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005752 break;
5753 }
5754 }
5755
5756 // Also check for cases where the sizeof argument is the exact same
5757 // type as the memory argument, and where it points to a user-defined
5758 // record type.
5759 if (SizeOfArgTy != QualType()) {
5760 if (PointeeTy->isRecordType() &&
5761 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
5762 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
5763 PDiag(diag::warn_sizeof_pointer_type_memaccess)
5764 << FnName << SizeOfArgTy << ArgIdx
5765 << PointeeTy << Dest->getSourceRange()
5766 << LenExpr->getSourceRange());
5767 break;
5768 }
Nico Weberc5e73862011-06-14 16:14:58 +00005769 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00005770 } else if (DestTy->isArrayType()) {
5771 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00005772 }
Nico Weberc5e73862011-06-14 16:14:58 +00005773
Nico Weberc44b35e2015-03-21 17:37:46 +00005774 if (PointeeTy == QualType())
5775 continue;
Anna Zaks22122702012-01-17 00:37:07 +00005776
Nico Weberc44b35e2015-03-21 17:37:46 +00005777 // Always complain about dynamic classes.
5778 bool IsContained;
5779 if (const CXXRecordDecl *ContainedRD =
5780 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00005781
Nico Weberc44b35e2015-03-21 17:37:46 +00005782 unsigned OperationType = 0;
5783 // "overwritten" if we're warning about the destination for any call
5784 // but memcmp; otherwise a verb appropriate to the call.
5785 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
5786 if (BId == Builtin::BImemcpy)
5787 OperationType = 1;
5788 else if(BId == Builtin::BImemmove)
5789 OperationType = 2;
5790 else if (BId == Builtin::BImemcmp)
5791 OperationType = 3;
5792 }
5793
John McCall31168b02011-06-15 23:02:42 +00005794 DiagRuntimeBehavior(
5795 Dest->getExprLoc(), Dest,
Nico Weberc44b35e2015-03-21 17:37:46 +00005796 PDiag(diag::warn_dyn_class_memaccess)
5797 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
5798 << FnName << IsContained << ContainedRD << OperationType
5799 << Call->getCallee()->getSourceRange());
5800 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
5801 BId != Builtin::BImemset)
5802 DiagRuntimeBehavior(
5803 Dest->getExprLoc(), Dest,
5804 PDiag(diag::warn_arc_object_memaccess)
5805 << ArgIdx << FnName << PointeeTy
5806 << Call->getCallee()->getSourceRange());
5807 else
5808 continue;
5809
5810 DiagRuntimeBehavior(
5811 Dest->getExprLoc(), Dest,
5812 PDiag(diag::note_bad_memaccess_silence)
5813 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
5814 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005815 }
5816}
5817
Ted Kremenek6865f772011-08-18 20:55:45 +00005818// A little helper routine: ignore addition and subtraction of integer literals.
5819// This intentionally does not ignore all integer constant expressions because
5820// we don't want to remove sizeof().
5821static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
5822 Ex = Ex->IgnoreParenCasts();
5823
5824 for (;;) {
5825 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
5826 if (!BO || !BO->isAdditiveOp())
5827 break;
5828
5829 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
5830 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
5831
5832 if (isa<IntegerLiteral>(RHS))
5833 Ex = LHS;
5834 else if (isa<IntegerLiteral>(LHS))
5835 Ex = RHS;
5836 else
5837 break;
5838 }
5839
5840 return Ex;
5841}
5842
Anna Zaks13b08572012-08-08 21:42:23 +00005843static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
5844 ASTContext &Context) {
5845 // Only handle constant-sized or VLAs, but not flexible members.
5846 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
5847 // Only issue the FIXIT for arrays of size > 1.
5848 if (CAT->getSize().getSExtValue() <= 1)
5849 return false;
5850 } else if (!Ty->isVariableArrayType()) {
5851 return false;
5852 }
5853 return true;
5854}
5855
Ted Kremenek6865f772011-08-18 20:55:45 +00005856// Warn if the user has made the 'size' argument to strlcpy or strlcat
5857// be the size of the source, instead of the destination.
5858void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
5859 IdentifierInfo *FnName) {
5860
5861 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00005862 unsigned NumArgs = Call->getNumArgs();
5863 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00005864 return;
5865
5866 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
5867 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00005868 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00005869
5870 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
5871 Call->getLocStart(), Call->getRParenLoc()))
5872 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00005873
5874 // Look for 'strlcpy(dst, x, sizeof(x))'
5875 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
5876 CompareWithSrc = Ex;
5877 else {
5878 // Look for 'strlcpy(dst, x, strlen(x))'
5879 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00005880 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
5881 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00005882 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
5883 }
5884 }
5885
5886 if (!CompareWithSrc)
5887 return;
5888
5889 // Determine if the argument to sizeof/strlen is equal to the source
5890 // argument. In principle there's all kinds of things you could do
5891 // here, for instance creating an == expression and evaluating it with
5892 // EvaluateAsBooleanCondition, but this uses a more direct technique:
5893 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
5894 if (!SrcArgDRE)
5895 return;
5896
5897 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
5898 if (!CompareWithSrcDRE ||
5899 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
5900 return;
5901
5902 const Expr *OriginalSizeArg = Call->getArg(2);
5903 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
5904 << OriginalSizeArg->getSourceRange() << FnName;
5905
5906 // Output a FIXIT hint if the destination is an array (rather than a
5907 // pointer to an array). This could be enhanced to handle some
5908 // pointers if we know the actual size, like if DstArg is 'array+2'
5909 // we could say 'sizeof(array)-2'.
5910 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00005911 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00005912 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00005913
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00005914 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00005915 llvm::raw_svector_ostream OS(sizeString);
5916 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00005917 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00005918 OS << ")";
5919
5920 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
5921 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
5922 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00005923}
5924
Anna Zaks314cd092012-02-01 19:08:57 +00005925/// Check if two expressions refer to the same declaration.
5926static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
5927 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
5928 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
5929 return D1->getDecl() == D2->getDecl();
5930 return false;
5931}
5932
5933static const Expr *getStrlenExprArg(const Expr *E) {
5934 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
5935 const FunctionDecl *FD = CE->getDirectCallee();
5936 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00005937 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00005938 return CE->getArg(0)->IgnoreParenCasts();
5939 }
Craig Topperc3ec1492014-05-26 06:22:03 +00005940 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00005941}
5942
5943// Warn on anti-patterns as the 'size' argument to strncat.
5944// The correct size argument should look like following:
5945// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
5946void Sema::CheckStrncatArguments(const CallExpr *CE,
5947 IdentifierInfo *FnName) {
5948 // Don't crash if the user has the wrong number of arguments.
5949 if (CE->getNumArgs() < 3)
5950 return;
5951 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
5952 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
5953 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
5954
Nico Weber0e6daef2013-12-26 23:38:39 +00005955 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
5956 CE->getRParenLoc()))
5957 return;
5958
Anna Zaks314cd092012-02-01 19:08:57 +00005959 // Identify common expressions, which are wrongly used as the size argument
5960 // to strncat and may lead to buffer overflows.
5961 unsigned PatternType = 0;
5962 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
5963 // - sizeof(dst)
5964 if (referToTheSameDecl(SizeOfArg, DstArg))
5965 PatternType = 1;
5966 // - sizeof(src)
5967 else if (referToTheSameDecl(SizeOfArg, SrcArg))
5968 PatternType = 2;
5969 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
5970 if (BE->getOpcode() == BO_Sub) {
5971 const Expr *L = BE->getLHS()->IgnoreParenCasts();
5972 const Expr *R = BE->getRHS()->IgnoreParenCasts();
5973 // - sizeof(dst) - strlen(dst)
5974 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
5975 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
5976 PatternType = 1;
5977 // - sizeof(src) - (anything)
5978 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
5979 PatternType = 2;
5980 }
5981 }
5982
5983 if (PatternType == 0)
5984 return;
5985
Anna Zaks5069aa32012-02-03 01:27:37 +00005986 // Generate the diagnostic.
5987 SourceLocation SL = LenArg->getLocStart();
5988 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00005989 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00005990
5991 // If the function is defined as a builtin macro, do not show macro expansion.
5992 if (SM.isMacroArgExpansion(SL)) {
5993 SL = SM.getSpellingLoc(SL);
5994 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
5995 SM.getSpellingLoc(SR.getEnd()));
5996 }
5997
Anna Zaks13b08572012-08-08 21:42:23 +00005998 // Check if the destination is an array (rather than a pointer to an array).
5999 QualType DstTy = DstArg->getType();
6000 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
6001 Context);
6002 if (!isKnownSizeArray) {
6003 if (PatternType == 1)
6004 Diag(SL, diag::warn_strncat_wrong_size) << SR;
6005 else
6006 Diag(SL, diag::warn_strncat_src_size) << SR;
6007 return;
6008 }
6009
Anna Zaks314cd092012-02-01 19:08:57 +00006010 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00006011 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00006012 else
Anna Zaks5069aa32012-02-03 01:27:37 +00006013 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00006014
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00006015 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00006016 llvm::raw_svector_ostream OS(sizeString);
6017 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00006018 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00006019 OS << ") - ";
6020 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00006021 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00006022 OS << ") - 1";
6023
Anna Zaks5069aa32012-02-03 01:27:37 +00006024 Diag(SL, diag::note_strncat_wrong_size)
6025 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00006026}
6027
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006028//===--- CHECK: Return Address of Stack Variable --------------------------===//
6029
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006030static const Expr *EvalVal(const Expr *E,
6031 SmallVectorImpl<const DeclRefExpr *> &refVars,
6032 const Decl *ParentDecl);
6033static const Expr *EvalAddr(const Expr *E,
6034 SmallVectorImpl<const DeclRefExpr *> &refVars,
6035 const Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006036
6037/// CheckReturnStackAddr - Check if a return statement returns the address
6038/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006039static void
6040CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
6041 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00006042
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006043 const Expr *stackE = nullptr;
6044 SmallVector<const DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006045
6046 // Perform checking for returned stack addresses, local blocks,
6047 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00006048 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006049 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006050 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00006051 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006052 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006053 }
6054
Craig Topperc3ec1492014-05-26 06:22:03 +00006055 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006056 return; // Nothing suspicious was found.
6057
6058 SourceLocation diagLoc;
6059 SourceRange diagRange;
6060 if (refVars.empty()) {
6061 diagLoc = stackE->getLocStart();
6062 diagRange = stackE->getSourceRange();
6063 } else {
6064 // We followed through a reference variable. 'stackE' contains the
6065 // problematic expression but we will warn at the return statement pointing
6066 // at the reference variable. We will later display the "trail" of
6067 // reference variables using notes.
6068 diagLoc = refVars[0]->getLocStart();
6069 diagRange = refVars[0]->getSourceRange();
6070 }
6071
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006072 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
6073 // address of local var
Craig Topperda7b27f2015-11-17 05:40:09 +00006074 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006075 << DR->getDecl()->getDeclName() << diagRange;
6076 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006077 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006078 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006079 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006080 } else { // local temporary.
Craig Topperda7b27f2015-11-17 05:40:09 +00006081 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
6082 << lhsType->isReferenceType() << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006083 }
6084
6085 // Display the "trail" of reference variables that we followed until we
6086 // found the problematic expression using notes.
6087 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006088 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006089 // If this var binds to another reference var, show the range of the next
6090 // var, otherwise the var binds to the problematic expression, in which case
6091 // show the range of the expression.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006092 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
6093 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006094 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
6095 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006096 }
6097}
6098
6099/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
6100/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006101/// to a location on the stack, a local block, an address of a label, or a
6102/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006103/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006104/// encounter a subexpression that (1) clearly does not lead to one of the
6105/// above problematic expressions (2) is something we cannot determine leads to
6106/// a problematic expression based on such local checking.
6107///
6108/// Both EvalAddr and EvalVal follow through reference variables to evaluate
6109/// the expression that they point to. Such variables are added to the
6110/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006111///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00006112/// EvalAddr processes expressions that are pointers that are used as
6113/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006114/// At the base case of the recursion is a check for the above problematic
6115/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006116///
6117/// This implementation handles:
6118///
6119/// * pointer-to-pointer casts
6120/// * implicit conversions from array references to pointers
6121/// * taking the address of fields
6122/// * arbitrary interplay between "&" and "*" operators
6123/// * pointer arithmetic from an address of a stack variable
6124/// * taking the address of an array element where the array is on the stack
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006125static const Expr *EvalAddr(const Expr *E,
6126 SmallVectorImpl<const DeclRefExpr *> &refVars,
6127 const Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006128 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00006129 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006130
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006131 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00006132 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00006133 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006134 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00006135 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00006136
Peter Collingbourne91147592011-04-15 00:35:48 +00006137 E = E->IgnoreParens();
6138
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006139 // Our "symbolic interpreter" is just a dispatch off the currently
6140 // viewed AST node. We then recursively traverse the AST by calling
6141 // EvalAddr and EvalVal appropriately.
6142 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006143 case Stmt::DeclRefExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006144 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006145
Richard Smith40f08eb2014-01-30 22:05:38 +00006146 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00006147 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00006148 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00006149
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006150 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006151 // If this is a reference variable, follow through to the expression that
6152 // it points to.
6153 if (V->hasLocalStorage() &&
6154 V->getType()->isReferenceType() && V->hasInit()) {
6155 // Add the reference variable to the "trail".
6156 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006157 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006158 }
6159
Craig Topperc3ec1492014-05-26 06:22:03 +00006160 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006161 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006162
Chris Lattner934edb22007-12-28 05:31:15 +00006163 case Stmt::UnaryOperatorClass: {
6164 // The only unary operator that make sense to handle here
6165 // is AddrOf. All others don't make sense as pointers.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006166 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00006167
John McCalle3027922010-08-25 11:45:40 +00006168 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006169 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006170 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006171 }
Mike Stump11289f42009-09-09 15:08:12 +00006172
Chris Lattner934edb22007-12-28 05:31:15 +00006173 case Stmt::BinaryOperatorClass: {
6174 // Handle pointer arithmetic. All other binary operators are not valid
6175 // in this context.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006176 const BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00006177 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00006178
John McCalle3027922010-08-25 11:45:40 +00006179 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00006180 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00006181
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006182 const Expr *Base = B->getLHS();
Chris Lattner934edb22007-12-28 05:31:15 +00006183
6184 // Determine which argument is the real pointer base. It could be
6185 // the RHS argument instead of the LHS.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006186 if (!Base->getType()->isPointerType())
6187 Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00006188
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006189 assert(Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006190 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00006191 }
Steve Naroff2752a172008-09-10 19:17:48 +00006192
Chris Lattner934edb22007-12-28 05:31:15 +00006193 // For conditional operators we need to see if either the LHS or RHS are
6194 // valid DeclRefExpr*s. If one of them is valid, we return it.
6195 case Stmt::ConditionalOperatorClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006196 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00006197
Chris Lattner934edb22007-12-28 05:31:15 +00006198 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006199 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006200 if (const Expr *LHSExpr = C->getLHS()) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006201 // In C++, we can have a throw-expression, which has 'void' type.
6202 if (!LHSExpr->getType()->isVoidType())
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006203 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00006204 return LHS;
6205 }
Chris Lattner934edb22007-12-28 05:31:15 +00006206
Douglas Gregor270b2ef2010-10-21 16:21:08 +00006207 // In C++, we can have a throw-expression, which has 'void' type.
6208 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00006209 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00006210
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006211 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00006212 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006213
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006214 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00006215 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006216 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00006217 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006218
6219 case Stmt::AddrLabelExprClass:
6220 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00006221
John McCall28fc7092011-11-10 05:35:25 +00006222 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006223 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
6224 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00006225
Ted Kremenekc3b4c522008-08-07 00:49:01 +00006226 // For casts, we need to handle conversions from arrays to
6227 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00006228 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00006229 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00006230 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00006231 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00006232 case Stmt::CXXStaticCastExprClass:
6233 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00006234 case Stmt::CXXConstCastExprClass:
6235 case Stmt::CXXReinterpretCastExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006236 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Eli Friedman8195ad72012-02-23 23:04:32 +00006237 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00006238 case CK_LValueToRValue:
6239 case CK_NoOp:
6240 case CK_BaseToDerived:
6241 case CK_DerivedToBase:
6242 case CK_UncheckedDerivedToBase:
6243 case CK_Dynamic:
6244 case CK_CPointerToObjCPointerCast:
6245 case CK_BlockPointerToObjCPointerCast:
6246 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006247 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00006248
6249 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006250 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00006251
Richard Trieudadefde2014-07-02 04:39:38 +00006252 case CK_BitCast:
6253 if (SubExpr->getType()->isAnyPointerType() ||
6254 SubExpr->getType()->isBlockPointerType() ||
6255 SubExpr->getType()->isObjCQualifiedIdType())
6256 return EvalAddr(SubExpr, refVars, ParentDecl);
6257 else
6258 return nullptr;
6259
Eli Friedman8195ad72012-02-23 23:04:32 +00006260 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00006261 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00006262 }
Chris Lattner934edb22007-12-28 05:31:15 +00006263 }
Mike Stump11289f42009-09-09 15:08:12 +00006264
Douglas Gregorfe314812011-06-21 17:03:29 +00006265 case Stmt::MaterializeTemporaryExprClass:
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006266 if (const Expr *Result =
6267 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
6268 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00006269 return Result;
Douglas Gregorfe314812011-06-21 17:03:29 +00006270 return E;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006271
Chris Lattner934edb22007-12-28 05:31:15 +00006272 // Everything else: we simply don't reason about them.
6273 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00006274 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00006275 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006276}
Mike Stump11289f42009-09-09 15:08:12 +00006277
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006278/// EvalVal - This function is complements EvalAddr in the mutual recursion.
6279/// See the comments for EvalAddr for more details.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006280static const Expr *EvalVal(const Expr *E,
6281 SmallVectorImpl<const DeclRefExpr *> &refVars,
6282 const Decl *ParentDecl) {
6283 do {
6284 // We should only be called for evaluating non-pointer expressions, or
6285 // expressions with a pointer type that are not used as references but
6286 // instead
6287 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00006288
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006289 // Our "symbolic interpreter" is just a dispatch off the currently
6290 // viewed AST node. We then recursively traverse the AST by calling
6291 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00006292
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006293 E = E->IgnoreParens();
6294 switch (E->getStmtClass()) {
6295 case Stmt::ImplicitCastExprClass: {
6296 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
6297 if (IE->getValueKind() == VK_LValue) {
6298 E = IE->getSubExpr();
6299 continue;
6300 }
Craig Topperc3ec1492014-05-26 06:22:03 +00006301 return nullptr;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006302 }
Richard Smith40f08eb2014-01-30 22:05:38 +00006303
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006304 case Stmt::ExprWithCleanupsClass:
6305 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
6306 ParentDecl);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006307
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006308 case Stmt::DeclRefExprClass: {
6309 // When we hit a DeclRefExpr we are looking at code that refers to a
6310 // variable's name. If it's not a reference variable we check if it has
6311 // local storage within the function, and if so, return the expression.
6312 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
6313
6314 // If we leave the immediate function, the lifetime isn't about to end.
6315 if (DR->refersToEnclosingVariableOrCapture())
6316 return nullptr;
6317
6318 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
6319 // Check if it refers to itself, e.g. "int& i = i;".
6320 if (V == ParentDecl)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006321 return DR;
6322
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006323 if (V->hasLocalStorage()) {
6324 if (!V->getType()->isReferenceType())
6325 return DR;
6326
6327 // Reference variable, follow through to the expression that
6328 // it points to.
6329 if (V->hasInit()) {
6330 // Add the reference variable to the "trail".
6331 refVars.push_back(DR);
6332 return EvalVal(V->getInit(), refVars, V);
6333 }
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006334 }
6335 }
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006336
6337 return nullptr;
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006338 }
Mike Stump11289f42009-09-09 15:08:12 +00006339
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006340 case Stmt::UnaryOperatorClass: {
6341 // The only unary operator that make sense to handle here
6342 // is Deref. All others don't resolve to a "name." This includes
6343 // handling all sorts of rvalues passed to a unary operator.
6344 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00006345
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006346 if (U->getOpcode() == UO_Deref)
6347 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Mike Stump11289f42009-09-09 15:08:12 +00006348
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006349 return nullptr;
6350 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006351
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006352 case Stmt::ArraySubscriptExprClass: {
6353 // Array subscripts are potential references to data on the stack. We
6354 // retrieve the DeclRefExpr* for the array variable if it indeed
6355 // has local storage.
Saleem Abdulrasoolcfd45532016-02-15 01:51:24 +00006356 const auto *ASE = cast<ArraySubscriptExpr>(E);
6357 if (ASE->isTypeDependent())
6358 return nullptr;
6359 return EvalAddr(ASE->getBase(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006360 }
Mike Stump11289f42009-09-09 15:08:12 +00006361
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006362 case Stmt::OMPArraySectionExprClass: {
6363 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
6364 ParentDecl);
6365 }
Mike Stump11289f42009-09-09 15:08:12 +00006366
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006367 case Stmt::ConditionalOperatorClass: {
6368 // For conditional operators we need to see if either the LHS or RHS are
6369 // non-NULL Expr's. If one is non-NULL, we return it.
6370 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Alexey Bataev1a3320e2015-08-25 14:24:04 +00006371
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006372 // Handle the GNU extension for missing LHS.
6373 if (const Expr *LHSExpr = C->getLHS()) {
6374 // In C++, we can have a throw-expression, which has 'void' type.
6375 if (!LHSExpr->getType()->isVoidType())
6376 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
6377 return LHS;
6378 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006379
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006380 // In C++, we can have a throw-expression, which has 'void' type.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006381 if (C->getRHS()->getType()->isVoidType())
6382 return nullptr;
6383
6384 return EvalVal(C->getRHS(), refVars, ParentDecl);
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006385 }
6386
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006387 // Accesses to members are potential references to data on the stack.
6388 case Stmt::MemberExprClass: {
6389 const MemberExpr *M = cast<MemberExpr>(E);
Anders Carlsson801c5c72007-11-30 19:04:31 +00006390
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006391 // Check for indirect access. We only want direct field accesses.
6392 if (M->isArrow())
6393 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00006394
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006395 // Check whether the member type is itself a reference, in which case
6396 // we're not going to refer to the member, but to what the member refers
6397 // to.
6398 if (M->getMemberDecl()->getType()->isReferenceType())
6399 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00006400
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006401 return EvalVal(M->getBase(), refVars, ParentDecl);
6402 }
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00006403
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006404 case Stmt::MaterializeTemporaryExprClass:
6405 if (const Expr *Result =
6406 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
6407 refVars, ParentDecl))
6408 return Result;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006409 return E;
6410
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006411 default:
6412 // Check that we don't return or take the address of a reference to a
6413 // temporary. This is only useful in C++.
6414 if (!E->isTypeDependent() && E->isRValue())
6415 return E;
6416
6417 // Everything else: we simply don't reason about them.
6418 return nullptr;
6419 }
6420 } while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006421}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006422
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006423void
6424Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
6425 SourceLocation ReturnLoc,
6426 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00006427 const AttrVec *Attrs,
6428 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006429 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
6430
6431 // Check if the return value is null but should not be.
Douglas Gregorb4866e82015-06-19 18:13:19 +00006432 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
6433 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
Benjamin Kramerae852a62014-02-23 14:34:50 +00006434 CheckNonNullExpr(*this, RetValExp))
6435 Diag(ReturnLoc, diag::warn_null_ret)
6436 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00006437
6438 // C++11 [basic.stc.dynamic.allocation]p4:
6439 // If an allocation function declared with a non-throwing
6440 // exception-specification fails to allocate storage, it shall return
6441 // a null pointer. Any other allocation function that fails to allocate
6442 // storage shall indicate failure only by throwing an exception [...]
6443 if (FD) {
6444 OverloadedOperatorKind Op = FD->getOverloadedOperator();
6445 if (Op == OO_New || Op == OO_Array_New) {
6446 const FunctionProtoType *Proto
6447 = FD->getType()->castAs<FunctionProtoType>();
6448 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
6449 CheckNonNullExpr(*this, RetValExp))
6450 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
6451 << FD << getLangOpts().CPlusPlus11;
6452 }
6453 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006454}
6455
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006456//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
6457
6458/// Check for comparisons of floating point operands using != and ==.
6459/// Issue a warning if these are no self-comparisons, as they are not likely
6460/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00006461void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00006462 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
6463 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006464
6465 // Special case: check for x == x (which is OK).
6466 // Do not emit warnings for such cases.
6467 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
6468 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
6469 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00006470 return;
Mike Stump11289f42009-09-09 15:08:12 +00006471
Ted Kremenekeda40e22007-11-29 00:59:04 +00006472 // Special case: check for comparisons against literals that can be exactly
6473 // represented by APFloat. In such cases, do not emit a warning. This
6474 // is a heuristic: often comparison against such literals are used to
6475 // detect if a value in a variable has not changed. This clearly can
6476 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00006477 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
6478 if (FLL->isExact())
6479 return;
6480 } else
6481 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
6482 if (FLR->isExact())
6483 return;
Mike Stump11289f42009-09-09 15:08:12 +00006484
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006485 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00006486 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00006487 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00006488 return;
Mike Stump11289f42009-09-09 15:08:12 +00006489
David Blaikie1f4ff152012-07-16 20:47:22 +00006490 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00006491 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00006492 return;
Mike Stump11289f42009-09-09 15:08:12 +00006493
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006494 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00006495 Diag(Loc, diag::warn_floatingpoint_eq)
6496 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006497}
John McCallca01b222010-01-04 23:21:16 +00006498
John McCall70aa5392010-01-06 05:24:50 +00006499//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
6500//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00006501
John McCall70aa5392010-01-06 05:24:50 +00006502namespace {
John McCallca01b222010-01-04 23:21:16 +00006503
John McCall70aa5392010-01-06 05:24:50 +00006504/// Structure recording the 'active' range of an integer-valued
6505/// expression.
6506struct IntRange {
6507 /// The number of bits active in the int.
6508 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00006509
John McCall70aa5392010-01-06 05:24:50 +00006510 /// True if the int is known not to have negative values.
6511 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00006512
John McCall70aa5392010-01-06 05:24:50 +00006513 IntRange(unsigned Width, bool NonNegative)
6514 : Width(Width), NonNegative(NonNegative)
6515 {}
John McCallca01b222010-01-04 23:21:16 +00006516
John McCall817d4af2010-11-10 23:38:19 +00006517 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00006518 static IntRange forBoolType() {
6519 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00006520 }
6521
John McCall817d4af2010-11-10 23:38:19 +00006522 /// Returns the range of an opaque value of the given integral type.
6523 static IntRange forValueOfType(ASTContext &C, QualType T) {
6524 return forValueOfCanonicalType(C,
6525 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00006526 }
6527
John McCall817d4af2010-11-10 23:38:19 +00006528 /// Returns the range of an opaque value of a canonical integral type.
6529 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00006530 assert(T->isCanonicalUnqualified());
6531
6532 if (const VectorType *VT = dyn_cast<VectorType>(T))
6533 T = VT->getElementType().getTypePtr();
6534 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
6535 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00006536 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
6537 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00006538
David Majnemer6a426652013-06-07 22:07:20 +00006539 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00006540 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00006541 EnumDecl *Enum = ET->getDecl();
6542 if (!Enum->isCompleteDefinition())
6543 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00006544
David Majnemer6a426652013-06-07 22:07:20 +00006545 unsigned NumPositive = Enum->getNumPositiveBits();
6546 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00006547
David Majnemer6a426652013-06-07 22:07:20 +00006548 if (NumNegative == 0)
6549 return IntRange(NumPositive, true/*NonNegative*/);
6550 else
6551 return IntRange(std::max(NumPositive + 1, NumNegative),
6552 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00006553 }
John McCall70aa5392010-01-06 05:24:50 +00006554
6555 const BuiltinType *BT = cast<BuiltinType>(T);
6556 assert(BT->isInteger());
6557
6558 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
6559 }
6560
John McCall817d4af2010-11-10 23:38:19 +00006561 /// Returns the "target" range of a canonical integral type, i.e.
6562 /// the range of values expressible in the type.
6563 ///
6564 /// This matches forValueOfCanonicalType except that enums have the
6565 /// full range of their type, not the range of their enumerators.
6566 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
6567 assert(T->isCanonicalUnqualified());
6568
6569 if (const VectorType *VT = dyn_cast<VectorType>(T))
6570 T = VT->getElementType().getTypePtr();
6571 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
6572 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00006573 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
6574 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00006575 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00006576 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00006577
6578 const BuiltinType *BT = cast<BuiltinType>(T);
6579 assert(BT->isInteger());
6580
6581 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
6582 }
6583
6584 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00006585 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00006586 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00006587 L.NonNegative && R.NonNegative);
6588 }
6589
John McCall817d4af2010-11-10 23:38:19 +00006590 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00006591 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00006592 return IntRange(std::min(L.Width, R.Width),
6593 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00006594 }
6595};
6596
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006597IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00006598 if (value.isSigned() && value.isNegative())
6599 return IntRange(value.getMinSignedBits(), false);
6600
6601 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00006602 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00006603
6604 // isNonNegative() just checks the sign bit without considering
6605 // signedness.
6606 return IntRange(value.getActiveBits(), true);
6607}
6608
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006609IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
6610 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00006611 if (result.isInt())
6612 return GetValueRange(C, result.getInt(), MaxWidth);
6613
6614 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00006615 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
6616 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
6617 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
6618 R = IntRange::join(R, El);
6619 }
John McCall70aa5392010-01-06 05:24:50 +00006620 return R;
6621 }
6622
6623 if (result.isComplexInt()) {
6624 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
6625 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
6626 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00006627 }
6628
6629 // This can happen with lossless casts to intptr_t of "based" lvalues.
6630 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00006631 // FIXME: The only reason we need to pass the type in here is to get
6632 // the sign right on this one case. It would be nice if APValue
6633 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006634 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00006635 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00006636}
John McCall70aa5392010-01-06 05:24:50 +00006637
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006638QualType GetExprType(const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00006639 QualType Ty = E->getType();
6640 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
6641 Ty = AtomicRHS->getValueType();
6642 return Ty;
6643}
6644
John McCall70aa5392010-01-06 05:24:50 +00006645/// Pseudo-evaluate the given integer expression, estimating the
6646/// range of values it might take.
6647///
6648/// \param MaxWidth - the width to which the value will be truncated
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006649IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00006650 E = E->IgnoreParens();
6651
6652 // Try a full evaluation first.
6653 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00006654 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00006655 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00006656
6657 // I think we only want to look through implicit casts here; if the
6658 // user has an explicit widening cast, we should treat the value as
6659 // being of the new, wider type.
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00006660 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00006661 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00006662 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
6663
Eli Friedmane6d33952013-07-08 20:20:06 +00006664 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00006665
George Burgess IVdf1ed002016-01-13 01:52:39 +00006666 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
6667 CE->getCastKind() == CK_BooleanToSignedIntegral;
John McCall2ce81ad2010-01-06 22:07:33 +00006668
John McCall70aa5392010-01-06 05:24:50 +00006669 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00006670 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00006671 return OutputTypeRange;
6672
6673 IntRange SubRange
6674 = GetExprRange(C, CE->getSubExpr(),
6675 std::min(MaxWidth, OutputTypeRange.Width));
6676
6677 // Bail out if the subexpr's range is as wide as the cast type.
6678 if (SubRange.Width >= OutputTypeRange.Width)
6679 return OutputTypeRange;
6680
6681 // Otherwise, we take the smaller width, and we're non-negative if
6682 // either the output type or the subexpr is.
6683 return IntRange(SubRange.Width,
6684 SubRange.NonNegative || OutputTypeRange.NonNegative);
6685 }
6686
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00006687 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00006688 // If we can fold the condition, just take that operand.
6689 bool CondResult;
6690 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
6691 return GetExprRange(C, CondResult ? CO->getTrueExpr()
6692 : CO->getFalseExpr(),
6693 MaxWidth);
6694
6695 // Otherwise, conservatively merge.
6696 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
6697 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
6698 return IntRange::join(L, R);
6699 }
6700
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00006701 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00006702 switch (BO->getOpcode()) {
6703
6704 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00006705 case BO_LAnd:
6706 case BO_LOr:
6707 case BO_LT:
6708 case BO_GT:
6709 case BO_LE:
6710 case BO_GE:
6711 case BO_EQ:
6712 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00006713 return IntRange::forBoolType();
6714
John McCallc3688382011-07-13 06:35:24 +00006715 // The type of the assignments is the type of the LHS, so the RHS
6716 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00006717 case BO_MulAssign:
6718 case BO_DivAssign:
6719 case BO_RemAssign:
6720 case BO_AddAssign:
6721 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00006722 case BO_XorAssign:
6723 case BO_OrAssign:
6724 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00006725 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00006726
John McCallc3688382011-07-13 06:35:24 +00006727 // Simple assignments just pass through the RHS, which will have
6728 // been coerced to the LHS type.
6729 case BO_Assign:
6730 // TODO: bitfields?
6731 return GetExprRange(C, BO->getRHS(), MaxWidth);
6732
John McCall70aa5392010-01-06 05:24:50 +00006733 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00006734 case BO_PtrMemD:
6735 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00006736 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006737
John McCall2ce81ad2010-01-06 22:07:33 +00006738 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00006739 case BO_And:
6740 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00006741 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
6742 GetExprRange(C, BO->getRHS(), MaxWidth));
6743
John McCall70aa5392010-01-06 05:24:50 +00006744 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00006745 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00006746 // ...except that we want to treat '1 << (blah)' as logically
6747 // positive. It's an important idiom.
6748 if (IntegerLiteral *I
6749 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
6750 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00006751 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00006752 return IntRange(R.Width, /*NonNegative*/ true);
6753 }
6754 }
6755 // fallthrough
6756
John McCalle3027922010-08-25 11:45:40 +00006757 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00006758 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006759
John McCall2ce81ad2010-01-06 22:07:33 +00006760 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00006761 case BO_Shr:
6762 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00006763 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
6764
6765 // If the shift amount is a positive constant, drop the width by
6766 // that much.
6767 llvm::APSInt shift;
6768 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
6769 shift.isNonNegative()) {
6770 unsigned zext = shift.getZExtValue();
6771 if (zext >= L.Width)
6772 L.Width = (L.NonNegative ? 0 : 1);
6773 else
6774 L.Width -= zext;
6775 }
6776
6777 return L;
6778 }
6779
6780 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00006781 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00006782 return GetExprRange(C, BO->getRHS(), MaxWidth);
6783
John McCall2ce81ad2010-01-06 22:07:33 +00006784 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00006785 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00006786 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00006787 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00006788 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006789
John McCall51431812011-07-14 22:39:48 +00006790 // The width of a division result is mostly determined by the size
6791 // of the LHS.
6792 case BO_Div: {
6793 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00006794 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00006795 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
6796
6797 // If the divisor is constant, use that.
6798 llvm::APSInt divisor;
6799 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
6800 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
6801 if (log2 >= L.Width)
6802 L.Width = (L.NonNegative ? 0 : 1);
6803 else
6804 L.Width = std::min(L.Width - log2, MaxWidth);
6805 return L;
6806 }
6807
6808 // Otherwise, just use the LHS's width.
6809 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
6810 return IntRange(L.Width, L.NonNegative && R.NonNegative);
6811 }
6812
6813 // The result of a remainder can't be larger than the result of
6814 // either side.
6815 case BO_Rem: {
6816 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00006817 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00006818 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
6819 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
6820
6821 IntRange meet = IntRange::meet(L, R);
6822 meet.Width = std::min(meet.Width, MaxWidth);
6823 return meet;
6824 }
6825
6826 // The default behavior is okay for these.
6827 case BO_Mul:
6828 case BO_Add:
6829 case BO_Xor:
6830 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00006831 break;
6832 }
6833
John McCall51431812011-07-14 22:39:48 +00006834 // The default case is to treat the operation as if it were closed
6835 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00006836 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
6837 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
6838 return IntRange::join(L, R);
6839 }
6840
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00006841 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00006842 switch (UO->getOpcode()) {
6843 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00006844 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00006845 return IntRange::forBoolType();
6846
6847 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00006848 case UO_Deref:
6849 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00006850 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006851
6852 default:
6853 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
6854 }
6855 }
6856
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00006857 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
Ted Kremeneka553fbf2013-10-14 18:55:27 +00006858 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
6859
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00006860 if (const auto *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00006861 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00006862 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00006863
Eli Friedmane6d33952013-07-08 20:20:06 +00006864 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006865}
John McCall263a48b2010-01-04 23:31:57 +00006866
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006867IntRange GetExprRange(ASTContext &C, const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00006868 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00006869}
6870
John McCall263a48b2010-01-04 23:31:57 +00006871/// Checks whether the given value, which currently has the given
6872/// source semantics, has the same value when coerced through the
6873/// target semantics.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006874bool IsSameFloatAfterCast(const llvm::APFloat &value,
6875 const llvm::fltSemantics &Src,
6876 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00006877 llvm::APFloat truncated = value;
6878
6879 bool ignored;
6880 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
6881 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
6882
6883 return truncated.bitwiseIsEqual(value);
6884}
6885
6886/// Checks whether the given value, which currently has the given
6887/// source semantics, has the same value when coerced through the
6888/// target semantics.
6889///
6890/// The value might be a vector of floats (or a complex number).
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006891bool IsSameFloatAfterCast(const APValue &value,
6892 const llvm::fltSemantics &Src,
6893 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00006894 if (value.isFloat())
6895 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
6896
6897 if (value.isVector()) {
6898 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
6899 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
6900 return false;
6901 return true;
6902 }
6903
6904 assert(value.isComplexFloat());
6905 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
6906 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
6907}
6908
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006909void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006910
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006911bool IsZero(Sema &S, Expr *E) {
Ted Kremenek6274be42010-09-23 21:43:44 +00006912 // Suppress cases where we are comparing against an enum constant.
6913 if (const DeclRefExpr *DR =
6914 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
6915 if (isa<EnumConstantDecl>(DR->getDecl()))
6916 return false;
6917
6918 // Suppress cases where the '0' value is expanded from a macro.
6919 if (E->getLocStart().isMacroID())
6920 return false;
6921
John McCallcc7e5bf2010-05-06 08:58:33 +00006922 llvm::APSInt Value;
6923 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
6924}
6925
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006926bool HasEnumType(Expr *E) {
John McCall2551c1b2010-10-06 00:25:24 +00006927 // Strip off implicit integral promotions.
6928 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00006929 if (ICE->getCastKind() != CK_IntegralCast &&
6930 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00006931 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00006932 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00006933 }
6934
6935 return E->getType()->isEnumeralType();
6936}
6937
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006938void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00006939 // Disable warning in template instantiations.
6940 if (!S.ActiveTemplateInstantiations.empty())
6941 return;
6942
John McCalle3027922010-08-25 11:45:40 +00006943 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00006944 if (E->isValueDependent())
6945 return;
6946
John McCalle3027922010-08-25 11:45:40 +00006947 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006948 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006949 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006950 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00006951 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006952 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006953 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006954 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00006955 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006956 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006957 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006958 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00006959 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006960 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006961 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006962 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
6963 }
6964}
6965
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006966void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
6967 Expr *Constant, Expr *Other,
6968 llvm::APSInt Value,
6969 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00006970 // Disable warning in template instantiations.
6971 if (!S.ActiveTemplateInstantiations.empty())
6972 return;
6973
Richard Trieu0f097742014-04-04 04:13:47 +00006974 // TODO: Investigate using GetExprRange() to get tighter bounds
6975 // on the bit ranges.
6976 QualType OtherT = Other->getType();
David Majnemer7800f1f2015-05-23 01:32:17 +00006977 if (const auto *AT = OtherT->getAs<AtomicType>())
Justin Bogner4f42fc42014-07-21 18:01:53 +00006978 OtherT = AT->getValueType();
Richard Trieu0f097742014-04-04 04:13:47 +00006979 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
6980 unsigned OtherWidth = OtherRange.Width;
6981
6982 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
6983
Richard Trieu560910c2012-11-14 22:50:24 +00006984 // 0 values are handled later by CheckTrivialUnsignedComparison().
Richard Trieu0f097742014-04-04 04:13:47 +00006985 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00006986 return;
6987
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006988 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00006989 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00006990
Richard Trieu0f097742014-04-04 04:13:47 +00006991 // Used for diagnostic printout.
6992 enum {
6993 LiteralConstant = 0,
6994 CXXBoolLiteralTrue,
6995 CXXBoolLiteralFalse
6996 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00006997
Richard Trieu0f097742014-04-04 04:13:47 +00006998 if (!OtherIsBooleanType) {
6999 QualType ConstantT = Constant->getType();
7000 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00007001
Richard Trieu0f097742014-04-04 04:13:47 +00007002 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
7003 return;
7004 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
7005 "comparison with non-integer type");
7006
7007 bool ConstantSigned = ConstantT->isSignedIntegerType();
7008 bool CommonSigned = CommonT->isSignedIntegerType();
7009
7010 bool EqualityOnly = false;
7011
7012 if (CommonSigned) {
7013 // The common type is signed, therefore no signed to unsigned conversion.
7014 if (!OtherRange.NonNegative) {
7015 // Check that the constant is representable in type OtherT.
7016 if (ConstantSigned) {
7017 if (OtherWidth >= Value.getMinSignedBits())
7018 return;
7019 } else { // !ConstantSigned
7020 if (OtherWidth >= Value.getActiveBits() + 1)
7021 return;
7022 }
7023 } else { // !OtherSigned
7024 // Check that the constant is representable in type OtherT.
7025 // Negative values are out of range.
7026 if (ConstantSigned) {
7027 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
7028 return;
7029 } else { // !ConstantSigned
7030 if (OtherWidth >= Value.getActiveBits())
7031 return;
7032 }
Richard Trieu560910c2012-11-14 22:50:24 +00007033 }
Richard Trieu0f097742014-04-04 04:13:47 +00007034 } else { // !CommonSigned
7035 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00007036 if (OtherWidth >= Value.getActiveBits())
7037 return;
Craig Toppercf360162014-06-18 05:13:11 +00007038 } else { // OtherSigned
7039 assert(!ConstantSigned &&
7040 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00007041 // Check to see if the constant is representable in OtherT.
7042 if (OtherWidth > Value.getActiveBits())
7043 return;
7044 // Check to see if the constant is equivalent to a negative value
7045 // cast to CommonT.
7046 if (S.Context.getIntWidth(ConstantT) ==
7047 S.Context.getIntWidth(CommonT) &&
7048 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
7049 return;
7050 // The constant value rests between values that OtherT can represent
7051 // after conversion. Relational comparison still works, but equality
7052 // comparisons will be tautological.
7053 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00007054 }
7055 }
Richard Trieu0f097742014-04-04 04:13:47 +00007056
7057 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
7058
7059 if (op == BO_EQ || op == BO_NE) {
7060 IsTrue = op == BO_NE;
7061 } else if (EqualityOnly) {
7062 return;
7063 } else if (RhsConstant) {
7064 if (op == BO_GT || op == BO_GE)
7065 IsTrue = !PositiveConstant;
7066 else // op == BO_LT || op == BO_LE
7067 IsTrue = PositiveConstant;
7068 } else {
7069 if (op == BO_LT || op == BO_LE)
7070 IsTrue = !PositiveConstant;
7071 else // op == BO_GT || op == BO_GE
7072 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00007073 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00007074 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00007075 // Other isKnownToHaveBooleanValue
7076 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
7077 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
7078 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
7079
7080 static const struct LinkedConditions {
7081 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
7082 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
7083 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
7084 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
7085 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
7086 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
7087
7088 } TruthTable = {
7089 // Constant on LHS. | Constant on RHS. |
7090 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
7091 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
7092 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
7093 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
7094 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
7095 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
7096 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
7097 };
7098
7099 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
7100
7101 enum ConstantValue ConstVal = Zero;
7102 if (Value.isUnsigned() || Value.isNonNegative()) {
7103 if (Value == 0) {
7104 LiteralOrBoolConstant =
7105 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
7106 ConstVal = Zero;
7107 } else if (Value == 1) {
7108 LiteralOrBoolConstant =
7109 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
7110 ConstVal = One;
7111 } else {
7112 LiteralOrBoolConstant = LiteralConstant;
7113 ConstVal = GT_One;
7114 }
7115 } else {
7116 ConstVal = LT_Zero;
7117 }
7118
7119 CompareBoolWithConstantResult CmpRes;
7120
7121 switch (op) {
7122 case BO_LT:
7123 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
7124 break;
7125 case BO_GT:
7126 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
7127 break;
7128 case BO_LE:
7129 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
7130 break;
7131 case BO_GE:
7132 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
7133 break;
7134 case BO_EQ:
7135 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
7136 break;
7137 case BO_NE:
7138 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
7139 break;
7140 default:
7141 CmpRes = Unkwn;
7142 break;
7143 }
7144
7145 if (CmpRes == AFals) {
7146 IsTrue = false;
7147 } else if (CmpRes == ATrue) {
7148 IsTrue = true;
7149 } else {
7150 return;
7151 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007152 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00007153
7154 // If this is a comparison to an enum constant, include that
7155 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00007156 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00007157 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
7158 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
7159
7160 SmallString<64> PrettySourceValue;
7161 llvm::raw_svector_ostream OS(PrettySourceValue);
7162 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00007163 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00007164 else
7165 OS << Value;
7166
Richard Trieu0f097742014-04-04 04:13:47 +00007167 S.DiagRuntimeBehavior(
7168 E->getOperatorLoc(), E,
7169 S.PDiag(diag::warn_out_of_range_compare)
7170 << OS.str() << LiteralOrBoolConstant
7171 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
7172 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007173}
7174
John McCallcc7e5bf2010-05-06 08:58:33 +00007175/// Analyze the operands of the given comparison. Implements the
7176/// fallback case from AnalyzeComparison.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007177void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00007178 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
7179 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00007180}
John McCall263a48b2010-01-04 23:31:57 +00007181
John McCallca01b222010-01-04 23:21:16 +00007182/// \brief Implements -Wsign-compare.
7183///
Richard Trieu82402a02011-09-15 21:56:47 +00007184/// \param E the binary operator to check for warnings
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007185void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007186 // The type the comparison is being performed in.
7187 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00007188
7189 // Only analyze comparison operators where both sides have been converted to
7190 // the same type.
7191 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
7192 return AnalyzeImpConvsInComparison(S, E);
7193
7194 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00007195 if (E->isValueDependent())
7196 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00007197
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007198 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
7199 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007200
7201 bool IsComparisonConstant = false;
7202
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00007203 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007204 // of 'true' or 'false'.
7205 if (T->isIntegralType(S.Context)) {
7206 llvm::APSInt RHSValue;
7207 bool IsRHSIntegralLiteral =
7208 RHS->isIntegerConstantExpr(RHSValue, S.Context);
7209 llvm::APSInt LHSValue;
7210 bool IsLHSIntegralLiteral =
7211 LHS->isIntegerConstantExpr(LHSValue, S.Context);
7212 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
7213 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
7214 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
7215 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
7216 else
7217 IsComparisonConstant =
7218 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00007219 } else if (!T->hasUnsignedIntegerRepresentation())
7220 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007221
John McCallcc7e5bf2010-05-06 08:58:33 +00007222 // We don't do anything special if this isn't an unsigned integral
7223 // comparison: we're only interested in integral comparisons, and
7224 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00007225 //
7226 // We also don't care about value-dependent expressions or expressions
7227 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007228 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00007229 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007230
John McCallcc7e5bf2010-05-06 08:58:33 +00007231 // Check to see if one of the (unmodified) operands is of different
7232 // signedness.
7233 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00007234 if (LHS->getType()->hasSignedIntegerRepresentation()) {
7235 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00007236 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00007237 signedOperand = LHS;
7238 unsignedOperand = RHS;
7239 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
7240 signedOperand = RHS;
7241 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00007242 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00007243 CheckTrivialUnsignedComparison(S, E);
7244 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00007245 }
7246
John McCallcc7e5bf2010-05-06 08:58:33 +00007247 // Otherwise, calculate the effective range of the signed operand.
7248 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00007249
John McCallcc7e5bf2010-05-06 08:58:33 +00007250 // Go ahead and analyze implicit conversions in the operands. Note
7251 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00007252 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
7253 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00007254
John McCallcc7e5bf2010-05-06 08:58:33 +00007255 // If the signed range is non-negative, -Wsign-compare won't fire,
7256 // but we should still check for comparisons which are always true
7257 // or false.
7258 if (signedRange.NonNegative)
7259 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00007260
7261 // For (in)equality comparisons, if the unsigned operand is a
7262 // constant which cannot collide with a overflowed signed operand,
7263 // then reinterpreting the signed operand as unsigned will not
7264 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00007265 if (E->isEqualityOp()) {
7266 unsigned comparisonWidth = S.Context.getIntWidth(T);
7267 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00007268
John McCallcc7e5bf2010-05-06 08:58:33 +00007269 // We should never be unable to prove that the unsigned operand is
7270 // non-negative.
7271 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
7272
7273 if (unsignedRange.Width < comparisonWidth)
7274 return;
7275 }
7276
Douglas Gregorbfb4a212012-05-01 01:53:49 +00007277 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
7278 S.PDiag(diag::warn_mixed_sign_comparison)
7279 << LHS->getType() << RHS->getType()
7280 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00007281}
7282
John McCall1f425642010-11-11 03:21:53 +00007283/// Analyzes an attempt to assign the given value to a bitfield.
7284///
7285/// Returns true if there was something fishy about the attempt.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007286bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
7287 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00007288 assert(Bitfield->isBitField());
7289 if (Bitfield->isInvalidDecl())
7290 return false;
7291
John McCalldeebbcf2010-11-11 05:33:51 +00007292 // White-list bool bitfields.
7293 if (Bitfield->getType()->isBooleanType())
7294 return false;
7295
Douglas Gregor789adec2011-02-04 13:09:01 +00007296 // Ignore value- or type-dependent expressions.
7297 if (Bitfield->getBitWidth()->isValueDependent() ||
7298 Bitfield->getBitWidth()->isTypeDependent() ||
7299 Init->isValueDependent() ||
7300 Init->isTypeDependent())
7301 return false;
7302
John McCall1f425642010-11-11 03:21:53 +00007303 Expr *OriginalInit = Init->IgnoreParenImpCasts();
7304
Richard Smith5fab0c92011-12-28 19:48:30 +00007305 llvm::APSInt Value;
7306 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00007307 return false;
7308
John McCall1f425642010-11-11 03:21:53 +00007309 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00007310 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00007311
7312 if (OriginalWidth <= FieldWidth)
7313 return false;
7314
Eli Friedmanc267a322012-01-26 23:11:39 +00007315 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00007316 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedmanc267a322012-01-26 23:11:39 +00007317 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00007318
Eli Friedmanc267a322012-01-26 23:11:39 +00007319 // Check whether the stored value is equal to the original value.
7320 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00007321 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00007322 return false;
7323
Eli Friedmanc267a322012-01-26 23:11:39 +00007324 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00007325 // therefore don't strictly fit into a signed bitfield of width 1.
7326 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00007327 return false;
7328
John McCall1f425642010-11-11 03:21:53 +00007329 std::string PrettyValue = Value.toString(10);
7330 std::string PrettyTrunc = TruncatedValue.toString(10);
7331
7332 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
7333 << PrettyValue << PrettyTrunc << OriginalInit->getType()
7334 << Init->getSourceRange();
7335
7336 return true;
7337}
7338
John McCalld2a53122010-11-09 23:24:47 +00007339/// Analyze the given simple or compound assignment for warning-worthy
7340/// operations.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007341void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00007342 // Just recurse on the LHS.
7343 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
7344
7345 // We want to recurse on the RHS as normal unless we're assigning to
7346 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00007347 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007348 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00007349 E->getOperatorLoc())) {
7350 // Recurse, ignoring any implicit conversions on the RHS.
7351 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
7352 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00007353 }
7354 }
7355
7356 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
7357}
7358
John McCall263a48b2010-01-04 23:31:57 +00007359/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007360void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
7361 SourceLocation CContext, unsigned diag,
7362 bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00007363 if (pruneControlFlow) {
7364 S.DiagRuntimeBehavior(E->getExprLoc(), E,
7365 S.PDiag(diag)
7366 << SourceType << T << E->getSourceRange()
7367 << SourceRange(CContext));
7368 return;
7369 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00007370 S.Diag(E->getExprLoc(), diag)
7371 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
7372}
7373
Chandler Carruth7f3654f2011-04-05 06:47:57 +00007374/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007375void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
7376 unsigned diag, bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00007377 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00007378}
7379
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00007380/// Diagnose an implicit cast from a literal expression. Does not warn when the
7381/// cast wouldn't lose information.
Chandler Carruth016ef402011-04-10 08:36:24 +00007382void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
7383 SourceLocation CContext) {
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00007384 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruth016ef402011-04-10 08:36:24 +00007385 bool isExact = false;
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00007386 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00007387 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
7388 T->hasUnsignedIntegerRepresentation());
7389 if (Value.convertToInteger(IntegerValue,
Chandler Carruth016ef402011-04-10 08:36:24 +00007390 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00007391 == llvm::APFloat::opOK && isExact)
Chandler Carruth016ef402011-04-10 08:36:24 +00007392 return;
7393
Eli Friedman07185912013-08-29 23:44:43 +00007394 // FIXME: Force the precision of the source value down so we don't print
7395 // digits which are usually useless (we don't really care here if we
7396 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
7397 // would automatically print the shortest representation, but it's a bit
7398 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00007399 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00007400 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
7401 precision = (precision * 59 + 195) / 196;
7402 Value.toString(PrettySourceValue, precision);
7403
David Blaikie9b88cc02012-05-15 17:18:27 +00007404 SmallString<16> PrettyTargetValue;
David Blaikie7555b6a2012-05-15 16:56:36 +00007405 if (T->isSpecificBuiltinType(BuiltinType::Bool))
Aaron Ballmandbc441e2015-12-30 14:26:07 +00007406 PrettyTargetValue = Value.isZero() ? "false" : "true";
David Blaikie7555b6a2012-05-15 16:56:36 +00007407 else
David Blaikie9b88cc02012-05-15 17:18:27 +00007408 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00007409
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00007410 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikie7555b6a2012-05-15 16:56:36 +00007411 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
7412 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruth016ef402011-04-10 08:36:24 +00007413}
7414
John McCall18a2c2c2010-11-09 22:22:12 +00007415std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
7416 if (!Range.Width) return "0";
7417
7418 llvm::APSInt ValueInRange = Value;
7419 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00007420 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00007421 return ValueInRange.toString(10);
7422}
7423
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007424bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00007425 if (!isa<ImplicitCastExpr>(Ex))
7426 return false;
7427
7428 Expr *InnerE = Ex->IgnoreParenImpCasts();
7429 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
7430 const Type *Source =
7431 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
7432 if (Target->isDependentType())
7433 return false;
7434
7435 const BuiltinType *FloatCandidateBT =
7436 dyn_cast<BuiltinType>(ToBool ? Source : Target);
7437 const Type *BoolCandidateType = ToBool ? Target : Source;
7438
7439 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
7440 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
7441}
7442
7443void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
7444 SourceLocation CC) {
7445 unsigned NumArgs = TheCall->getNumArgs();
7446 for (unsigned i = 0; i < NumArgs; ++i) {
7447 Expr *CurrA = TheCall->getArg(i);
7448 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
7449 continue;
7450
7451 bool IsSwapped = ((i > 0) &&
7452 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
7453 IsSwapped |= ((i < (NumArgs - 1)) &&
7454 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
7455 if (IsSwapped) {
7456 // Warn on this floating-point to bool conversion.
7457 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
7458 CurrA->getType(), CC,
7459 diag::warn_impcast_floating_point_to_bool);
7460 }
7461 }
7462}
7463
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007464void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) {
Richard Trieu5b993502014-10-15 03:42:06 +00007465 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
7466 E->getExprLoc()))
7467 return;
7468
Richard Trieu09d6b802016-01-08 23:35:06 +00007469 // Don't warn on functions which have return type nullptr_t.
7470 if (isa<CallExpr>(E))
7471 return;
7472
Richard Trieu5b993502014-10-15 03:42:06 +00007473 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
7474 const Expr::NullPointerConstantKind NullKind =
7475 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
7476 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
7477 return;
7478
7479 // Return if target type is a safe conversion.
7480 if (T->isAnyPointerType() || T->isBlockPointerType() ||
7481 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
7482 return;
7483
7484 SourceLocation Loc = E->getSourceRange().getBegin();
7485
Richard Trieu0a5e1662016-02-13 00:58:53 +00007486 // Venture through the macro stacks to get to the source of macro arguments.
7487 // The new location is a better location than the complete location that was
7488 // passed in.
7489 while (S.SourceMgr.isMacroArgExpansion(Loc))
7490 Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc);
7491
7492 while (S.SourceMgr.isMacroArgExpansion(CC))
7493 CC = S.SourceMgr.getImmediateMacroCallerLoc(CC);
7494
Richard Trieu5b993502014-10-15 03:42:06 +00007495 // __null is usually wrapped in a macro. Go up a macro if that is the case.
Richard Trieu0a5e1662016-02-13 00:58:53 +00007496 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
7497 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
7498 Loc, S.SourceMgr, S.getLangOpts());
7499 if (MacroName == "NULL")
7500 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
Richard Trieu5b993502014-10-15 03:42:06 +00007501 }
7502
7503 // Only warn if the null and context location are in the same macro expansion.
7504 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
7505 return;
7506
7507 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
7508 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
7509 << FixItHint::CreateReplacement(Loc,
7510 S.getFixItZeroLiteralForType(T, Loc));
7511}
7512
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007513void checkObjCArrayLiteral(Sema &S, QualType TargetType,
7514 ObjCArrayLiteral *ArrayLiteral);
7515void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
7516 ObjCDictionaryLiteral *DictionaryLiteral);
Douglas Gregor5054cb02015-07-07 03:58:22 +00007517
7518/// Check a single element within a collection literal against the
7519/// target element type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007520void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType,
7521 Expr *Element, unsigned ElementKind) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00007522 // Skip a bitcast to 'id' or qualified 'id'.
7523 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
7524 if (ICE->getCastKind() == CK_BitCast &&
7525 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
7526 Element = ICE->getSubExpr();
7527 }
7528
7529 QualType ElementType = Element->getType();
7530 ExprResult ElementResult(Element);
7531 if (ElementType->getAs<ObjCObjectPointerType>() &&
7532 S.CheckSingleAssignmentConstraints(TargetElementType,
7533 ElementResult,
7534 false, false)
7535 != Sema::Compatible) {
7536 S.Diag(Element->getLocStart(),
7537 diag::warn_objc_collection_literal_element)
7538 << ElementType << ElementKind << TargetElementType
7539 << Element->getSourceRange();
7540 }
7541
7542 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
7543 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
7544 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
7545 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
7546}
7547
7548/// Check an Objective-C array literal being converted to the given
7549/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007550void checkObjCArrayLiteral(Sema &S, QualType TargetType,
7551 ObjCArrayLiteral *ArrayLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00007552 if (!S.NSArrayDecl)
7553 return;
7554
7555 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
7556 if (!TargetObjCPtr)
7557 return;
7558
7559 if (TargetObjCPtr->isUnspecialized() ||
7560 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
7561 != S.NSArrayDecl->getCanonicalDecl())
7562 return;
7563
7564 auto TypeArgs = TargetObjCPtr->getTypeArgs();
7565 if (TypeArgs.size() != 1)
7566 return;
7567
7568 QualType TargetElementType = TypeArgs[0];
7569 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
7570 checkObjCCollectionLiteralElement(S, TargetElementType,
7571 ArrayLiteral->getElement(I),
7572 0);
7573 }
7574}
7575
7576/// Check an Objective-C dictionary literal being converted to the given
7577/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007578void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
7579 ObjCDictionaryLiteral *DictionaryLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00007580 if (!S.NSDictionaryDecl)
7581 return;
7582
7583 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
7584 if (!TargetObjCPtr)
7585 return;
7586
7587 if (TargetObjCPtr->isUnspecialized() ||
7588 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
7589 != S.NSDictionaryDecl->getCanonicalDecl())
7590 return;
7591
7592 auto TypeArgs = TargetObjCPtr->getTypeArgs();
7593 if (TypeArgs.size() != 2)
7594 return;
7595
7596 QualType TargetKeyType = TypeArgs[0];
7597 QualType TargetObjectType = TypeArgs[1];
7598 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
7599 auto Element = DictionaryLiteral->getKeyValueElement(I);
7600 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
7601 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
7602 }
7603}
7604
Richard Trieufc404c72016-02-05 23:02:38 +00007605// Helper function to filter out cases for constant width constant conversion.
7606// Don't warn on char array initialization or for non-decimal values.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007607bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
7608 SourceLocation CC) {
Richard Trieufc404c72016-02-05 23:02:38 +00007609 // If initializing from a constant, and the constant starts with '0',
7610 // then it is a binary, octal, or hexadecimal. Allow these constants
7611 // to fill all the bits, even if there is a sign change.
7612 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
7613 const char FirstLiteralCharacter =
7614 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
7615 if (FirstLiteralCharacter == '0')
7616 return false;
7617 }
7618
7619 // If the CC location points to a '{', and the type is char, then assume
7620 // assume it is an array initialization.
7621 if (CC.isValid() && T->isCharType()) {
7622 const char FirstContextCharacter =
7623 S.getSourceManager().getCharacterData(CC)[0];
7624 if (FirstContextCharacter == '{')
7625 return false;
7626 }
7627
7628 return true;
7629}
7630
John McCallcc7e5bf2010-05-06 08:58:33 +00007631void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00007632 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007633 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00007634
John McCallcc7e5bf2010-05-06 08:58:33 +00007635 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
7636 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
7637 if (Source == Target) return;
7638 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00007639
Chandler Carruthc22845a2011-07-26 05:40:03 +00007640 // If the conversion context location is invalid don't complain. We also
7641 // don't want to emit a warning if the issue occurs from the expansion of
7642 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
7643 // delay this check as long as possible. Once we detect we are in that
7644 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007645 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00007646 return;
7647
Richard Trieu021baa32011-09-23 20:10:00 +00007648 // Diagnose implicit casts to bool.
7649 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
7650 if (isa<StringLiteral>(E))
7651 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00007652 // and expressions, for instance, assert(0 && "error here"), are
7653 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00007654 return DiagnoseImpCast(S, E, T, CC,
7655 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00007656 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
7657 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
7658 // This covers the literal expressions that evaluate to Objective-C
7659 // objects.
7660 return DiagnoseImpCast(S, E, T, CC,
7661 diag::warn_impcast_objective_c_literal_to_bool);
7662 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00007663 if (Source->isPointerType() || Source->canDecayToPointerType()) {
7664 // Warn on pointer to bool conversion that is always true.
7665 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
7666 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00007667 }
Richard Trieu021baa32011-09-23 20:10:00 +00007668 }
John McCall263a48b2010-01-04 23:31:57 +00007669
Douglas Gregor5054cb02015-07-07 03:58:22 +00007670 // Check implicit casts from Objective-C collection literals to specialized
7671 // collection types, e.g., NSArray<NSString *> *.
7672 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
7673 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
7674 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
7675 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
7676
John McCall263a48b2010-01-04 23:31:57 +00007677 // Strip vector types.
7678 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007679 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007680 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007681 return;
John McCallacf0ee52010-10-08 02:01:28 +00007682 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007683 }
Chris Lattneree7286f2011-06-14 04:51:15 +00007684
7685 // If the vector cast is cast between two vectors of the same size, it is
7686 // a bitcast, not a conversion.
7687 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
7688 return;
John McCall263a48b2010-01-04 23:31:57 +00007689
7690 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
7691 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
7692 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00007693 if (auto VecTy = dyn_cast<VectorType>(Target))
7694 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00007695
7696 // Strip complex types.
7697 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007698 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007699 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007700 return;
7701
John McCallacf0ee52010-10-08 02:01:28 +00007702 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007703 }
John McCall263a48b2010-01-04 23:31:57 +00007704
7705 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
7706 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
7707 }
7708
7709 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
7710 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
7711
7712 // If the source is floating point...
7713 if (SourceBT && SourceBT->isFloatingPoint()) {
7714 // ...and the target is floating point...
7715 if (TargetBT && TargetBT->isFloatingPoint()) {
7716 // ...then warn if we're dropping FP rank.
7717
7718 // Builtin FP kinds are ordered by increasing FP rank.
7719 if (SourceBT->getKind() > TargetBT->getKind()) {
7720 // Don't warn about float constants that are precisely
7721 // representable in the target type.
7722 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00007723 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00007724 // Value might be a float, a float vector, or a float complex.
7725 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00007726 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
7727 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00007728 return;
7729 }
7730
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007731 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007732 return;
7733
John McCallacf0ee52010-10-08 02:01:28 +00007734 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
George Burgess IV148e0d32015-10-29 00:28:52 +00007735 }
7736 // ... or possibly if we're increasing rank, too
7737 else if (TargetBT->getKind() > SourceBT->getKind()) {
7738 if (S.SourceMgr.isInSystemMacro(CC))
7739 return;
7740
7741 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
John McCall263a48b2010-01-04 23:31:57 +00007742 }
7743 return;
7744 }
7745
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007746 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00007747 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007748 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007749 return;
7750
Chandler Carruth22c7a792011-02-17 11:05:49 +00007751 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00007752 // We also want to warn on, e.g., "int i = -1.234"
7753 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
7754 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
7755 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
7756
Chandler Carruth016ef402011-04-10 08:36:24 +00007757 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
7758 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00007759 } else {
7760 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
7761 }
7762 }
John McCall263a48b2010-01-04 23:31:57 +00007763
Richard Smith54894fd2015-12-30 01:06:52 +00007764 // Detect the case where a call result is converted from floating-point to
7765 // to bool, and the final argument to the call is converted from bool, to
7766 // discover this typo:
7767 //
7768 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
7769 //
7770 // FIXME: This is an incredibly special case; is there some more general
7771 // way to detect this class of misplaced-parentheses bug?
7772 if (Target->isBooleanType() && isa<CallExpr>(E)) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00007773 // Check last argument of function call to see if it is an
7774 // implicit cast from a type matching the type the result
7775 // is being cast to.
7776 CallExpr *CEx = cast<CallExpr>(E);
Richard Smith54894fd2015-12-30 01:06:52 +00007777 if (unsigned NumArgs = CEx->getNumArgs()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00007778 Expr *LastA = CEx->getArg(NumArgs - 1);
7779 Expr *InnerE = LastA->IgnoreParenImpCasts();
Richard Smith54894fd2015-12-30 01:06:52 +00007780 if (isa<ImplicitCastExpr>(LastA) &&
7781 InnerE->getType()->isBooleanType()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00007782 // Warn on this floating-point to bool conversion
7783 DiagnoseImpCast(S, E, T, CC,
7784 diag::warn_impcast_floating_point_to_bool);
7785 }
7786 }
7787 }
John McCall263a48b2010-01-04 23:31:57 +00007788 return;
7789 }
7790
Richard Trieu5b993502014-10-15 03:42:06 +00007791 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +00007792
David Blaikie9366d2b2012-06-19 21:19:06 +00007793 if (!Source->isIntegerType() || !Target->isIntegerType())
7794 return;
7795
David Blaikie7555b6a2012-05-15 16:56:36 +00007796 // TODO: remove this early return once the false positives for constant->bool
7797 // in templates, macros, etc, are reduced or removed.
7798 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
7799 return;
7800
John McCallcc7e5bf2010-05-06 08:58:33 +00007801 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00007802 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00007803
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007804 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00007805 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007806 // TODO: this should happen for bitfield stores, too.
7807 llvm::APSInt Value(32);
Richard Trieudcb55572016-01-29 23:51:16 +00007808 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007809 if (S.SourceMgr.isInSystemMacro(CC))
7810 return;
7811
John McCall18a2c2c2010-11-09 22:22:12 +00007812 std::string PrettySourceValue = Value.toString(10);
7813 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007814
Ted Kremenek33ba9952011-10-22 02:37:33 +00007815 S.DiagRuntimeBehavior(E->getExprLoc(), E,
7816 S.PDiag(diag::warn_impcast_integer_precision_constant)
7817 << PrettySourceValue << PrettyTargetValue
7818 << E->getType() << T << E->getSourceRange()
7819 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00007820 return;
7821 }
7822
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007823 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
7824 if (S.SourceMgr.isInSystemMacro(CC))
7825 return;
7826
David Blaikie9455da02012-04-12 22:40:54 +00007827 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00007828 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
7829 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00007830 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00007831 }
7832
Richard Trieudcb55572016-01-29 23:51:16 +00007833 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
7834 SourceRange.NonNegative && Source->isSignedIntegerType()) {
7835 // Warn when doing a signed to signed conversion, warn if the positive
7836 // source value is exactly the width of the target type, which will
7837 // cause a negative value to be stored.
7838
7839 llvm::APSInt Value;
Richard Trieufc404c72016-02-05 23:02:38 +00007840 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
7841 !S.SourceMgr.isInSystemMacro(CC)) {
7842 if (isSameWidthConstantConversion(S, E, T, CC)) {
7843 std::string PrettySourceValue = Value.toString(10);
7844 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Richard Trieudcb55572016-01-29 23:51:16 +00007845
Richard Trieufc404c72016-02-05 23:02:38 +00007846 S.DiagRuntimeBehavior(
7847 E->getExprLoc(), E,
7848 S.PDiag(diag::warn_impcast_integer_precision_constant)
7849 << PrettySourceValue << PrettyTargetValue << E->getType() << T
7850 << E->getSourceRange() << clang::SourceRange(CC));
7851 return;
Richard Trieudcb55572016-01-29 23:51:16 +00007852 }
7853 }
Richard Trieufc404c72016-02-05 23:02:38 +00007854
Richard Trieudcb55572016-01-29 23:51:16 +00007855 // Fall through for non-constants to give a sign conversion warning.
7856 }
7857
John McCallcc7e5bf2010-05-06 08:58:33 +00007858 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
7859 (!TargetRange.NonNegative && SourceRange.NonNegative &&
7860 SourceRange.Width == TargetRange.Width)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007861 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007862 return;
7863
John McCallcc7e5bf2010-05-06 08:58:33 +00007864 unsigned DiagID = diag::warn_impcast_integer_sign;
7865
7866 // Traditionally, gcc has warned about this under -Wsign-compare.
7867 // We also want to warn about it in -Wconversion.
7868 // So if -Wconversion is off, use a completely identical diagnostic
7869 // in the sign-compare group.
7870 // The conditional-checking code will
7871 if (ICContext) {
7872 DiagID = diag::warn_impcast_integer_sign_conditional;
7873 *ICContext = true;
7874 }
7875
John McCallacf0ee52010-10-08 02:01:28 +00007876 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00007877 }
7878
Douglas Gregora78f1932011-02-22 02:45:07 +00007879 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00007880 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
7881 // type, to give us better diagnostics.
7882 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00007883 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00007884 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
7885 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
7886 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
7887 SourceType = S.Context.getTypeDeclType(Enum);
7888 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
7889 }
7890 }
7891
Douglas Gregora78f1932011-02-22 02:45:07 +00007892 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
7893 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00007894 if (SourceEnum->getDecl()->hasNameForLinkage() &&
7895 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007896 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007897 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007898 return;
7899
Douglas Gregor364f7db2011-03-12 00:14:31 +00007900 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00007901 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007902 }
John McCall263a48b2010-01-04 23:31:57 +00007903}
7904
David Blaikie18e9ac72012-05-15 21:57:38 +00007905void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
7906 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00007907
7908void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00007909 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007910 E = E->IgnoreParenImpCasts();
7911
7912 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00007913 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00007914
John McCallacf0ee52010-10-08 02:01:28 +00007915 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007916 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00007917 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00007918}
7919
David Blaikie18e9ac72012-05-15 21:57:38 +00007920void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
7921 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00007922 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00007923
7924 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00007925 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
7926 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00007927
7928 // If -Wconversion would have warned about either of the candidates
7929 // for a signedness conversion to the context type...
7930 if (!Suspicious) return;
7931
7932 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007933 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00007934 return;
7935
John McCallcc7e5bf2010-05-06 08:58:33 +00007936 // ...then check whether it would have warned about either of the
7937 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00007938 if (E->getType() == T) return;
7939
7940 Suspicious = false;
7941 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
7942 E->getType(), CC, &Suspicious);
7943 if (!Suspicious)
7944 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00007945 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00007946}
7947
Richard Trieu65724892014-11-15 06:37:39 +00007948/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
7949/// Input argument E is a logical expression.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007950void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
Richard Trieu65724892014-11-15 06:37:39 +00007951 if (S.getLangOpts().Bool)
7952 return;
7953 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
7954}
7955
John McCallcc7e5bf2010-05-06 08:58:33 +00007956/// AnalyzeImplicitConversions - Find and report any interesting
7957/// implicit conversions in the given expression. There are a couple
7958/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00007959void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00007960 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00007961 Expr *E = OrigE->IgnoreParenImpCasts();
7962
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00007963 if (E->isTypeDependent() || E->isValueDependent())
7964 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00007965
John McCallcc7e5bf2010-05-06 08:58:33 +00007966 // For conditional operators, we analyze the arguments as if they
7967 // were being fed directly into the output.
7968 if (isa<ConditionalOperator>(E)) {
7969 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00007970 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00007971 return;
7972 }
7973
Hans Wennborgf4ad2322012-08-28 15:44:30 +00007974 // Check implicit argument conversions for function calls.
7975 if (CallExpr *Call = dyn_cast<CallExpr>(E))
7976 CheckImplicitArgumentConversions(S, Call, CC);
7977
John McCallcc7e5bf2010-05-06 08:58:33 +00007978 // Go ahead and check any implicit conversions we might have skipped.
7979 // The non-canonical typecheck is just an optimization;
7980 // CheckImplicitConversion will filter out dead implicit conversions.
7981 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00007982 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007983
7984 // Now continue drilling into this expression.
Richard Smithd7bed4d2015-11-22 02:57:17 +00007985
7986 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
7987 // The bound subexpressions in a PseudoObjectExpr are not reachable
7988 // as transitive children.
7989 // FIXME: Use a more uniform representation for this.
7990 for (auto *SE : POE->semantics())
7991 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
7992 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00007993 }
Richard Smithd7bed4d2015-11-22 02:57:17 +00007994
John McCallcc7e5bf2010-05-06 08:58:33 +00007995 // Skip past explicit casts.
7996 if (isa<ExplicitCastExpr>(E)) {
7997 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00007998 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007999 }
8000
John McCalld2a53122010-11-09 23:24:47 +00008001 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
8002 // Do a somewhat different check with comparison operators.
8003 if (BO->isComparisonOp())
8004 return AnalyzeComparison(S, BO);
8005
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008006 // And with simple assignments.
8007 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00008008 return AnalyzeAssignment(S, BO);
8009 }
John McCallcc7e5bf2010-05-06 08:58:33 +00008010
8011 // These break the otherwise-useful invariant below. Fortunately,
8012 // we don't really need to recurse into them, because any internal
8013 // expressions should have been analyzed already when they were
8014 // built into statements.
8015 if (isa<StmtExpr>(E)) return;
8016
8017 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00008018 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00008019
8020 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00008021 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00008022 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00008023 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Benjamin Kramer642f1732015-07-02 21:03:14 +00008024 for (Stmt *SubStmt : E->children()) {
8025 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00008026 if (!ChildExpr)
8027 continue;
8028
Richard Trieu955231d2014-01-25 01:10:35 +00008029 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00008030 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00008031 // Ignore checking string literals that are in logical and operators.
8032 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00008033 continue;
8034 AnalyzeImplicitConversions(S, ChildExpr, CC);
8035 }
Richard Trieu791b86e2014-11-19 06:08:18 +00008036
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00008037 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +00008038 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
8039 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00008040 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +00008041
8042 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
8043 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00008044 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00008045 }
Richard Trieu791b86e2014-11-19 06:08:18 +00008046
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00008047 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
8048 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +00008049 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008050}
8051
8052} // end anonymous namespace
8053
Richard Trieuc1888e02014-06-28 23:25:37 +00008054// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
8055// Returns true when emitting a warning about taking the address of a reference.
8056static bool CheckForReference(Sema &SemaRef, const Expr *E,
8057 PartialDiagnostic PD) {
8058 E = E->IgnoreParenImpCasts();
8059
8060 const FunctionDecl *FD = nullptr;
8061
8062 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
8063 if (!DRE->getDecl()->getType()->isReferenceType())
8064 return false;
8065 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
8066 if (!M->getMemberDecl()->getType()->isReferenceType())
8067 return false;
8068 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +00008069 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +00008070 return false;
8071 FD = Call->getDirectCallee();
8072 } else {
8073 return false;
8074 }
8075
8076 SemaRef.Diag(E->getExprLoc(), PD);
8077
8078 // If possible, point to location of function.
8079 if (FD) {
8080 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
8081 }
8082
8083 return true;
8084}
8085
Richard Trieu4cbff5c2014-08-08 22:41:43 +00008086// Returns true if the SourceLocation is expanded from any macro body.
8087// Returns false if the SourceLocation is invalid, is from not in a macro
8088// expansion, or is from expanded from a top-level macro argument.
8089static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
8090 if (Loc.isInvalid())
8091 return false;
8092
8093 while (Loc.isMacroID()) {
8094 if (SM.isMacroBodyExpansion(Loc))
8095 return true;
8096 Loc = SM.getImmediateMacroCallerLoc(Loc);
8097 }
8098
8099 return false;
8100}
8101
Richard Trieu3bb8b562014-02-26 02:36:06 +00008102/// \brief Diagnose pointers that are always non-null.
8103/// \param E the expression containing the pointer
8104/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
8105/// compared to a null pointer
8106/// \param IsEqual True when the comparison is equal to a null pointer
8107/// \param Range Extra SourceRange to highlight in the diagnostic
8108void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
8109 Expr::NullPointerConstantKind NullKind,
8110 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00008111 if (!E)
8112 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00008113
8114 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +00008115 if (E->getExprLoc().isMacroID()) {
8116 const SourceManager &SM = getSourceManager();
8117 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
8118 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +00008119 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +00008120 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00008121 E = E->IgnoreImpCasts();
8122
8123 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
8124
Richard Trieuf7432752014-06-06 21:39:26 +00008125 if (isa<CXXThisExpr>(E)) {
8126 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
8127 : diag::warn_this_bool_conversion;
8128 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
8129 return;
8130 }
8131
Richard Trieu3bb8b562014-02-26 02:36:06 +00008132 bool IsAddressOf = false;
8133
8134 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
8135 if (UO->getOpcode() != UO_AddrOf)
8136 return;
8137 IsAddressOf = true;
8138 E = UO->getSubExpr();
8139 }
8140
Richard Trieuc1888e02014-06-28 23:25:37 +00008141 if (IsAddressOf) {
8142 unsigned DiagID = IsCompare
8143 ? diag::warn_address_of_reference_null_compare
8144 : diag::warn_address_of_reference_bool_conversion;
8145 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
8146 << IsEqual;
8147 if (CheckForReference(*this, E, PD)) {
8148 return;
8149 }
8150 }
8151
George Burgess IV850269a2015-12-08 22:02:00 +00008152 auto ComplainAboutNonnullParamOrCall = [&](bool IsParam) {
8153 std::string Str;
8154 llvm::raw_string_ostream S(Str);
8155 E->printPretty(S, nullptr, getPrintingPolicy());
8156 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
8157 : diag::warn_cast_nonnull_to_bool;
8158 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
8159 << E->getSourceRange() << Range << IsEqual;
8160 };
8161
8162 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
8163 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
8164 if (auto *Callee = Call->getDirectCallee()) {
8165 if (Callee->hasAttr<ReturnsNonNullAttr>()) {
8166 ComplainAboutNonnullParamOrCall(false);
8167 return;
8168 }
8169 }
8170 }
8171
Richard Trieu3bb8b562014-02-26 02:36:06 +00008172 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +00008173 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +00008174 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
8175 D = R->getDecl();
8176 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
8177 D = M->getMemberDecl();
8178 }
8179
8180 // Weak Decls can be null.
8181 if (!D || D->isWeak())
8182 return;
George Burgess IV850269a2015-12-08 22:02:00 +00008183
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008184 // Check for parameter decl with nonnull attribute
George Burgess IV850269a2015-12-08 22:02:00 +00008185 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
8186 if (getCurFunction() &&
8187 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
8188 if (PV->hasAttr<NonNullAttr>()) {
8189 ComplainAboutNonnullParamOrCall(true);
8190 return;
8191 }
8192
8193 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
8194 auto ParamIter = std::find(FD->param_begin(), FD->param_end(), PV);
8195 assert(ParamIter != FD->param_end());
8196 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
8197
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008198 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
8199 if (!NonNull->args_size()) {
George Burgess IV850269a2015-12-08 22:02:00 +00008200 ComplainAboutNonnullParamOrCall(true);
8201 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008202 }
George Burgess IV850269a2015-12-08 22:02:00 +00008203
8204 for (unsigned ArgNo : NonNull->args()) {
8205 if (ArgNo == ParamNo) {
8206 ComplainAboutNonnullParamOrCall(true);
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008207 return;
8208 }
George Burgess IV850269a2015-12-08 22:02:00 +00008209 }
8210 }
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008211 }
8212 }
George Burgess IV850269a2015-12-08 22:02:00 +00008213 }
8214
Richard Trieu3bb8b562014-02-26 02:36:06 +00008215 QualType T = D->getType();
8216 const bool IsArray = T->isArrayType();
8217 const bool IsFunction = T->isFunctionType();
8218
Richard Trieuc1888e02014-06-28 23:25:37 +00008219 // Address of function is used to silence the function warning.
8220 if (IsAddressOf && IsFunction) {
8221 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00008222 }
8223
8224 // Found nothing.
8225 if (!IsAddressOf && !IsFunction && !IsArray)
8226 return;
8227
8228 // Pretty print the expression for the diagnostic.
8229 std::string Str;
8230 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +00008231 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +00008232
8233 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
8234 : diag::warn_impcast_pointer_to_bool;
Craig Topperfa1340f2015-12-23 05:44:46 +00008235 enum {
8236 AddressOf,
8237 FunctionPointer,
8238 ArrayPointer
8239 } DiagType;
Richard Trieu3bb8b562014-02-26 02:36:06 +00008240 if (IsAddressOf)
8241 DiagType = AddressOf;
8242 else if (IsFunction)
8243 DiagType = FunctionPointer;
8244 else if (IsArray)
8245 DiagType = ArrayPointer;
8246 else
8247 llvm_unreachable("Could not determine diagnostic.");
8248 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
8249 << Range << IsEqual;
8250
8251 if (!IsFunction)
8252 return;
8253
8254 // Suggest '&' to silence the function warning.
8255 Diag(E->getExprLoc(), diag::note_function_warning_silence)
8256 << FixItHint::CreateInsertion(E->getLocStart(), "&");
8257
8258 // Check to see if '()' fixit should be emitted.
8259 QualType ReturnType;
8260 UnresolvedSet<4> NonTemplateOverloads;
8261 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
8262 if (ReturnType.isNull())
8263 return;
8264
8265 if (IsCompare) {
8266 // There are two cases here. If there is null constant, the only suggest
8267 // for a pointer return type. If the null is 0, then suggest if the return
8268 // type is a pointer or an integer type.
8269 if (!ReturnType->isPointerType()) {
8270 if (NullKind == Expr::NPCK_ZeroExpression ||
8271 NullKind == Expr::NPCK_ZeroLiteral) {
8272 if (!ReturnType->isIntegerType())
8273 return;
8274 } else {
8275 return;
8276 }
8277 }
8278 } else { // !IsCompare
8279 // For function to bool, only suggest if the function pointer has bool
8280 // return type.
8281 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
8282 return;
8283 }
8284 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +00008285 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +00008286}
8287
John McCallcc7e5bf2010-05-06 08:58:33 +00008288/// Diagnoses "dangerous" implicit conversions within the given
8289/// expression (which is a full expression). Implements -Wconversion
8290/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00008291///
8292/// \param CC the "context" location of the implicit conversion, i.e.
8293/// the most location of the syntactic entity requiring the implicit
8294/// conversion
8295void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008296 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00008297 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00008298 return;
8299
8300 // Don't diagnose for value- or type-dependent expressions.
8301 if (E->isTypeDependent() || E->isValueDependent())
8302 return;
8303
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008304 // Check for array bounds violations in cases where the check isn't triggered
8305 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
8306 // ArraySubscriptExpr is on the RHS of a variable initialization.
8307 CheckArrayAccess(E);
8308
John McCallacf0ee52010-10-08 02:01:28 +00008309 // This is not the right CC for (e.g.) a variable initialization.
8310 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008311}
8312
Richard Trieu65724892014-11-15 06:37:39 +00008313/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
8314/// Input argument E is a logical expression.
8315void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
8316 ::CheckBoolLikeConversion(*this, E, CC);
8317}
8318
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008319/// Diagnose when expression is an integer constant expression and its evaluation
8320/// results in integer overflow
8321void Sema::CheckForIntOverflow (Expr *E) {
Akira Hatanakadfe2156f2016-02-10 06:06:06 +00008322 // Use a work list to deal with nested struct initializers.
8323 SmallVector<Expr *, 2> Exprs(1, E);
8324
8325 do {
8326 Expr *E = Exprs.pop_back_val();
8327
8328 if (isa<BinaryOperator>(E->IgnoreParenCasts())) {
8329 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
8330 continue;
8331 }
8332
8333 if (auto InitList = dyn_cast<InitListExpr>(E))
8334 Exprs.append(InitList->inits().begin(), InitList->inits().end());
8335 } while (!Exprs.empty());
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008336}
8337
Richard Smithc406cb72013-01-17 01:17:56 +00008338namespace {
8339/// \brief Visitor for expressions which looks for unsequenced operations on the
8340/// same object.
8341class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00008342 typedef EvaluatedExprVisitor<SequenceChecker> Base;
8343
Richard Smithc406cb72013-01-17 01:17:56 +00008344 /// \brief A tree of sequenced regions within an expression. Two regions are
8345 /// unsequenced if one is an ancestor or a descendent of the other. When we
8346 /// finish processing an expression with sequencing, such as a comma
8347 /// expression, we fold its tree nodes into its parent, since they are
8348 /// unsequenced with respect to nodes we will visit later.
8349 class SequenceTree {
8350 struct Value {
8351 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
8352 unsigned Parent : 31;
8353 bool Merged : 1;
8354 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008355 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00008356
8357 public:
8358 /// \brief A region within an expression which may be sequenced with respect
8359 /// to some other region.
8360 class Seq {
8361 explicit Seq(unsigned N) : Index(N) {}
8362 unsigned Index;
8363 friend class SequenceTree;
8364 public:
8365 Seq() : Index(0) {}
8366 };
8367
8368 SequenceTree() { Values.push_back(Value(0)); }
8369 Seq root() const { return Seq(0); }
8370
8371 /// \brief Create a new sequence of operations, which is an unsequenced
8372 /// subset of \p Parent. This sequence of operations is sequenced with
8373 /// respect to other children of \p Parent.
8374 Seq allocate(Seq Parent) {
8375 Values.push_back(Value(Parent.Index));
8376 return Seq(Values.size() - 1);
8377 }
8378
8379 /// \brief Merge a sequence of operations into its parent.
8380 void merge(Seq S) {
8381 Values[S.Index].Merged = true;
8382 }
8383
8384 /// \brief Determine whether two operations are unsequenced. This operation
8385 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
8386 /// should have been merged into its parent as appropriate.
8387 bool isUnsequenced(Seq Cur, Seq Old) {
8388 unsigned C = representative(Cur.Index);
8389 unsigned Target = representative(Old.Index);
8390 while (C >= Target) {
8391 if (C == Target)
8392 return true;
8393 C = Values[C].Parent;
8394 }
8395 return false;
8396 }
8397
8398 private:
8399 /// \brief Pick a representative for a sequence.
8400 unsigned representative(unsigned K) {
8401 if (Values[K].Merged)
8402 // Perform path compression as we go.
8403 return Values[K].Parent = representative(Values[K].Parent);
8404 return K;
8405 }
8406 };
8407
8408 /// An object for which we can track unsequenced uses.
8409 typedef NamedDecl *Object;
8410
8411 /// Different flavors of object usage which we track. We only track the
8412 /// least-sequenced usage of each kind.
8413 enum UsageKind {
8414 /// A read of an object. Multiple unsequenced reads are OK.
8415 UK_Use,
8416 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00008417 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00008418 UK_ModAsValue,
8419 /// A modification of an object which is not sequenced before the value
8420 /// computation of the expression, such as n++.
8421 UK_ModAsSideEffect,
8422
8423 UK_Count = UK_ModAsSideEffect + 1
8424 };
8425
8426 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +00008427 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +00008428 Expr *Use;
8429 SequenceTree::Seq Seq;
8430 };
8431
8432 struct UsageInfo {
8433 UsageInfo() : Diagnosed(false) {}
8434 Usage Uses[UK_Count];
8435 /// Have we issued a diagnostic for this variable already?
8436 bool Diagnosed;
8437 };
8438 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
8439
8440 Sema &SemaRef;
8441 /// Sequenced regions within the expression.
8442 SequenceTree Tree;
8443 /// Declaration modifications and references which we have seen.
8444 UsageInfoMap UsageMap;
8445 /// The region we are currently within.
8446 SequenceTree::Seq Region;
8447 /// Filled in with declarations which were modified as a side-effect
8448 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008449 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00008450 /// Expressions to check later. We defer checking these to reduce
8451 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008452 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00008453
8454 /// RAII object wrapping the visitation of a sequenced subexpression of an
8455 /// expression. At the end of this process, the side-effects of the evaluation
8456 /// become sequenced with respect to the value computation of the result, so
8457 /// we downgrade any UK_ModAsSideEffect within the evaluation to
8458 /// UK_ModAsValue.
8459 struct SequencedSubexpression {
8460 SequencedSubexpression(SequenceChecker &Self)
8461 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
8462 Self.ModAsSideEffect = &ModAsSideEffect;
8463 }
8464 ~SequencedSubexpression() {
Richard Smithe8efd992014-12-03 01:05:50 +00008465 for (auto MI = ModAsSideEffect.rbegin(), ME = ModAsSideEffect.rend();
8466 MI != ME; ++MI) {
8467 UsageInfo &U = Self.UsageMap[MI->first];
8468 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
8469 Self.addUsage(U, MI->first, SideEffectUsage.Use, UK_ModAsValue);
8470 SideEffectUsage = MI->second;
Richard Smithc406cb72013-01-17 01:17:56 +00008471 }
8472 Self.ModAsSideEffect = OldModAsSideEffect;
8473 }
8474
8475 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008476 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
8477 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00008478 };
8479
Richard Smith40238f02013-06-20 22:21:56 +00008480 /// RAII object wrapping the visitation of a subexpression which we might
8481 /// choose to evaluate as a constant. If any subexpression is evaluated and
8482 /// found to be non-constant, this allows us to suppress the evaluation of
8483 /// the outer expression.
8484 class EvaluationTracker {
8485 public:
8486 EvaluationTracker(SequenceChecker &Self)
8487 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
8488 Self.EvalTracker = this;
8489 }
8490 ~EvaluationTracker() {
8491 Self.EvalTracker = Prev;
8492 if (Prev)
8493 Prev->EvalOK &= EvalOK;
8494 }
8495
8496 bool evaluate(const Expr *E, bool &Result) {
8497 if (!EvalOK || E->isValueDependent())
8498 return false;
8499 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
8500 return EvalOK;
8501 }
8502
8503 private:
8504 SequenceChecker &Self;
8505 EvaluationTracker *Prev;
8506 bool EvalOK;
8507 } *EvalTracker;
8508
Richard Smithc406cb72013-01-17 01:17:56 +00008509 /// \brief Find the object which is produced by the specified expression,
8510 /// if any.
8511 Object getObject(Expr *E, bool Mod) const {
8512 E = E->IgnoreParenCasts();
8513 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
8514 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
8515 return getObject(UO->getSubExpr(), Mod);
8516 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
8517 if (BO->getOpcode() == BO_Comma)
8518 return getObject(BO->getRHS(), Mod);
8519 if (Mod && BO->isAssignmentOp())
8520 return getObject(BO->getLHS(), Mod);
8521 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
8522 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
8523 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
8524 return ME->getMemberDecl();
8525 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
8526 // FIXME: If this is a reference, map through to its value.
8527 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00008528 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +00008529 }
8530
8531 /// \brief Note that an object was modified or used by an expression.
8532 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
8533 Usage &U = UI.Uses[UK];
8534 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
8535 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
8536 ModAsSideEffect->push_back(std::make_pair(O, U));
8537 U.Use = Ref;
8538 U.Seq = Region;
8539 }
8540 }
8541 /// \brief Check whether a modification or use conflicts with a prior usage.
8542 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
8543 bool IsModMod) {
8544 if (UI.Diagnosed)
8545 return;
8546
8547 const Usage &U = UI.Uses[OtherKind];
8548 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
8549 return;
8550
8551 Expr *Mod = U.Use;
8552 Expr *ModOrUse = Ref;
8553 if (OtherKind == UK_Use)
8554 std::swap(Mod, ModOrUse);
8555
8556 SemaRef.Diag(Mod->getExprLoc(),
8557 IsModMod ? diag::warn_unsequenced_mod_mod
8558 : diag::warn_unsequenced_mod_use)
8559 << O << SourceRange(ModOrUse->getExprLoc());
8560 UI.Diagnosed = true;
8561 }
8562
8563 void notePreUse(Object O, Expr *Use) {
8564 UsageInfo &U = UsageMap[O];
8565 // Uses conflict with other modifications.
8566 checkUsage(O, U, Use, UK_ModAsValue, false);
8567 }
8568 void notePostUse(Object O, Expr *Use) {
8569 UsageInfo &U = UsageMap[O];
8570 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
8571 addUsage(U, O, Use, UK_Use);
8572 }
8573
8574 void notePreMod(Object O, Expr *Mod) {
8575 UsageInfo &U = UsageMap[O];
8576 // Modifications conflict with other modifications and with uses.
8577 checkUsage(O, U, Mod, UK_ModAsValue, true);
8578 checkUsage(O, U, Mod, UK_Use, false);
8579 }
8580 void notePostMod(Object O, Expr *Use, UsageKind UK) {
8581 UsageInfo &U = UsageMap[O];
8582 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
8583 addUsage(U, O, Use, UK);
8584 }
8585
8586public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008587 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +00008588 : Base(S.Context), SemaRef(S), Region(Tree.root()),
8589 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +00008590 Visit(E);
8591 }
8592
8593 void VisitStmt(Stmt *S) {
8594 // Skip all statements which aren't expressions for now.
8595 }
8596
8597 void VisitExpr(Expr *E) {
8598 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00008599 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00008600 }
8601
8602 void VisitCastExpr(CastExpr *E) {
8603 Object O = Object();
8604 if (E->getCastKind() == CK_LValueToRValue)
8605 O = getObject(E->getSubExpr(), false);
8606
8607 if (O)
8608 notePreUse(O, E);
8609 VisitExpr(E);
8610 if (O)
8611 notePostUse(O, E);
8612 }
8613
8614 void VisitBinComma(BinaryOperator *BO) {
8615 // C++11 [expr.comma]p1:
8616 // Every value computation and side effect associated with the left
8617 // expression is sequenced before every value computation and side
8618 // effect associated with the right expression.
8619 SequenceTree::Seq LHS = Tree.allocate(Region);
8620 SequenceTree::Seq RHS = Tree.allocate(Region);
8621 SequenceTree::Seq OldRegion = Region;
8622
8623 {
8624 SequencedSubexpression SeqLHS(*this);
8625 Region = LHS;
8626 Visit(BO->getLHS());
8627 }
8628
8629 Region = RHS;
8630 Visit(BO->getRHS());
8631
8632 Region = OldRegion;
8633
8634 // Forget that LHS and RHS are sequenced. They are both unsequenced
8635 // with respect to other stuff.
8636 Tree.merge(LHS);
8637 Tree.merge(RHS);
8638 }
8639
8640 void VisitBinAssign(BinaryOperator *BO) {
8641 // The modification is sequenced after the value computation of the LHS
8642 // and RHS, so check it before inspecting the operands and update the
8643 // map afterwards.
8644 Object O = getObject(BO->getLHS(), true);
8645 if (!O)
8646 return VisitExpr(BO);
8647
8648 notePreMod(O, BO);
8649
8650 // C++11 [expr.ass]p7:
8651 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
8652 // only once.
8653 //
8654 // Therefore, for a compound assignment operator, O is considered used
8655 // everywhere except within the evaluation of E1 itself.
8656 if (isa<CompoundAssignOperator>(BO))
8657 notePreUse(O, BO);
8658
8659 Visit(BO->getLHS());
8660
8661 if (isa<CompoundAssignOperator>(BO))
8662 notePostUse(O, BO);
8663
8664 Visit(BO->getRHS());
8665
Richard Smith83e37bee2013-06-26 23:16:51 +00008666 // C++11 [expr.ass]p1:
8667 // the assignment is sequenced [...] before the value computation of the
8668 // assignment expression.
8669 // C11 6.5.16/3 has no such rule.
8670 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
8671 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00008672 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008673
Richard Smithc406cb72013-01-17 01:17:56 +00008674 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
8675 VisitBinAssign(CAO);
8676 }
8677
8678 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
8679 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
8680 void VisitUnaryPreIncDec(UnaryOperator *UO) {
8681 Object O = getObject(UO->getSubExpr(), true);
8682 if (!O)
8683 return VisitExpr(UO);
8684
8685 notePreMod(O, UO);
8686 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +00008687 // C++11 [expr.pre.incr]p1:
8688 // the expression ++x is equivalent to x+=1
8689 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
8690 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00008691 }
8692
8693 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
8694 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
8695 void VisitUnaryPostIncDec(UnaryOperator *UO) {
8696 Object O = getObject(UO->getSubExpr(), true);
8697 if (!O)
8698 return VisitExpr(UO);
8699
8700 notePreMod(O, UO);
8701 Visit(UO->getSubExpr());
8702 notePostMod(O, UO, UK_ModAsSideEffect);
8703 }
8704
8705 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
8706 void VisitBinLOr(BinaryOperator *BO) {
8707 // The side-effects of the LHS of an '&&' are sequenced before the
8708 // value computation of the RHS, and hence before the value computation
8709 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
8710 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +00008711 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00008712 {
8713 SequencedSubexpression Sequenced(*this);
8714 Visit(BO->getLHS());
8715 }
8716
8717 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00008718 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00008719 if (!Result)
8720 Visit(BO->getRHS());
8721 } else {
8722 // Check for unsequenced operations in the RHS, treating it as an
8723 // entirely separate evaluation.
8724 //
8725 // FIXME: If there are operations in the RHS which are unsequenced
8726 // with respect to operations outside the RHS, and those operations
8727 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +00008728 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00008729 }
Richard Smithc406cb72013-01-17 01:17:56 +00008730 }
8731 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +00008732 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00008733 {
8734 SequencedSubexpression Sequenced(*this);
8735 Visit(BO->getLHS());
8736 }
8737
8738 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00008739 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00008740 if (Result)
8741 Visit(BO->getRHS());
8742 } else {
Richard Smithd33f5202013-01-17 23:18:09 +00008743 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00008744 }
Richard Smithc406cb72013-01-17 01:17:56 +00008745 }
8746
8747 // Only visit the condition, unless we can be sure which subexpression will
8748 // be chosen.
8749 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +00008750 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +00008751 {
8752 SequencedSubexpression Sequenced(*this);
8753 Visit(CO->getCond());
8754 }
Richard Smithc406cb72013-01-17 01:17:56 +00008755
8756 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00008757 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +00008758 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00008759 else {
Richard Smithd33f5202013-01-17 23:18:09 +00008760 WorkList.push_back(CO->getTrueExpr());
8761 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00008762 }
Richard Smithc406cb72013-01-17 01:17:56 +00008763 }
8764
Richard Smithe3dbfe02013-06-30 10:40:20 +00008765 void VisitCallExpr(CallExpr *CE) {
8766 // C++11 [intro.execution]p15:
8767 // When calling a function [...], every value computation and side effect
8768 // associated with any argument expression, or with the postfix expression
8769 // designating the called function, is sequenced before execution of every
8770 // expression or statement in the body of the function [and thus before
8771 // the value computation of its result].
8772 SequencedSubexpression Sequenced(*this);
8773 Base::VisitCallExpr(CE);
8774
8775 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
8776 }
8777
Richard Smithc406cb72013-01-17 01:17:56 +00008778 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +00008779 // This is a call, so all subexpressions are sequenced before the result.
8780 SequencedSubexpression Sequenced(*this);
8781
Richard Smithc406cb72013-01-17 01:17:56 +00008782 if (!CCE->isListInitialization())
8783 return VisitExpr(CCE);
8784
8785 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008786 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00008787 SequenceTree::Seq Parent = Region;
8788 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
8789 E = CCE->arg_end();
8790 I != E; ++I) {
8791 Region = Tree.allocate(Parent);
8792 Elts.push_back(Region);
8793 Visit(*I);
8794 }
8795
8796 // Forget that the initializers are sequenced.
8797 Region = Parent;
8798 for (unsigned I = 0; I < Elts.size(); ++I)
8799 Tree.merge(Elts[I]);
8800 }
8801
8802 void VisitInitListExpr(InitListExpr *ILE) {
8803 if (!SemaRef.getLangOpts().CPlusPlus11)
8804 return VisitExpr(ILE);
8805
8806 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008807 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00008808 SequenceTree::Seq Parent = Region;
8809 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
8810 Expr *E = ILE->getInit(I);
8811 if (!E) continue;
8812 Region = Tree.allocate(Parent);
8813 Elts.push_back(Region);
8814 Visit(E);
8815 }
8816
8817 // Forget that the initializers are sequenced.
8818 Region = Parent;
8819 for (unsigned I = 0; I < Elts.size(); ++I)
8820 Tree.merge(Elts[I]);
8821 }
8822};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008823} // end anonymous namespace
Richard Smithc406cb72013-01-17 01:17:56 +00008824
8825void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008826 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +00008827 WorkList.push_back(E);
8828 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00008829 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +00008830 SequenceChecker(*this, Item, WorkList);
8831 }
Richard Smithc406cb72013-01-17 01:17:56 +00008832}
8833
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008834void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
8835 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +00008836 CheckImplicitConversions(E, CheckLoc);
8837 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008838 if (!IsConstexpr && !E->isValueDependent())
8839 CheckForIntOverflow(E);
Richard Smithc406cb72013-01-17 01:17:56 +00008840}
8841
John McCall1f425642010-11-11 03:21:53 +00008842void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
8843 FieldDecl *BitField,
8844 Expr *Init) {
8845 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
8846}
8847
David Majnemer61a5bbf2015-04-07 22:08:51 +00008848static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
8849 SourceLocation Loc) {
8850 if (!PType->isVariablyModifiedType())
8851 return;
8852 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
8853 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
8854 return;
8855 }
David Majnemerdf8f73f2015-04-09 19:53:25 +00008856 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
8857 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
8858 return;
8859 }
David Majnemer61a5bbf2015-04-07 22:08:51 +00008860 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
8861 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
8862 return;
8863 }
8864
8865 const ArrayType *AT = S.Context.getAsArrayType(PType);
8866 if (!AT)
8867 return;
8868
8869 if (AT->getSizeModifier() != ArrayType::Star) {
8870 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
8871 return;
8872 }
8873
8874 S.Diag(Loc, diag::err_array_star_in_function_definition);
8875}
8876
Mike Stump0c2ec772010-01-21 03:59:47 +00008877/// CheckParmsForFunctionDef - Check that the parameters of the given
8878/// function are appropriate for the definition of a function. This
8879/// takes care of any checks that cannot be performed on the
8880/// declaration itself, e.g., that the types of each of the function
8881/// parameters are complete.
Reid Kleckner5a115802013-06-24 14:38:26 +00008882bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
8883 ParmVarDecl *const *PEnd,
Douglas Gregorb524d902010-11-01 18:37:59 +00008884 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +00008885 bool HasInvalidParm = false;
Douglas Gregorb524d902010-11-01 18:37:59 +00008886 for (; P != PEnd; ++P) {
8887 ParmVarDecl *Param = *P;
8888
Mike Stump0c2ec772010-01-21 03:59:47 +00008889 // C99 6.7.5.3p4: the parameters in a parameter type list in a
8890 // function declarator that is part of a function definition of
8891 // that function shall not have incomplete type.
8892 //
8893 // This is also C++ [dcl.fct]p6.
8894 if (!Param->isInvalidDecl() &&
8895 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00008896 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +00008897 Param->setInvalidDecl();
8898 HasInvalidParm = true;
8899 }
8900
8901 // C99 6.9.1p5: If the declarator includes a parameter type list, the
8902 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +00008903 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +00008904 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +00008905 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00008906 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +00008907 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +00008908
8909 // C99 6.7.5.3p12:
8910 // If the function declarator is not part of a definition of that
8911 // function, parameters may have incomplete type and may use the [*]
8912 // notation in their sequences of declarator specifiers to specify
8913 // variable length array types.
8914 QualType PType = Param->getOriginalType();
David Majnemer61a5bbf2015-04-07 22:08:51 +00008915 // FIXME: This diagnostic should point the '[*]' if source-location
8916 // information is added for it.
8917 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00008918
8919 // MSVC destroys objects passed by value in the callee. Therefore a
8920 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00008921 // object's destructor. However, we don't perform any direct access check
8922 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +00008923 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
8924 .getCXXABI()
8925 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +00008926 if (!Param->isInvalidDecl()) {
8927 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
8928 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
8929 if (!ClassDecl->isInvalidDecl() &&
8930 !ClassDecl->hasIrrelevantDestructor() &&
8931 !ClassDecl->isDependentContext()) {
8932 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
8933 MarkFunctionReferenced(Param->getLocation(), Destructor);
8934 DiagnoseUseOfDecl(Destructor, Param->getLocation());
8935 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00008936 }
8937 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00008938 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008939
8940 // Parameters with the pass_object_size attribute only need to be marked
8941 // constant at function definitions. Because we lack information about
8942 // whether we're on a declaration or definition when we're instantiating the
8943 // attribute, we need to check for constness here.
8944 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
8945 if (!Param->getType().isConstQualified())
8946 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
8947 << Attr->getSpelling() << 1;
Mike Stump0c2ec772010-01-21 03:59:47 +00008948 }
8949
8950 return HasInvalidParm;
8951}
John McCall2b5c1b22010-08-12 21:44:57 +00008952
8953/// CheckCastAlign - Implements -Wcast-align, which warns when a
8954/// pointer cast increases the alignment requirements.
8955void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
8956 // This is actually a lot of work to potentially be doing on every
8957 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00008958 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +00008959 return;
8960
8961 // Ignore dependent types.
8962 if (T->isDependentType() || Op->getType()->isDependentType())
8963 return;
8964
8965 // Require that the destination be a pointer type.
8966 const PointerType *DestPtr = T->getAs<PointerType>();
8967 if (!DestPtr) return;
8968
8969 // If the destination has alignment 1, we're done.
8970 QualType DestPointee = DestPtr->getPointeeType();
8971 if (DestPointee->isIncompleteType()) return;
8972 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
8973 if (DestAlign.isOne()) return;
8974
8975 // Require that the source be a pointer type.
8976 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
8977 if (!SrcPtr) return;
8978 QualType SrcPointee = SrcPtr->getPointeeType();
8979
8980 // Whitelist casts from cv void*. We already implicitly
8981 // whitelisted casts to cv void*, since they have alignment 1.
8982 // Also whitelist casts involving incomplete types, which implicitly
8983 // includes 'void'.
8984 if (SrcPointee->isIncompleteType()) return;
8985
8986 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
8987 if (SrcAlign >= DestAlign) return;
8988
8989 Diag(TRange.getBegin(), diag::warn_cast_align)
8990 << Op->getType() << T
8991 << static_cast<unsigned>(SrcAlign.getQuantity())
8992 << static_cast<unsigned>(DestAlign.getQuantity())
8993 << TRange << Op->getSourceRange();
8994}
8995
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008996static const Type* getElementType(const Expr *BaseExpr) {
8997 const Type* EltType = BaseExpr->getType().getTypePtr();
8998 if (EltType->isAnyPointerType())
8999 return EltType->getPointeeType().getTypePtr();
9000 else if (EltType->isArrayType())
9001 return EltType->getBaseElementTypeUnsafe();
9002 return EltType;
9003}
9004
Chandler Carruth28389f02011-08-05 09:10:50 +00009005/// \brief Check whether this array fits the idiom of a size-one tail padded
9006/// array member of a struct.
9007///
9008/// We avoid emitting out-of-bounds access warnings for such arrays as they are
9009/// commonly used to emulate flexible arrays in C89 code.
9010static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
9011 const NamedDecl *ND) {
9012 if (Size != 1 || !ND) return false;
9013
9014 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
9015 if (!FD) return false;
9016
9017 // Don't consider sizes resulting from macro expansions or template argument
9018 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +00009019
9020 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00009021 while (TInfo) {
9022 TypeLoc TL = TInfo->getTypeLoc();
9023 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +00009024 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
9025 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00009026 TInfo = TDL->getTypeSourceInfo();
9027 continue;
9028 }
David Blaikie6adc78e2013-02-18 22:06:02 +00009029 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
9030 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +00009031 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
9032 return false;
9033 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +00009034 break;
Sean Callanan06a48a62012-05-04 18:22:53 +00009035 }
Chandler Carruth28389f02011-08-05 09:10:50 +00009036
9037 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +00009038 if (!RD) return false;
9039 if (RD->isUnion()) return false;
9040 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
9041 if (!CRD->isStandardLayout()) return false;
9042 }
Chandler Carruth28389f02011-08-05 09:10:50 +00009043
Benjamin Kramer8c543672011-08-06 03:04:42 +00009044 // See if this is the last field decl in the record.
9045 const Decl *D = FD;
9046 while ((D = D->getNextDeclInContext()))
9047 if (isa<FieldDecl>(D))
9048 return false;
9049 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +00009050}
9051
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009052void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009053 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +00009054 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +00009055 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009056 if (IndexExpr->isValueDependent())
9057 return;
9058
Matt Beaumont-Gay9d570c42011-12-12 22:35:02 +00009059 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009060 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009061 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009062 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009063 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +00009064 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +00009065
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009066 llvm::APSInt index;
Richard Smith0c6124b2015-12-03 01:36:22 +00009067 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
Ted Kremenek64699be2011-02-16 01:57:07 +00009068 return;
Richard Smith13f67182011-12-16 19:31:14 +00009069 if (IndexNegated)
9070 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +00009071
Craig Topperc3ec1492014-05-26 06:22:03 +00009072 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +00009073 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
9074 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +00009075 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +00009076 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +00009077
Ted Kremeneke4b316c2011-02-23 23:06:04 +00009078 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00009079 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +00009080 if (!size.isStrictlyPositive())
9081 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009082
9083 const Type* BaseType = getElementType(BaseExpr);
Nico Weber7c299802011-09-17 22:59:41 +00009084 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009085 // Make sure we're comparing apples to apples when comparing index to size
9086 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
9087 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +00009088 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +00009089 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009090 if (ptrarith_typesize != array_typesize) {
9091 // There's a cast to a different size type involved
9092 uint64_t ratio = array_typesize / ptrarith_typesize;
9093 // TODO: Be smarter about handling cases where array_typesize is not a
9094 // multiple of ptrarith_typesize
9095 if (ptrarith_typesize * ratio == array_typesize)
9096 size *= llvm::APInt(size.getBitWidth(), ratio);
9097 }
9098 }
9099
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009100 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00009101 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00009102 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00009103 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00009104
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009105 // For array subscripting the index must be less than size, but for pointer
9106 // arithmetic also allow the index (offset) to be equal to size since
9107 // computing the next address after the end of the array is legal and
9108 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +00009109 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +00009110 return;
9111
9112 // Also don't warn for arrays of size 1 which are members of some
9113 // structure. These are often used to approximate flexible arrays in C89
9114 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009115 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +00009116 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009117
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009118 // Suppress the warning if the subscript expression (as identified by the
9119 // ']' location) and the index expression are both from macro expansions
9120 // within a system header.
9121 if (ASE) {
9122 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
9123 ASE->getRBracketLoc());
9124 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
9125 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
9126 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +00009127 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009128 return;
9129 }
9130 }
9131
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009132 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009133 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009134 DiagID = diag::warn_array_index_exceeds_bounds;
9135
9136 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
9137 PDiag(DiagID) << index.toString(10, true)
9138 << size.toString(10, true)
9139 << (unsigned)size.getLimitedValue(~0U)
9140 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009141 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009142 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009143 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009144 DiagID = diag::warn_ptr_arith_precedes_bounds;
9145 if (index.isNegative()) index = -index;
9146 }
9147
9148 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
9149 PDiag(DiagID) << index.toString(10, true)
9150 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +00009151 }
Chandler Carruth1af88f12011-02-17 21:10:52 +00009152
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +00009153 if (!ND) {
9154 // Try harder to find a NamedDecl to point at in the note.
9155 while (const ArraySubscriptExpr *ASE =
9156 dyn_cast<ArraySubscriptExpr>(BaseExpr))
9157 BaseExpr = ASE->getBase()->IgnoreParenCasts();
9158 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
9159 ND = dyn_cast<NamedDecl>(DRE->getDecl());
9160 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
9161 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
9162 }
9163
Chandler Carruth1af88f12011-02-17 21:10:52 +00009164 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009165 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
9166 PDiag(diag::note_array_index_out_of_bounds)
9167 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +00009168}
9169
Ted Kremenekdf26df72011-03-01 18:41:00 +00009170void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009171 int AllowOnePastEnd = 0;
9172 while (expr) {
9173 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +00009174 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009175 case Stmt::ArraySubscriptExprClass: {
9176 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009177 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009178 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +00009179 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009180 }
Alexey Bataev1a3320e2015-08-25 14:24:04 +00009181 case Stmt::OMPArraySectionExprClass: {
9182 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
9183 if (ASE->getLowerBound())
9184 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
9185 /*ASE=*/nullptr, AllowOnePastEnd > 0);
9186 return;
9187 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009188 case Stmt::UnaryOperatorClass: {
9189 // Only unwrap the * and & unary operators
9190 const UnaryOperator *UO = cast<UnaryOperator>(expr);
9191 expr = UO->getSubExpr();
9192 switch (UO->getOpcode()) {
9193 case UO_AddrOf:
9194 AllowOnePastEnd++;
9195 break;
9196 case UO_Deref:
9197 AllowOnePastEnd--;
9198 break;
9199 default:
9200 return;
9201 }
9202 break;
9203 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00009204 case Stmt::ConditionalOperatorClass: {
9205 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
9206 if (const Expr *lhs = cond->getLHS())
9207 CheckArrayAccess(lhs);
9208 if (const Expr *rhs = cond->getRHS())
9209 CheckArrayAccess(rhs);
9210 return;
9211 }
9212 default:
9213 return;
9214 }
Peter Collingbourne91147592011-04-15 00:35:48 +00009215 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00009216}
John McCall31168b02011-06-15 23:02:42 +00009217
9218//===--- CHECK: Objective-C retain cycles ----------------------------------//
9219
9220namespace {
9221 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +00009222 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +00009223 VarDecl *Variable;
9224 SourceRange Range;
9225 SourceLocation Loc;
9226 bool Indirect;
9227
9228 void setLocsFrom(Expr *e) {
9229 Loc = e->getExprLoc();
9230 Range = e->getSourceRange();
9231 }
9232 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009233} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +00009234
9235/// Consider whether capturing the given variable can possibly lead to
9236/// a retain cycle.
9237static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00009238 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +00009239 // lifetime. In MRR, it's captured strongly if the variable is
9240 // __block and has an appropriate type.
9241 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
9242 return false;
9243
9244 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00009245 if (ref)
9246 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +00009247 return true;
9248}
9249
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009250static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +00009251 while (true) {
9252 e = e->IgnoreParens();
9253 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
9254 switch (cast->getCastKind()) {
9255 case CK_BitCast:
9256 case CK_LValueBitCast:
9257 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00009258 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +00009259 e = cast->getSubExpr();
9260 continue;
9261
John McCall31168b02011-06-15 23:02:42 +00009262 default:
9263 return false;
9264 }
9265 }
9266
9267 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
9268 ObjCIvarDecl *ivar = ref->getDecl();
9269 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
9270 return false;
9271
9272 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009273 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +00009274 return false;
9275
9276 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
9277 owner.Indirect = true;
9278 return true;
9279 }
9280
9281 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
9282 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
9283 if (!var) return false;
9284 return considerVariable(var, ref, owner);
9285 }
9286
John McCall31168b02011-06-15 23:02:42 +00009287 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
9288 if (member->isArrow()) return false;
9289
9290 // Don't count this as an indirect ownership.
9291 e = member->getBase();
9292 continue;
9293 }
9294
John McCallfe96e0b2011-11-06 09:01:30 +00009295 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
9296 // Only pay attention to pseudo-objects on property references.
9297 ObjCPropertyRefExpr *pre
9298 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
9299 ->IgnoreParens());
9300 if (!pre) return false;
9301 if (pre->isImplicitProperty()) return false;
9302 ObjCPropertyDecl *property = pre->getExplicitProperty();
9303 if (!property->isRetaining() &&
9304 !(property->getPropertyIvarDecl() &&
9305 property->getPropertyIvarDecl()->getType()
9306 .getObjCLifetime() == Qualifiers::OCL_Strong))
9307 return false;
9308
9309 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009310 if (pre->isSuperReceiver()) {
9311 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
9312 if (!owner.Variable)
9313 return false;
9314 owner.Loc = pre->getLocation();
9315 owner.Range = pre->getSourceRange();
9316 return true;
9317 }
John McCallfe96e0b2011-11-06 09:01:30 +00009318 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
9319 ->getSourceExpr());
9320 continue;
9321 }
9322
John McCall31168b02011-06-15 23:02:42 +00009323 // Array ivars?
9324
9325 return false;
9326 }
9327}
9328
9329namespace {
9330 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
9331 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
9332 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00009333 Context(Context), Variable(variable), Capturer(nullptr),
9334 VarWillBeReased(false) {}
9335 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +00009336 VarDecl *Variable;
9337 Expr *Capturer;
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00009338 bool VarWillBeReased;
John McCall31168b02011-06-15 23:02:42 +00009339
9340 void VisitDeclRefExpr(DeclRefExpr *ref) {
9341 if (ref->getDecl() == Variable && !Capturer)
9342 Capturer = ref;
9343 }
9344
John McCall31168b02011-06-15 23:02:42 +00009345 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
9346 if (Capturer) return;
9347 Visit(ref->getBase());
9348 if (Capturer && ref->isFreeIvar())
9349 Capturer = ref;
9350 }
9351
9352 void VisitBlockExpr(BlockExpr *block) {
9353 // Look inside nested blocks
9354 if (block->getBlockDecl()->capturesVariable(Variable))
9355 Visit(block->getBlockDecl()->getBody());
9356 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +00009357
9358 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
9359 if (Capturer) return;
9360 if (OVE->getSourceExpr())
9361 Visit(OVE->getSourceExpr());
9362 }
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00009363 void VisitBinaryOperator(BinaryOperator *BinOp) {
9364 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
9365 return;
9366 Expr *LHS = BinOp->getLHS();
9367 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
9368 if (DRE->getDecl() != Variable)
9369 return;
9370 if (Expr *RHS = BinOp->getRHS()) {
9371 RHS = RHS->IgnoreParenCasts();
9372 llvm::APSInt Value;
9373 VarWillBeReased =
9374 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
9375 }
9376 }
9377 }
John McCall31168b02011-06-15 23:02:42 +00009378 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009379} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +00009380
9381/// Check whether the given argument is a block which captures a
9382/// variable.
9383static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
9384 assert(owner.Variable && owner.Loc.isValid());
9385
9386 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +00009387
9388 // Look through [^{...} copy] and Block_copy(^{...}).
9389 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
9390 Selector Cmd = ME->getSelector();
9391 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
9392 e = ME->getInstanceReceiver();
9393 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +00009394 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +00009395 e = e->IgnoreParenCasts();
9396 }
9397 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
9398 if (CE->getNumArgs() == 1) {
9399 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +00009400 if (Fn) {
9401 const IdentifierInfo *FnI = Fn->getIdentifier();
9402 if (FnI && FnI->isStr("_Block_copy")) {
9403 e = CE->getArg(0)->IgnoreParenCasts();
9404 }
9405 }
Jordan Rose67e887c2012-09-17 17:54:30 +00009406 }
9407 }
9408
John McCall31168b02011-06-15 23:02:42 +00009409 BlockExpr *block = dyn_cast<BlockExpr>(e);
9410 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +00009411 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00009412
9413 FindCaptureVisitor visitor(S.Context, owner.Variable);
9414 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00009415 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +00009416}
9417
9418static void diagnoseRetainCycle(Sema &S, Expr *capturer,
9419 RetainCycleOwner &owner) {
9420 assert(capturer);
9421 assert(owner.Variable && owner.Loc.isValid());
9422
9423 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
9424 << owner.Variable << capturer->getSourceRange();
9425 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
9426 << owner.Indirect << owner.Range;
9427}
9428
9429/// Check for a keyword selector that starts with the word 'add' or
9430/// 'set'.
9431static bool isSetterLikeSelector(Selector sel) {
9432 if (sel.isUnarySelector()) return false;
9433
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009434 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +00009435 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +00009436 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +00009437 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +00009438 else if (str.startswith("add")) {
9439 // Specially whitelist 'addOperationWithBlock:'.
9440 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
9441 return false;
9442 str = str.substr(3);
9443 }
John McCall31168b02011-06-15 23:02:42 +00009444 else
9445 return false;
9446
9447 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +00009448 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +00009449}
9450
Benjamin Kramer3a743452015-03-09 15:03:32 +00009451static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
9452 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +00009453 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
9454 Message->getReceiverInterface(),
9455 NSAPI::ClassId_NSMutableArray);
9456 if (!IsMutableArray) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009457 return None;
9458 }
9459
9460 Selector Sel = Message->getSelector();
9461
9462 Optional<NSAPI::NSArrayMethodKind> MKOpt =
9463 S.NSAPIObj->getNSArrayMethodKind(Sel);
9464 if (!MKOpt) {
9465 return None;
9466 }
9467
9468 NSAPI::NSArrayMethodKind MK = *MKOpt;
9469
9470 switch (MK) {
9471 case NSAPI::NSMutableArr_addObject:
9472 case NSAPI::NSMutableArr_insertObjectAtIndex:
9473 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
9474 return 0;
9475 case NSAPI::NSMutableArr_replaceObjectAtIndex:
9476 return 1;
9477
9478 default:
9479 return None;
9480 }
9481
9482 return None;
9483}
9484
9485static
9486Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
9487 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +00009488 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
9489 Message->getReceiverInterface(),
9490 NSAPI::ClassId_NSMutableDictionary);
9491 if (!IsMutableDictionary) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009492 return None;
9493 }
9494
9495 Selector Sel = Message->getSelector();
9496
9497 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
9498 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
9499 if (!MKOpt) {
9500 return None;
9501 }
9502
9503 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
9504
9505 switch (MK) {
9506 case NSAPI::NSMutableDict_setObjectForKey:
9507 case NSAPI::NSMutableDict_setValueForKey:
9508 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
9509 return 0;
9510
9511 default:
9512 return None;
9513 }
9514
9515 return None;
9516}
9517
9518static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +00009519 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
9520 Message->getReceiverInterface(),
9521 NSAPI::ClassId_NSMutableSet);
Alex Denisove1d882c2015-03-04 17:55:52 +00009522
Alex Denisov5dfac812015-08-06 04:51:14 +00009523 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
9524 Message->getReceiverInterface(),
9525 NSAPI::ClassId_NSMutableOrderedSet);
9526 if (!IsMutableSet && !IsMutableOrderedSet) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009527 return None;
9528 }
9529
9530 Selector Sel = Message->getSelector();
9531
9532 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
9533 if (!MKOpt) {
9534 return None;
9535 }
9536
9537 NSAPI::NSSetMethodKind MK = *MKOpt;
9538
9539 switch (MK) {
9540 case NSAPI::NSMutableSet_addObject:
9541 case NSAPI::NSOrderedSet_setObjectAtIndex:
9542 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
9543 case NSAPI::NSOrderedSet_insertObjectAtIndex:
9544 return 0;
9545 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
9546 return 1;
9547 }
9548
9549 return None;
9550}
9551
9552void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
9553 if (!Message->isInstanceMessage()) {
9554 return;
9555 }
9556
9557 Optional<int> ArgOpt;
9558
9559 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
9560 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
9561 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
9562 return;
9563 }
9564
9565 int ArgIndex = *ArgOpt;
9566
Alex Denisove1d882c2015-03-04 17:55:52 +00009567 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
9568 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
9569 Arg = OE->getSourceExpr()->IgnoreImpCasts();
9570 }
9571
Alex Denisov5dfac812015-08-06 04:51:14 +00009572 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009573 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
Alex Denisov5dfac812015-08-06 04:51:14 +00009574 if (ArgRE->isObjCSelfExpr()) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009575 Diag(Message->getSourceRange().getBegin(),
9576 diag::warn_objc_circular_container)
Alex Denisov5dfac812015-08-06 04:51:14 +00009577 << ArgRE->getDecl()->getName() << StringRef("super");
Alex Denisove1d882c2015-03-04 17:55:52 +00009578 }
9579 }
Alex Denisov5dfac812015-08-06 04:51:14 +00009580 } else {
9581 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
9582
9583 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
9584 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
9585 }
9586
9587 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
9588 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
9589 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
9590 ValueDecl *Decl = ReceiverRE->getDecl();
9591 Diag(Message->getSourceRange().getBegin(),
9592 diag::warn_objc_circular_container)
9593 << Decl->getName() << Decl->getName();
9594 if (!ArgRE->isObjCSelfExpr()) {
9595 Diag(Decl->getLocation(),
9596 diag::note_objc_circular_container_declared_here)
9597 << Decl->getName();
9598 }
9599 }
9600 }
9601 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
9602 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
9603 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
9604 ObjCIvarDecl *Decl = IvarRE->getDecl();
9605 Diag(Message->getSourceRange().getBegin(),
9606 diag::warn_objc_circular_container)
9607 << Decl->getName() << Decl->getName();
9608 Diag(Decl->getLocation(),
9609 diag::note_objc_circular_container_declared_here)
9610 << Decl->getName();
9611 }
Alex Denisove1d882c2015-03-04 17:55:52 +00009612 }
9613 }
9614 }
Alex Denisove1d882c2015-03-04 17:55:52 +00009615}
9616
John McCall31168b02011-06-15 23:02:42 +00009617/// Check a message send to see if it's likely to cause a retain cycle.
9618void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
9619 // Only check instance methods whose selector looks like a setter.
9620 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
9621 return;
9622
9623 // Try to find a variable that the receiver is strongly owned by.
9624 RetainCycleOwner owner;
9625 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009626 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +00009627 return;
9628 } else {
9629 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
9630 owner.Variable = getCurMethodDecl()->getSelfDecl();
9631 owner.Loc = msg->getSuperLoc();
9632 owner.Range = msg->getSuperLoc();
9633 }
9634
9635 // Check whether the receiver is captured by any of the arguments.
9636 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
9637 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
9638 return diagnoseRetainCycle(*this, capturer, owner);
9639}
9640
9641/// Check a property assign to see if it's likely to cause a retain cycle.
9642void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
9643 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009644 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +00009645 return;
9646
9647 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
9648 diagnoseRetainCycle(*this, capturer, owner);
9649}
9650
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00009651void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
9652 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +00009653 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00009654 return;
9655
9656 // Because we don't have an expression for the variable, we have to set the
9657 // location explicitly here.
9658 Owner.Loc = Var->getLocation();
9659 Owner.Range = Var->getSourceRange();
9660
9661 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
9662 diagnoseRetainCycle(*this, Capturer, Owner);
9663}
9664
Ted Kremenek9304da92012-12-21 08:04:28 +00009665static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
9666 Expr *RHS, bool isProperty) {
9667 // Check if RHS is an Objective-C object literal, which also can get
9668 // immediately zapped in a weak reference. Note that we explicitly
9669 // allow ObjCStringLiterals, since those are designed to never really die.
9670 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00009671
Ted Kremenek64873352012-12-21 22:46:35 +00009672 // This enum needs to match with the 'select' in
9673 // warn_objc_arc_literal_assign (off-by-1).
9674 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
9675 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
9676 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00009677
9678 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +00009679 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +00009680 << (isProperty ? 0 : 1)
9681 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00009682
9683 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +00009684}
9685
Ted Kremenekc1f014a2012-12-21 19:45:30 +00009686static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
9687 Qualifiers::ObjCLifetime LT,
9688 Expr *RHS, bool isProperty) {
9689 // Strip off any implicit cast added to get to the one ARC-specific.
9690 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
9691 if (cast->getCastKind() == CK_ARCConsumeObject) {
9692 S.Diag(Loc, diag::warn_arc_retained_assign)
9693 << (LT == Qualifiers::OCL_ExplicitNone)
9694 << (isProperty ? 0 : 1)
9695 << RHS->getSourceRange();
9696 return true;
9697 }
9698 RHS = cast->getSubExpr();
9699 }
9700
9701 if (LT == Qualifiers::OCL_Weak &&
9702 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
9703 return true;
9704
9705 return false;
9706}
9707
Ted Kremenekb36234d2012-12-21 08:04:20 +00009708bool Sema::checkUnsafeAssigns(SourceLocation Loc,
9709 QualType LHS, Expr *RHS) {
9710 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
9711
9712 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
9713 return false;
9714
9715 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
9716 return true;
9717
9718 return false;
9719}
9720
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009721void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
9722 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009723 QualType LHSType;
9724 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +00009725 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009726 ObjCPropertyRefExpr *PRE
9727 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
9728 if (PRE && !PRE->isImplicitProperty()) {
9729 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
9730 if (PD)
9731 LHSType = PD->getType();
9732 }
9733
9734 if (LHSType.isNull())
9735 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +00009736
9737 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
9738
9739 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009740 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +00009741 getCurFunction()->markSafeWeakUse(LHS);
9742 }
9743
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009744 if (checkUnsafeAssigns(Loc, LHSType, RHS))
9745 return;
Jordan Rose657b5f42012-09-28 22:21:35 +00009746
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009747 // FIXME. Check for other life times.
9748 if (LT != Qualifiers::OCL_None)
9749 return;
9750
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009751 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009752 if (PRE->isImplicitProperty())
9753 return;
9754 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
9755 if (!PD)
9756 return;
9757
Bill Wendling44426052012-12-20 19:22:21 +00009758 unsigned Attributes = PD->getPropertyAttributes();
9759 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009760 // when 'assign' attribute was not explicitly specified
9761 // by user, ignore it and rely on property type itself
9762 // for lifetime info.
9763 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
9764 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
9765 LHSType->isObjCRetainableType())
9766 return;
9767
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009768 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +00009769 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009770 Diag(Loc, diag::warn_arc_retained_property_assign)
9771 << RHS->getSourceRange();
9772 return;
9773 }
9774 RHS = cast->getSubExpr();
9775 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009776 }
Bill Wendling44426052012-12-20 19:22:21 +00009777 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +00009778 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
9779 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +00009780 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009781 }
9782}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009783
9784//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
9785
9786namespace {
9787bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
9788 SourceLocation StmtLoc,
9789 const NullStmt *Body) {
9790 // Do not warn if the body is a macro that expands to nothing, e.g:
9791 //
9792 // #define CALL(x)
9793 // if (condition)
9794 // CALL(0);
9795 //
9796 if (Body->hasLeadingEmptyMacro())
9797 return false;
9798
9799 // Get line numbers of statement and body.
9800 bool StmtLineInvalid;
Dmitri Gribenkoad80af82015-03-15 01:08:23 +00009801 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009802 &StmtLineInvalid);
9803 if (StmtLineInvalid)
9804 return false;
9805
9806 bool BodyLineInvalid;
9807 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
9808 &BodyLineInvalid);
9809 if (BodyLineInvalid)
9810 return false;
9811
9812 // Warn if null statement and body are on the same line.
9813 if (StmtLine != BodyLine)
9814 return false;
9815
9816 return true;
9817}
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009818} // end anonymous namespace
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009819
9820void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
9821 const Stmt *Body,
9822 unsigned DiagID) {
9823 // Since this is a syntactic check, don't emit diagnostic for template
9824 // instantiations, this just adds noise.
9825 if (CurrentInstantiationScope)
9826 return;
9827
9828 // The body should be a null statement.
9829 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
9830 if (!NBody)
9831 return;
9832
9833 // Do the usual checks.
9834 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
9835 return;
9836
9837 Diag(NBody->getSemiLoc(), DiagID);
9838 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
9839}
9840
9841void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
9842 const Stmt *PossibleBody) {
9843 assert(!CurrentInstantiationScope); // Ensured by caller
9844
9845 SourceLocation StmtLoc;
9846 const Stmt *Body;
9847 unsigned DiagID;
9848 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
9849 StmtLoc = FS->getRParenLoc();
9850 Body = FS->getBody();
9851 DiagID = diag::warn_empty_for_body;
9852 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
9853 StmtLoc = WS->getCond()->getSourceRange().getEnd();
9854 Body = WS->getBody();
9855 DiagID = diag::warn_empty_while_body;
9856 } else
9857 return; // Neither `for' nor `while'.
9858
9859 // The body should be a null statement.
9860 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
9861 if (!NBody)
9862 return;
9863
9864 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009865 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009866 return;
9867
9868 // Do the usual checks.
9869 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
9870 return;
9871
9872 // `for(...);' and `while(...);' are popular idioms, so in order to keep
9873 // noise level low, emit diagnostics only if for/while is followed by a
9874 // CompoundStmt, e.g.:
9875 // for (int i = 0; i < n; i++);
9876 // {
9877 // a(i);
9878 // }
9879 // or if for/while is followed by a statement with more indentation
9880 // than for/while itself:
9881 // for (int i = 0; i < n; i++);
9882 // a(i);
9883 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
9884 if (!ProbableTypo) {
9885 bool BodyColInvalid;
9886 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
9887 PossibleBody->getLocStart(),
9888 &BodyColInvalid);
9889 if (BodyColInvalid)
9890 return;
9891
9892 bool StmtColInvalid;
9893 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
9894 S->getLocStart(),
9895 &StmtColInvalid);
9896 if (StmtColInvalid)
9897 return;
9898
9899 if (BodyCol > StmtCol)
9900 ProbableTypo = true;
9901 }
9902
9903 if (ProbableTypo) {
9904 Diag(NBody->getSemiLoc(), DiagID);
9905 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
9906 }
9907}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009908
Richard Trieu36d0b2b2015-01-13 02:32:02 +00009909//===--- CHECK: Warn on self move with std::move. -------------------------===//
9910
9911/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
9912void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
9913 SourceLocation OpLoc) {
Richard Trieu36d0b2b2015-01-13 02:32:02 +00009914 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
9915 return;
9916
9917 if (!ActiveTemplateInstantiations.empty())
9918 return;
9919
9920 // Strip parens and casts away.
9921 LHSExpr = LHSExpr->IgnoreParenImpCasts();
9922 RHSExpr = RHSExpr->IgnoreParenImpCasts();
9923
9924 // Check for a call expression
9925 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
9926 if (!CE || CE->getNumArgs() != 1)
9927 return;
9928
9929 // Check for a call to std::move
9930 const FunctionDecl *FD = CE->getDirectCallee();
9931 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
9932 !FD->getIdentifier()->isStr("move"))
9933 return;
9934
9935 // Get argument from std::move
9936 RHSExpr = CE->getArg(0);
9937
9938 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
9939 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
9940
9941 // Two DeclRefExpr's, check that the decls are the same.
9942 if (LHSDeclRef && RHSDeclRef) {
9943 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
9944 return;
9945 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
9946 RHSDeclRef->getDecl()->getCanonicalDecl())
9947 return;
9948
9949 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
9950 << LHSExpr->getSourceRange()
9951 << RHSExpr->getSourceRange();
9952 return;
9953 }
9954
9955 // Member variables require a different approach to check for self moves.
9956 // MemberExpr's are the same if every nested MemberExpr refers to the same
9957 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
9958 // the base Expr's are CXXThisExpr's.
9959 const Expr *LHSBase = LHSExpr;
9960 const Expr *RHSBase = RHSExpr;
9961 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
9962 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
9963 if (!LHSME || !RHSME)
9964 return;
9965
9966 while (LHSME && RHSME) {
9967 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
9968 RHSME->getMemberDecl()->getCanonicalDecl())
9969 return;
9970
9971 LHSBase = LHSME->getBase();
9972 RHSBase = RHSME->getBase();
9973 LHSME = dyn_cast<MemberExpr>(LHSBase);
9974 RHSME = dyn_cast<MemberExpr>(RHSBase);
9975 }
9976
9977 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
9978 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
9979 if (LHSDeclRef && RHSDeclRef) {
9980 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
9981 return;
9982 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
9983 RHSDeclRef->getDecl()->getCanonicalDecl())
9984 return;
9985
9986 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
9987 << LHSExpr->getSourceRange()
9988 << RHSExpr->getSourceRange();
9989 return;
9990 }
9991
9992 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
9993 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
9994 << LHSExpr->getSourceRange()
9995 << RHSExpr->getSourceRange();
9996}
9997
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009998//===--- Layout compatibility ----------------------------------------------//
9999
10000namespace {
10001
10002bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
10003
10004/// \brief Check if two enumeration types are layout-compatible.
10005bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
10006 // C++11 [dcl.enum] p8:
10007 // Two enumeration types are layout-compatible if they have the same
10008 // underlying type.
10009 return ED1->isComplete() && ED2->isComplete() &&
10010 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
10011}
10012
10013/// \brief Check if two fields are layout-compatible.
10014bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
10015 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
10016 return false;
10017
10018 if (Field1->isBitField() != Field2->isBitField())
10019 return false;
10020
10021 if (Field1->isBitField()) {
10022 // Make sure that the bit-fields are the same length.
10023 unsigned Bits1 = Field1->getBitWidthValue(C);
10024 unsigned Bits2 = Field2->getBitWidthValue(C);
10025
10026 if (Bits1 != Bits2)
10027 return false;
10028 }
10029
10030 return true;
10031}
10032
10033/// \brief Check if two standard-layout structs are layout-compatible.
10034/// (C++11 [class.mem] p17)
10035bool isLayoutCompatibleStruct(ASTContext &C,
10036 RecordDecl *RD1,
10037 RecordDecl *RD2) {
10038 // If both records are C++ classes, check that base classes match.
10039 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
10040 // If one of records is a CXXRecordDecl we are in C++ mode,
10041 // thus the other one is a CXXRecordDecl, too.
10042 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
10043 // Check number of base classes.
10044 if (D1CXX->getNumBases() != D2CXX->getNumBases())
10045 return false;
10046
10047 // Check the base classes.
10048 for (CXXRecordDecl::base_class_const_iterator
10049 Base1 = D1CXX->bases_begin(),
10050 BaseEnd1 = D1CXX->bases_end(),
10051 Base2 = D2CXX->bases_begin();
10052 Base1 != BaseEnd1;
10053 ++Base1, ++Base2) {
10054 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
10055 return false;
10056 }
10057 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
10058 // If only RD2 is a C++ class, it should have zero base classes.
10059 if (D2CXX->getNumBases() > 0)
10060 return false;
10061 }
10062
10063 // Check the fields.
10064 RecordDecl::field_iterator Field2 = RD2->field_begin(),
10065 Field2End = RD2->field_end(),
10066 Field1 = RD1->field_begin(),
10067 Field1End = RD1->field_end();
10068 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
10069 if (!isLayoutCompatible(C, *Field1, *Field2))
10070 return false;
10071 }
10072 if (Field1 != Field1End || Field2 != Field2End)
10073 return false;
10074
10075 return true;
10076}
10077
10078/// \brief Check if two standard-layout unions are layout-compatible.
10079/// (C++11 [class.mem] p18)
10080bool isLayoutCompatibleUnion(ASTContext &C,
10081 RecordDecl *RD1,
10082 RecordDecl *RD2) {
10083 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010084 for (auto *Field2 : RD2->fields())
10085 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010086
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010087 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010088 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
10089 I = UnmatchedFields.begin(),
10090 E = UnmatchedFields.end();
10091
10092 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010093 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010094 bool Result = UnmatchedFields.erase(*I);
10095 (void) Result;
10096 assert(Result);
10097 break;
10098 }
10099 }
10100 if (I == E)
10101 return false;
10102 }
10103
10104 return UnmatchedFields.empty();
10105}
10106
10107bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
10108 if (RD1->isUnion() != RD2->isUnion())
10109 return false;
10110
10111 if (RD1->isUnion())
10112 return isLayoutCompatibleUnion(C, RD1, RD2);
10113 else
10114 return isLayoutCompatibleStruct(C, RD1, RD2);
10115}
10116
10117/// \brief Check if two types are layout-compatible in C++11 sense.
10118bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
10119 if (T1.isNull() || T2.isNull())
10120 return false;
10121
10122 // C++11 [basic.types] p11:
10123 // If two types T1 and T2 are the same type, then T1 and T2 are
10124 // layout-compatible types.
10125 if (C.hasSameType(T1, T2))
10126 return true;
10127
10128 T1 = T1.getCanonicalType().getUnqualifiedType();
10129 T2 = T2.getCanonicalType().getUnqualifiedType();
10130
10131 const Type::TypeClass TC1 = T1->getTypeClass();
10132 const Type::TypeClass TC2 = T2->getTypeClass();
10133
10134 if (TC1 != TC2)
10135 return false;
10136
10137 if (TC1 == Type::Enum) {
10138 return isLayoutCompatible(C,
10139 cast<EnumType>(T1)->getDecl(),
10140 cast<EnumType>(T2)->getDecl());
10141 } else if (TC1 == Type::Record) {
10142 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
10143 return false;
10144
10145 return isLayoutCompatible(C,
10146 cast<RecordType>(T1)->getDecl(),
10147 cast<RecordType>(T2)->getDecl());
10148 }
10149
10150 return false;
10151}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010152} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010153
10154//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
10155
10156namespace {
10157/// \brief Given a type tag expression find the type tag itself.
10158///
10159/// \param TypeExpr Type tag expression, as it appears in user's code.
10160///
10161/// \param VD Declaration of an identifier that appears in a type tag.
10162///
10163/// \param MagicValue Type tag magic value.
10164bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
10165 const ValueDecl **VD, uint64_t *MagicValue) {
10166 while(true) {
10167 if (!TypeExpr)
10168 return false;
10169
10170 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
10171
10172 switch (TypeExpr->getStmtClass()) {
10173 case Stmt::UnaryOperatorClass: {
10174 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
10175 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
10176 TypeExpr = UO->getSubExpr();
10177 continue;
10178 }
10179 return false;
10180 }
10181
10182 case Stmt::DeclRefExprClass: {
10183 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
10184 *VD = DRE->getDecl();
10185 return true;
10186 }
10187
10188 case Stmt::IntegerLiteralClass: {
10189 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
10190 llvm::APInt MagicValueAPInt = IL->getValue();
10191 if (MagicValueAPInt.getActiveBits() <= 64) {
10192 *MagicValue = MagicValueAPInt.getZExtValue();
10193 return true;
10194 } else
10195 return false;
10196 }
10197
10198 case Stmt::BinaryConditionalOperatorClass:
10199 case Stmt::ConditionalOperatorClass: {
10200 const AbstractConditionalOperator *ACO =
10201 cast<AbstractConditionalOperator>(TypeExpr);
10202 bool Result;
10203 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
10204 if (Result)
10205 TypeExpr = ACO->getTrueExpr();
10206 else
10207 TypeExpr = ACO->getFalseExpr();
10208 continue;
10209 }
10210 return false;
10211 }
10212
10213 case Stmt::BinaryOperatorClass: {
10214 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
10215 if (BO->getOpcode() == BO_Comma) {
10216 TypeExpr = BO->getRHS();
10217 continue;
10218 }
10219 return false;
10220 }
10221
10222 default:
10223 return false;
10224 }
10225 }
10226}
10227
10228/// \brief Retrieve the C type corresponding to type tag TypeExpr.
10229///
10230/// \param TypeExpr Expression that specifies a type tag.
10231///
10232/// \param MagicValues Registered magic values.
10233///
10234/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
10235/// kind.
10236///
10237/// \param TypeInfo Information about the corresponding C type.
10238///
10239/// \returns true if the corresponding C type was found.
10240bool GetMatchingCType(
10241 const IdentifierInfo *ArgumentKind,
10242 const Expr *TypeExpr, const ASTContext &Ctx,
10243 const llvm::DenseMap<Sema::TypeTagMagicValue,
10244 Sema::TypeTagData> *MagicValues,
10245 bool &FoundWrongKind,
10246 Sema::TypeTagData &TypeInfo) {
10247 FoundWrongKind = false;
10248
10249 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +000010250 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010251
10252 uint64_t MagicValue;
10253
10254 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
10255 return false;
10256
10257 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +000010258 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010259 if (I->getArgumentKind() != ArgumentKind) {
10260 FoundWrongKind = true;
10261 return false;
10262 }
10263 TypeInfo.Type = I->getMatchingCType();
10264 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
10265 TypeInfo.MustBeNull = I->getMustBeNull();
10266 return true;
10267 }
10268 return false;
10269 }
10270
10271 if (!MagicValues)
10272 return false;
10273
10274 llvm::DenseMap<Sema::TypeTagMagicValue,
10275 Sema::TypeTagData>::const_iterator I =
10276 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
10277 if (I == MagicValues->end())
10278 return false;
10279
10280 TypeInfo = I->second;
10281 return true;
10282}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010283} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010284
10285void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
10286 uint64_t MagicValue, QualType Type,
10287 bool LayoutCompatible,
10288 bool MustBeNull) {
10289 if (!TypeTagForDatatypeMagicValues)
10290 TypeTagForDatatypeMagicValues.reset(
10291 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
10292
10293 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
10294 (*TypeTagForDatatypeMagicValues)[Magic] =
10295 TypeTagData(Type, LayoutCompatible, MustBeNull);
10296}
10297
10298namespace {
10299bool IsSameCharType(QualType T1, QualType T2) {
10300 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
10301 if (!BT1)
10302 return false;
10303
10304 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
10305 if (!BT2)
10306 return false;
10307
10308 BuiltinType::Kind T1Kind = BT1->getKind();
10309 BuiltinType::Kind T2Kind = BT2->getKind();
10310
10311 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
10312 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
10313 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
10314 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
10315}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010316} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010317
10318void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
10319 const Expr * const *ExprArgs) {
10320 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
10321 bool IsPointerAttr = Attr->getIsPointer();
10322
10323 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
10324 bool FoundWrongKind;
10325 TypeTagData TypeInfo;
10326 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
10327 TypeTagForDatatypeMagicValues.get(),
10328 FoundWrongKind, TypeInfo)) {
10329 if (FoundWrongKind)
10330 Diag(TypeTagExpr->getExprLoc(),
10331 diag::warn_type_tag_for_datatype_wrong_kind)
10332 << TypeTagExpr->getSourceRange();
10333 return;
10334 }
10335
10336 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
10337 if (IsPointerAttr) {
10338 // Skip implicit cast of pointer to `void *' (as a function argument).
10339 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +000010340 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +000010341 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010342 ArgumentExpr = ICE->getSubExpr();
10343 }
10344 QualType ArgumentType = ArgumentExpr->getType();
10345
10346 // Passing a `void*' pointer shouldn't trigger a warning.
10347 if (IsPointerAttr && ArgumentType->isVoidPointerType())
10348 return;
10349
10350 if (TypeInfo.MustBeNull) {
10351 // Type tag with matching void type requires a null pointer.
10352 if (!ArgumentExpr->isNullPointerConstant(Context,
10353 Expr::NPC_ValueDependentIsNotNull)) {
10354 Diag(ArgumentExpr->getExprLoc(),
10355 diag::warn_type_safety_null_pointer_required)
10356 << ArgumentKind->getName()
10357 << ArgumentExpr->getSourceRange()
10358 << TypeTagExpr->getSourceRange();
10359 }
10360 return;
10361 }
10362
10363 QualType RequiredType = TypeInfo.Type;
10364 if (IsPointerAttr)
10365 RequiredType = Context.getPointerType(RequiredType);
10366
10367 bool mismatch = false;
10368 if (!TypeInfo.LayoutCompatible) {
10369 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
10370
10371 // C++11 [basic.fundamental] p1:
10372 // Plain char, signed char, and unsigned char are three distinct types.
10373 //
10374 // But we treat plain `char' as equivalent to `signed char' or `unsigned
10375 // char' depending on the current char signedness mode.
10376 if (mismatch)
10377 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
10378 RequiredType->getPointeeType())) ||
10379 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
10380 mismatch = false;
10381 } else
10382 if (IsPointerAttr)
10383 mismatch = !isLayoutCompatible(Context,
10384 ArgumentType->getPointeeType(),
10385 RequiredType->getPointeeType());
10386 else
10387 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
10388
10389 if (mismatch)
10390 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +000010391 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010392 << TypeInfo.LayoutCompatible << RequiredType
10393 << ArgumentExpr->getSourceRange()
10394 << TypeTagExpr->getSourceRange();
10395}