blob: 81dc23724e929f7f36673aa425f2f52f33e6017e [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
Chris Lattnerb87b1b32007-08-10 20:18:51 +000015#include "clang/AST/ASTContext.h"
Ken Dyck40775002010-01-11 17:06:35 +000016#include "clang/AST/CharUnits.h"
John McCall28a0cf72010-08-25 07:42:41 +000017#include "clang/AST/DeclCXX.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000018#include "clang/AST/DeclObjC.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "clang/AST/EvaluatedExprVisitor.h"
David Blaikie7555b6a2012-05-15 16:56:36 +000020#include "clang/AST/Expr.h"
Ted Kremenekc81614d2007-08-20 16:18:38 +000021#include "clang/AST/ExprCXX.h"
Ted Kremenek34f664d2008-06-16 18:00:42 +000022#include "clang/AST/ExprObjC.h"
Alexey Bataev1a3320e2015-08-25 14:24:04 +000023#include "clang/AST/ExprOpenMP.h"
Mike Stump0c2ec772010-01-21 03:59:47 +000024#include "clang/AST/StmtCXX.h"
25#include "clang/AST/StmtObjC.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000026#include "clang/Analysis/Analyses/FormatString.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000027#include "clang/Basic/CharInfo.h"
Eric Christopher8d0c6212010-04-17 02:26:23 +000028#include "clang/Basic/TargetBuiltins.h"
Nate Begeman4904e322010-06-08 02:47:44 +000029#include "clang/Basic/TargetInfo.h"
Alp Tokerb6cc5922014-05-03 03:45:55 +000030#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
Chandler Carruth3a022472012-12-04 09:13:33 +000031#include "clang/Sema/Initialization.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000032#include "clang/Sema/Lookup.h"
33#include "clang/Sema/ScopeInfo.h"
34#include "clang/Sema/Sema.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000035#include "clang/Sema/SemaInternal.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"
Mehdi Amini9670f842016-07-18 19:02:11 +000039#include "llvm/Support/ConvertUTF.h"
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +000040#include "llvm/Support/Format.h"
41#include "llvm/Support/Locale.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000042#include "llvm/Support/raw_ostream.h"
Eugene Zelenko1ced5092016-02-12 22:53:10 +000043
Chris Lattnerb87b1b32007-08-10 20:18:51 +000044using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000045using namespace sema;
Chris Lattnerb87b1b32007-08-10 20:18:51 +000046
Chris Lattnera26fb342009-02-18 17:49:48 +000047SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
48 unsigned ByteNo) const {
Alp Tokerb6cc5922014-05-03 03:45:55 +000049 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
50 Context.getTargetInfo());
Chris Lattnera26fb342009-02-18 17:49:48 +000051}
52
John McCallbebede42011-02-26 05:39:39 +000053/// Checks that a call expression's argument count is the desired number.
54/// This is useful when doing custom type-checking. Returns true on error.
55static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
56 unsigned argCount = call->getNumArgs();
57 if (argCount == desiredArgCount) return false;
58
59 if (argCount < desiredArgCount)
60 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
61 << 0 /*function call*/ << desiredArgCount << argCount
62 << call->getSourceRange();
63
64 // Highlight all the excess arguments.
65 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
66 call->getArg(argCount - 1)->getLocEnd());
67
68 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
69 << 0 /*function call*/ << desiredArgCount << argCount
70 << call->getArg(1)->getSourceRange();
71}
72
Julien Lerouge4a5b4442012-04-28 17:39:16 +000073/// Check that the first argument to __builtin_annotation is an integer
74/// and the second argument is a non-wide string literal.
75static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
76 if (checkArgCount(S, TheCall, 2))
77 return true;
78
79 // First argument should be an integer.
80 Expr *ValArg = TheCall->getArg(0);
81 QualType Ty = ValArg->getType();
82 if (!Ty->isIntegerType()) {
83 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
84 << ValArg->getSourceRange();
Julien Lerouge5a6b6982011-09-09 22:41:49 +000085 return true;
86 }
Julien Lerouge4a5b4442012-04-28 17:39:16 +000087
88 // Second argument should be a constant string.
89 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
90 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
91 if (!Literal || !Literal->isAscii()) {
92 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
93 << StrArg->getSourceRange();
94 return true;
95 }
96
97 TheCall->setType(Ty);
Julien Lerouge5a6b6982011-09-09 22:41:49 +000098 return false;
99}
100
Richard Smith6cbd65d2013-07-11 02:27:57 +0000101/// Check that the argument to __builtin_addressof is a glvalue, and set the
102/// result type to the corresponding pointer type.
103static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
104 if (checkArgCount(S, TheCall, 1))
105 return true;
106
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000107 ExprResult Arg(TheCall->getArg(0));
Richard Smith6cbd65d2013-07-11 02:27:57 +0000108 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
109 if (ResultType.isNull())
110 return true;
111
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000112 TheCall->setArg(0, Arg.get());
Richard Smith6cbd65d2013-07-11 02:27:57 +0000113 TheCall->setType(ResultType);
114 return false;
115}
116
John McCall03107a42015-10-29 20:48:01 +0000117static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
118 if (checkArgCount(S, TheCall, 3))
119 return true;
120
121 // First two arguments should be integers.
122 for (unsigned I = 0; I < 2; ++I) {
123 Expr *Arg = TheCall->getArg(I);
124 QualType Ty = Arg->getType();
125 if (!Ty->isIntegerType()) {
126 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_int)
127 << Ty << Arg->getSourceRange();
128 return true;
129 }
130 }
131
132 // Third argument should be a pointer to a non-const integer.
133 // IRGen correctly handles volatile, restrict, and address spaces, and
134 // the other qualifiers aren't possible.
135 {
136 Expr *Arg = TheCall->getArg(2);
137 QualType Ty = Arg->getType();
138 const auto *PtrTy = Ty->getAs<PointerType>();
139 if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
140 !PtrTy->getPointeeType().isConstQualified())) {
141 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_ptr_int)
142 << Ty << Arg->getSourceRange();
143 return true;
144 }
145 }
146
147 return false;
148}
149
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000150static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
151 CallExpr *TheCall, unsigned SizeIdx,
152 unsigned DstSizeIdx) {
153 if (TheCall->getNumArgs() <= SizeIdx ||
154 TheCall->getNumArgs() <= DstSizeIdx)
155 return;
156
157 const Expr *SizeArg = TheCall->getArg(SizeIdx);
158 const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
159
160 llvm::APSInt Size, DstSize;
161
162 // find out if both sizes are known at compile time
163 if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
164 !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
165 return;
166
167 if (Size.ule(DstSize))
168 return;
169
170 // confirmed overflow so generate the diagnostic.
171 IdentifierInfo *FnName = FDecl->getIdentifier();
172 SourceLocation SL = TheCall->getLocStart();
173 SourceRange SR = TheCall->getSourceRange();
174
175 S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
176}
177
Peter Collingbournef7706832014-12-12 23:41:25 +0000178static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
179 if (checkArgCount(S, BuiltinCall, 2))
180 return true;
181
182 SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
183 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
184 Expr *Call = BuiltinCall->getArg(0);
185 Expr *Chain = BuiltinCall->getArg(1);
186
187 if (Call->getStmtClass() != Stmt::CallExprClass) {
188 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
189 << Call->getSourceRange();
190 return true;
191 }
192
193 auto CE = cast<CallExpr>(Call);
194 if (CE->getCallee()->getType()->isBlockPointerType()) {
195 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
196 << Call->getSourceRange();
197 return true;
198 }
199
200 const Decl *TargetDecl = CE->getCalleeDecl();
201 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
202 if (FD->getBuiltinID()) {
203 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
204 << Call->getSourceRange();
205 return true;
206 }
207
208 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
209 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
210 << Call->getSourceRange();
211 return true;
212 }
213
214 ExprResult ChainResult = S.UsualUnaryConversions(Chain);
215 if (ChainResult.isInvalid())
216 return true;
217 if (!ChainResult.get()->getType()->isPointerType()) {
218 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
219 << Chain->getSourceRange();
220 return true;
221 }
222
David Majnemerced8bdf2015-02-25 17:36:15 +0000223 QualType ReturnTy = CE->getCallReturnType(S.Context);
Peter Collingbournef7706832014-12-12 23:41:25 +0000224 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
225 QualType BuiltinTy = S.Context.getFunctionType(
226 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
227 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
228
229 Builtin =
230 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
231
232 BuiltinCall->setType(CE->getType());
233 BuiltinCall->setValueKind(CE->getValueKind());
234 BuiltinCall->setObjectKind(CE->getObjectKind());
235 BuiltinCall->setCallee(Builtin);
236 BuiltinCall->setArg(1, ChainResult.get());
237
238 return false;
239}
240
Reid Kleckner1d59f992015-01-22 01:36:17 +0000241static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
242 Scope::ScopeFlags NeededScopeFlags,
243 unsigned DiagID) {
244 // Scopes aren't available during instantiation. Fortunately, builtin
245 // functions cannot be template args so they cannot be formed through template
246 // instantiation. Therefore checking once during the parse is sufficient.
247 if (!SemaRef.ActiveTemplateInstantiations.empty())
248 return false;
249
250 Scope *S = SemaRef.getCurScope();
251 while (S && !S->isSEHExceptScope())
252 S = S->getParent();
253 if (!S || !(S->getFlags() & NeededScopeFlags)) {
254 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
255 SemaRef.Diag(TheCall->getExprLoc(), DiagID)
256 << DRE->getDecl()->getIdentifier();
257 return true;
258 }
259
260 return false;
261}
262
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000263static inline bool isBlockPointer(Expr *Arg) {
264 return Arg->getType()->isBlockPointerType();
265}
266
267/// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
268/// void*, which is a requirement of device side enqueue.
269static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
270 const BlockPointerType *BPT =
271 cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
272 ArrayRef<QualType> Params =
273 BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes();
274 unsigned ArgCounter = 0;
275 bool IllegalParams = false;
276 // Iterate through the block parameters until either one is found that is not
277 // a local void*, or the block is valid.
278 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
279 I != E; ++I, ++ArgCounter) {
280 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
281 (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
282 LangAS::opencl_local) {
283 // Get the location of the error. If a block literal has been passed
284 // (BlockExpr) then we can point straight to the offending argument,
285 // else we just point to the variable reference.
286 SourceLocation ErrorLoc;
287 if (isa<BlockExpr>(BlockArg)) {
288 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
289 ErrorLoc = BD->getParamDecl(ArgCounter)->getLocStart();
290 } else if (isa<DeclRefExpr>(BlockArg)) {
291 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getLocStart();
292 }
293 S.Diag(ErrorLoc,
294 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
295 IllegalParams = true;
296 }
297 }
298
299 return IllegalParams;
300}
301
302/// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
303/// get_kernel_work_group_size
304/// and get_kernel_preferred_work_group_size_multiple builtin functions.
305static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
306 if (checkArgCount(S, TheCall, 1))
307 return true;
308
309 Expr *BlockArg = TheCall->getArg(0);
310 if (!isBlockPointer(BlockArg)) {
311 S.Diag(BlockArg->getLocStart(),
312 diag::err_opencl_enqueue_kernel_expected_type) << "block";
313 return true;
314 }
315 return checkOpenCLBlockArgs(S, BlockArg);
316}
317
318static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
319 unsigned Start, unsigned End);
320
321/// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
322/// 'local void*' parameter of passed block.
323static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
324 Expr *BlockArg,
325 unsigned NumNonVarArgs) {
326 const BlockPointerType *BPT =
327 cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
328 unsigned NumBlockParams =
329 BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams();
330 unsigned TotalNumArgs = TheCall->getNumArgs();
331
332 // For each argument passed to the block, a corresponding uint needs to
333 // be passed to describe the size of the local memory.
334 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
335 S.Diag(TheCall->getLocStart(),
336 diag::err_opencl_enqueue_kernel_local_size_args);
337 return true;
338 }
339
340 // Check that the sizes of the local memory are specified by integers.
341 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
342 TotalNumArgs - 1);
343}
344
345/// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
346/// overload formats specified in Table 6.13.17.1.
347/// int enqueue_kernel(queue_t queue,
348/// kernel_enqueue_flags_t flags,
349/// const ndrange_t ndrange,
350/// void (^block)(void))
351/// int enqueue_kernel(queue_t queue,
352/// kernel_enqueue_flags_t flags,
353/// const ndrange_t ndrange,
354/// uint num_events_in_wait_list,
355/// clk_event_t *event_wait_list,
356/// clk_event_t *event_ret,
357/// void (^block)(void))
358/// int enqueue_kernel(queue_t queue,
359/// kernel_enqueue_flags_t flags,
360/// const ndrange_t ndrange,
361/// void (^block)(local void*, ...),
362/// uint size0, ...)
363/// int enqueue_kernel(queue_t queue,
364/// kernel_enqueue_flags_t flags,
365/// const ndrange_t ndrange,
366/// uint num_events_in_wait_list,
367/// clk_event_t *event_wait_list,
368/// clk_event_t *event_ret,
369/// void (^block)(local void*, ...),
370/// uint size0, ...)
371static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
372 unsigned NumArgs = TheCall->getNumArgs();
373
374 if (NumArgs < 4) {
375 S.Diag(TheCall->getLocStart(), diag::err_typecheck_call_too_few_args);
376 return true;
377 }
378
379 Expr *Arg0 = TheCall->getArg(0);
380 Expr *Arg1 = TheCall->getArg(1);
381 Expr *Arg2 = TheCall->getArg(2);
382 Expr *Arg3 = TheCall->getArg(3);
383
384 // First argument always needs to be a queue_t type.
385 if (!Arg0->getType()->isQueueT()) {
386 S.Diag(TheCall->getArg(0)->getLocStart(),
387 diag::err_opencl_enqueue_kernel_expected_type)
388 << S.Context.OCLQueueTy;
389 return true;
390 }
391
392 // Second argument always needs to be a kernel_enqueue_flags_t enum value.
393 if (!Arg1->getType()->isIntegerType()) {
394 S.Diag(TheCall->getArg(1)->getLocStart(),
395 diag::err_opencl_enqueue_kernel_expected_type)
396 << "'kernel_enqueue_flags_t' (i.e. uint)";
397 return true;
398 }
399
400 // Third argument is always an ndrange_t type.
401 if (!Arg2->getType()->isNDRangeT()) {
402 S.Diag(TheCall->getArg(2)->getLocStart(),
403 diag::err_opencl_enqueue_kernel_expected_type)
404 << S.Context.OCLNDRangeTy;
405 return true;
406 }
407
408 // With four arguments, there is only one form that the function could be
409 // called in: no events and no variable arguments.
410 if (NumArgs == 4) {
411 // check that the last argument is the right block type.
412 if (!isBlockPointer(Arg3)) {
413 S.Diag(Arg3->getLocStart(), diag::err_opencl_enqueue_kernel_expected_type)
414 << "block";
415 return true;
416 }
417 // we have a block type, check the prototype
418 const BlockPointerType *BPT =
419 cast<BlockPointerType>(Arg3->getType().getCanonicalType());
420 if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) {
421 S.Diag(Arg3->getLocStart(),
422 diag::err_opencl_enqueue_kernel_blocks_no_args);
423 return true;
424 }
425 return false;
426 }
427 // we can have block + varargs.
428 if (isBlockPointer(Arg3))
429 return (checkOpenCLBlockArgs(S, Arg3) ||
430 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
431 // last two cases with either exactly 7 args or 7 args and varargs.
432 if (NumArgs >= 7) {
433 // check common block argument.
434 Expr *Arg6 = TheCall->getArg(6);
435 if (!isBlockPointer(Arg6)) {
436 S.Diag(Arg6->getLocStart(), diag::err_opencl_enqueue_kernel_expected_type)
437 << "block";
438 return true;
439 }
440 if (checkOpenCLBlockArgs(S, Arg6))
441 return true;
442
443 // Forth argument has to be any integer type.
444 if (!Arg3->getType()->isIntegerType()) {
445 S.Diag(TheCall->getArg(3)->getLocStart(),
446 diag::err_opencl_enqueue_kernel_expected_type)
447 << "integer";
448 return true;
449 }
450 // check remaining common arguments.
451 Expr *Arg4 = TheCall->getArg(4);
452 Expr *Arg5 = TheCall->getArg(5);
453
454 // Fith argument is always passed as pointers to clk_event_t.
455 if (!Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
456 S.Diag(TheCall->getArg(4)->getLocStart(),
457 diag::err_opencl_enqueue_kernel_expected_type)
458 << S.Context.getPointerType(S.Context.OCLClkEventTy);
459 return true;
460 }
461
462 // Sixth argument is always passed as pointers to clk_event_t.
463 if (!(Arg5->getType()->isPointerType() &&
464 Arg5->getType()->getPointeeType()->isClkEventT())) {
465 S.Diag(TheCall->getArg(5)->getLocStart(),
466 diag::err_opencl_enqueue_kernel_expected_type)
467 << S.Context.getPointerType(S.Context.OCLClkEventTy);
468 return true;
469 }
470
471 if (NumArgs == 7)
472 return false;
473
474 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
475 }
476
477 // None of the specific case has been detected, give generic error
478 S.Diag(TheCall->getLocStart(),
479 diag::err_opencl_enqueue_kernel_incorrect_args);
480 return true;
481}
482
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000483/// Returns OpenCL access qual.
Xiuli Pan11e13f62016-02-26 03:13:03 +0000484static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
Xiuli Pan11e13f62016-02-26 03:13:03 +0000485 return D->getAttr<OpenCLAccessAttr>();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000486}
487
488/// Returns true if pipe element type is different from the pointer.
489static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
490 const Expr *Arg0 = Call->getArg(0);
491 // First argument type should always be pipe.
492 if (!Arg0->getType()->isPipeType()) {
493 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000494 << Call->getDirectCallee() << Arg0->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000495 return true;
496 }
Xiuli Pan11e13f62016-02-26 03:13:03 +0000497 OpenCLAccessAttr *AccessQual =
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000498 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
499 // Validates the access qualifier is compatible with the call.
500 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
501 // read_only and write_only, and assumed to be read_only if no qualifier is
502 // specified.
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000503 switch (Call->getDirectCallee()->getBuiltinID()) {
504 case Builtin::BIread_pipe:
505 case Builtin::BIreserve_read_pipe:
506 case Builtin::BIcommit_read_pipe:
507 case Builtin::BIwork_group_reserve_read_pipe:
508 case Builtin::BIsub_group_reserve_read_pipe:
509 case Builtin::BIwork_group_commit_read_pipe:
510 case Builtin::BIsub_group_commit_read_pipe:
511 if (!(!AccessQual || AccessQual->isReadOnly())) {
512 S.Diag(Arg0->getLocStart(),
513 diag::err_opencl_builtin_pipe_invalid_access_modifier)
514 << "read_only" << Arg0->getSourceRange();
515 return true;
516 }
517 break;
518 case Builtin::BIwrite_pipe:
519 case Builtin::BIreserve_write_pipe:
520 case Builtin::BIcommit_write_pipe:
521 case Builtin::BIwork_group_reserve_write_pipe:
522 case Builtin::BIsub_group_reserve_write_pipe:
523 case Builtin::BIwork_group_commit_write_pipe:
524 case Builtin::BIsub_group_commit_write_pipe:
525 if (!(AccessQual && AccessQual->isWriteOnly())) {
526 S.Diag(Arg0->getLocStart(),
527 diag::err_opencl_builtin_pipe_invalid_access_modifier)
528 << "write_only" << Arg0->getSourceRange();
529 return true;
530 }
531 break;
532 default:
533 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000534 }
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000535 return false;
536}
537
538/// Returns true if pipe element type is different from the pointer.
539static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
540 const Expr *Arg0 = Call->getArg(0);
541 const Expr *ArgIdx = Call->getArg(Idx);
542 const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000543 const QualType EltTy = PipeTy->getElementType();
544 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000545 // The Idx argument should be a pointer and the type of the pointer and
546 // the type of pipe element should also be the same.
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000547 if (!ArgTy ||
548 !S.Context.hasSameType(
549 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000550 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000551 << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000552 << ArgIdx->getType() << ArgIdx->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000553 return true;
554 }
555 return false;
556}
557
558// \brief Performs semantic analysis for the read/write_pipe call.
559// \param S Reference to the semantic analyzer.
560// \param Call A pointer to the builtin call.
561// \return True if a semantic error has been found, false otherwise.
562static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000563 // OpenCL v2.0 s6.13.16.2 - The built-in read/write
564 // functions have two forms.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000565 switch (Call->getNumArgs()) {
566 case 2: {
567 if (checkOpenCLPipeArg(S, Call))
568 return true;
569 // The call with 2 arguments should be
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000570 // read/write_pipe(pipe T, T*).
571 // Check packet type T.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000572 if (checkOpenCLPipePacketType(S, Call, 1))
573 return true;
574 } break;
575
576 case 4: {
577 if (checkOpenCLPipeArg(S, Call))
578 return true;
579 // The call with 4 arguments should be
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000580 // read/write_pipe(pipe T, reserve_id_t, uint, T*).
581 // Check reserve_id_t.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000582 if (!Call->getArg(1)->getType()->isReserveIDT()) {
583 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000584 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000585 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000586 return true;
587 }
588
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000589 // Check the index.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000590 const Expr *Arg2 = Call->getArg(2);
591 if (!Arg2->getType()->isIntegerType() &&
592 !Arg2->getType()->isUnsignedIntegerType()) {
593 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000594 << Call->getDirectCallee() << S.Context.UnsignedIntTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000595 << Arg2->getType() << Arg2->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000596 return true;
597 }
598
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000599 // Check packet type T.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000600 if (checkOpenCLPipePacketType(S, Call, 3))
601 return true;
602 } break;
603 default:
604 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000605 << Call->getDirectCallee() << Call->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000606 return true;
607 }
608
609 return false;
610}
611
612// \brief Performs a semantic analysis on the {work_group_/sub_group_
613// /_}reserve_{read/write}_pipe
614// \param S Reference to the semantic analyzer.
615// \param Call The call to the builtin function to be analyzed.
616// \return True if a semantic error was found, false otherwise.
617static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
618 if (checkArgCount(S, Call, 2))
619 return true;
620
621 if (checkOpenCLPipeArg(S, Call))
622 return true;
623
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000624 // Check the reserve size.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000625 if (!Call->getArg(1)->getType()->isIntegerType() &&
626 !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
627 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000628 << Call->getDirectCallee() << S.Context.UnsignedIntTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000629 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000630 return true;
631 }
632
633 return false;
634}
635
636// \brief Performs a semantic analysis on {work_group_/sub_group_
637// /_}commit_{read/write}_pipe
638// \param S Reference to the semantic analyzer.
639// \param Call The call to the builtin function to be analyzed.
640// \return True if a semantic error was found, false otherwise.
641static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
642 if (checkArgCount(S, Call, 2))
643 return true;
644
645 if (checkOpenCLPipeArg(S, Call))
646 return true;
647
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000648 // Check reserve_id_t.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000649 if (!Call->getArg(1)->getType()->isReserveIDT()) {
650 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000651 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000652 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000653 return true;
654 }
655
656 return false;
657}
658
659// \brief Performs a semantic analysis on the call to built-in Pipe
660// Query Functions.
661// \param S Reference to the semantic analyzer.
662// \param Call The call to the builtin function to be analyzed.
663// \return True if a semantic error was found, false otherwise.
664static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
665 if (checkArgCount(S, Call, 1))
666 return true;
667
668 if (!Call->getArg(0)->getType()->isPipeType()) {
669 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000670 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000671 return true;
672 }
673
674 return false;
675}
Anastasia Stulova7f8d6dc2016-07-04 16:07:18 +0000676// \brief OpenCL v2.0 s6.13.9 - Address space qualifier functions.
Yaxun Liuf7449a12016-05-20 19:54:38 +0000677// \brief Performs semantic analysis for the to_global/local/private call.
678// \param S Reference to the semantic analyzer.
679// \param BuiltinID ID of the builtin function.
680// \param Call A pointer to the builtin call.
681// \return True if a semantic error has been found, false otherwise.
682static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
683 CallExpr *Call) {
Yaxun Liuf7449a12016-05-20 19:54:38 +0000684 if (Call->getNumArgs() != 1) {
685 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_arg_num)
686 << Call->getDirectCallee() << Call->getSourceRange();
687 return true;
688 }
689
690 auto RT = Call->getArg(0)->getType();
691 if (!RT->isPointerType() || RT->getPointeeType()
692 .getAddressSpace() == LangAS::opencl_constant) {
693 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg)
694 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
695 return true;
696 }
697
698 RT = RT->getPointeeType();
699 auto Qual = RT.getQualifiers();
700 switch (BuiltinID) {
701 case Builtin::BIto_global:
702 Qual.setAddressSpace(LangAS::opencl_global);
703 break;
704 case Builtin::BIto_local:
705 Qual.setAddressSpace(LangAS::opencl_local);
706 break;
707 default:
708 Qual.removeAddressSpace();
709 }
710 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
711 RT.getUnqualifiedType(), Qual)));
712
713 return false;
714}
715
John McCalldadc5752010-08-24 06:29:42 +0000716ExprResult
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000717Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
718 CallExpr *TheCall) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000719 ExprResult TheCallResult(TheCall);
Douglas Gregorae2fbad2008-11-17 20:34:05 +0000720
Chris Lattner3be167f2010-10-01 23:23:24 +0000721 // Find out if any arguments are required to be integer constant expressions.
722 unsigned ICEArguments = 0;
723 ASTContext::GetBuiltinTypeError Error;
724 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
725 if (Error != ASTContext::GE_None)
726 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
727
728 // If any arguments are required to be ICE's, check and diagnose.
729 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
730 // Skip arguments not required to be ICE's.
731 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
732
733 llvm::APSInt Result;
734 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
735 return true;
736 ICEArguments &= ~(1 << ArgNo);
737 }
738
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000739 switch (BuiltinID) {
Chris Lattner43be2e62007-12-19 23:59:04 +0000740 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner08464942007-12-28 05:29:59 +0000741 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner2da14fb2007-12-20 00:26:33 +0000742 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner6436fb62009-02-18 06:01:06 +0000743 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000744 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000745 break;
Ted Kremeneka174c522008-07-09 17:58:53 +0000746 case Builtin::BI__builtin_stdarg_start:
Chris Lattner43be2e62007-12-19 23:59:04 +0000747 case Builtin::BI__builtin_va_start:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000748 if (SemaBuiltinVAStart(TheCall))
749 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000750 break;
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000751 case Builtin::BI__va_start: {
752 switch (Context.getTargetInfo().getTriple().getArch()) {
753 case llvm::Triple::arm:
754 case llvm::Triple::thumb:
755 if (SemaBuiltinVAStartARM(TheCall))
756 return ExprError();
757 break;
758 default:
759 if (SemaBuiltinVAStart(TheCall))
760 return ExprError();
761 break;
762 }
763 break;
764 }
Chris Lattner2da14fb2007-12-20 00:26:33 +0000765 case Builtin::BI__builtin_isgreater:
766 case Builtin::BI__builtin_isgreaterequal:
767 case Builtin::BI__builtin_isless:
768 case Builtin::BI__builtin_islessequal:
769 case Builtin::BI__builtin_islessgreater:
770 case Builtin::BI__builtin_isunordered:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000771 if (SemaBuiltinUnorderedCompare(TheCall))
772 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000773 break;
Benjamin Kramer634fc102010-02-15 22:42:31 +0000774 case Builtin::BI__builtin_fpclassify:
775 if (SemaBuiltinFPClassification(TheCall, 6))
776 return ExprError();
777 break;
Eli Friedman7e4faac2009-08-31 20:06:00 +0000778 case Builtin::BI__builtin_isfinite:
779 case Builtin::BI__builtin_isinf:
780 case Builtin::BI__builtin_isinf_sign:
781 case Builtin::BI__builtin_isnan:
782 case Builtin::BI__builtin_isnormal:
Benjamin Kramer64aae502010-02-16 10:07:31 +0000783 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman7e4faac2009-08-31 20:06:00 +0000784 return ExprError();
785 break;
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000786 case Builtin::BI__builtin_shufflevector:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000787 return SemaBuiltinShuffleVector(TheCall);
788 // TheCall will be freed by the smart pointer here, but that's fine, since
789 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbarb7257262008-07-21 22:59:13 +0000790 case Builtin::BI__builtin_prefetch:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000791 if (SemaBuiltinPrefetch(TheCall))
792 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000793 break;
Hal Finkelf0417332014-07-17 14:25:55 +0000794 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +0000795 case Builtin::BI__builtin_assume:
Hal Finkelf0417332014-07-17 14:25:55 +0000796 if (SemaBuiltinAssume(TheCall))
797 return ExprError();
798 break;
Hal Finkelbcc06082014-09-07 22:58:14 +0000799 case Builtin::BI__builtin_assume_aligned:
800 if (SemaBuiltinAssumeAligned(TheCall))
801 return ExprError();
802 break;
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000803 case Builtin::BI__builtin_object_size:
Richard Sandiford28940af2014-04-16 08:47:51 +0000804 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000805 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000806 break;
Eli Friedmaneed8ad22009-05-03 04:46:36 +0000807 case Builtin::BI__builtin_longjmp:
808 if (SemaBuiltinLongjmp(TheCall))
809 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000810 break;
Joerg Sonnenberger27173282015-03-11 23:46:32 +0000811 case Builtin::BI__builtin_setjmp:
812 if (SemaBuiltinSetjmp(TheCall))
813 return ExprError();
814 break;
David Majnemerc403a1c2015-03-20 17:03:35 +0000815 case Builtin::BI_setjmp:
816 case Builtin::BI_setjmpex:
817 if (checkArgCount(*this, TheCall, 1))
818 return true;
819 break;
John McCallbebede42011-02-26 05:39:39 +0000820
821 case Builtin::BI__builtin_classify_type:
822 if (checkArgCount(*this, TheCall, 1)) return true;
823 TheCall->setType(Context.IntTy);
824 break;
Chris Lattner17c0eac2010-10-12 17:47:42 +0000825 case Builtin::BI__builtin_constant_p:
John McCallbebede42011-02-26 05:39:39 +0000826 if (checkArgCount(*this, TheCall, 1)) return true;
827 TheCall->setType(Context.IntTy);
Chris Lattner17c0eac2010-10-12 17:47:42 +0000828 break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000829 case Builtin::BI__sync_fetch_and_add:
Douglas Gregor73722482011-11-28 16:30:08 +0000830 case Builtin::BI__sync_fetch_and_add_1:
831 case Builtin::BI__sync_fetch_and_add_2:
832 case Builtin::BI__sync_fetch_and_add_4:
833 case Builtin::BI__sync_fetch_and_add_8:
834 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000835 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregor73722482011-11-28 16:30:08 +0000836 case Builtin::BI__sync_fetch_and_sub_1:
837 case Builtin::BI__sync_fetch_and_sub_2:
838 case Builtin::BI__sync_fetch_and_sub_4:
839 case Builtin::BI__sync_fetch_and_sub_8:
840 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000841 case Builtin::BI__sync_fetch_and_or:
Douglas Gregor73722482011-11-28 16:30:08 +0000842 case Builtin::BI__sync_fetch_and_or_1:
843 case Builtin::BI__sync_fetch_and_or_2:
844 case Builtin::BI__sync_fetch_and_or_4:
845 case Builtin::BI__sync_fetch_and_or_8:
846 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000847 case Builtin::BI__sync_fetch_and_and:
Douglas Gregor73722482011-11-28 16:30:08 +0000848 case Builtin::BI__sync_fetch_and_and_1:
849 case Builtin::BI__sync_fetch_and_and_2:
850 case Builtin::BI__sync_fetch_and_and_4:
851 case Builtin::BI__sync_fetch_and_and_8:
852 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000853 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregor73722482011-11-28 16:30:08 +0000854 case Builtin::BI__sync_fetch_and_xor_1:
855 case Builtin::BI__sync_fetch_and_xor_2:
856 case Builtin::BI__sync_fetch_and_xor_4:
857 case Builtin::BI__sync_fetch_and_xor_8:
858 case Builtin::BI__sync_fetch_and_xor_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000859 case Builtin::BI__sync_fetch_and_nand:
860 case Builtin::BI__sync_fetch_and_nand_1:
861 case Builtin::BI__sync_fetch_and_nand_2:
862 case Builtin::BI__sync_fetch_and_nand_4:
863 case Builtin::BI__sync_fetch_and_nand_8:
864 case Builtin::BI__sync_fetch_and_nand_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000865 case Builtin::BI__sync_add_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000866 case Builtin::BI__sync_add_and_fetch_1:
867 case Builtin::BI__sync_add_and_fetch_2:
868 case Builtin::BI__sync_add_and_fetch_4:
869 case Builtin::BI__sync_add_and_fetch_8:
870 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000871 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000872 case Builtin::BI__sync_sub_and_fetch_1:
873 case Builtin::BI__sync_sub_and_fetch_2:
874 case Builtin::BI__sync_sub_and_fetch_4:
875 case Builtin::BI__sync_sub_and_fetch_8:
876 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000877 case Builtin::BI__sync_and_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000878 case Builtin::BI__sync_and_and_fetch_1:
879 case Builtin::BI__sync_and_and_fetch_2:
880 case Builtin::BI__sync_and_and_fetch_4:
881 case Builtin::BI__sync_and_and_fetch_8:
882 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000883 case Builtin::BI__sync_or_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000884 case Builtin::BI__sync_or_and_fetch_1:
885 case Builtin::BI__sync_or_and_fetch_2:
886 case Builtin::BI__sync_or_and_fetch_4:
887 case Builtin::BI__sync_or_and_fetch_8:
888 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000889 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000890 case Builtin::BI__sync_xor_and_fetch_1:
891 case Builtin::BI__sync_xor_and_fetch_2:
892 case Builtin::BI__sync_xor_and_fetch_4:
893 case Builtin::BI__sync_xor_and_fetch_8:
894 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000895 case Builtin::BI__sync_nand_and_fetch:
896 case Builtin::BI__sync_nand_and_fetch_1:
897 case Builtin::BI__sync_nand_and_fetch_2:
898 case Builtin::BI__sync_nand_and_fetch_4:
899 case Builtin::BI__sync_nand_and_fetch_8:
900 case Builtin::BI__sync_nand_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000901 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000902 case Builtin::BI__sync_val_compare_and_swap_1:
903 case Builtin::BI__sync_val_compare_and_swap_2:
904 case Builtin::BI__sync_val_compare_and_swap_4:
905 case Builtin::BI__sync_val_compare_and_swap_8:
906 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000907 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000908 case Builtin::BI__sync_bool_compare_and_swap_1:
909 case Builtin::BI__sync_bool_compare_and_swap_2:
910 case Builtin::BI__sync_bool_compare_and_swap_4:
911 case Builtin::BI__sync_bool_compare_and_swap_8:
912 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000913 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +0000914 case Builtin::BI__sync_lock_test_and_set_1:
915 case Builtin::BI__sync_lock_test_and_set_2:
916 case Builtin::BI__sync_lock_test_and_set_4:
917 case Builtin::BI__sync_lock_test_and_set_8:
918 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000919 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +0000920 case Builtin::BI__sync_lock_release_1:
921 case Builtin::BI__sync_lock_release_2:
922 case Builtin::BI__sync_lock_release_4:
923 case Builtin::BI__sync_lock_release_8:
924 case Builtin::BI__sync_lock_release_16:
Chris Lattner9cb59fa2011-04-09 03:57:26 +0000925 case Builtin::BI__sync_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000926 case Builtin::BI__sync_swap_1:
927 case Builtin::BI__sync_swap_2:
928 case Builtin::BI__sync_swap_4:
929 case Builtin::BI__sync_swap_8:
930 case Builtin::BI__sync_swap_16:
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000931 return SemaBuiltinAtomicOverloaded(TheCallResult);
Michael Zolotukhin84df1232015-09-08 23:52:33 +0000932 case Builtin::BI__builtin_nontemporal_load:
933 case Builtin::BI__builtin_nontemporal_store:
934 return SemaBuiltinNontemporalOverloaded(TheCallResult);
Richard Smithfeea8832012-04-12 05:08:17 +0000935#define BUILTIN(ID, TYPE, ATTRS)
936#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
937 case Builtin::BI##ID: \
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000938 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithfeea8832012-04-12 05:08:17 +0000939#include "clang/Basic/Builtins.def"
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000940 case Builtin::BI__builtin_annotation:
Julien Lerouge4a5b4442012-04-28 17:39:16 +0000941 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000942 return ExprError();
943 break;
Richard Smith6cbd65d2013-07-11 02:27:57 +0000944 case Builtin::BI__builtin_addressof:
945 if (SemaBuiltinAddressof(*this, TheCall))
946 return ExprError();
947 break;
John McCall03107a42015-10-29 20:48:01 +0000948 case Builtin::BI__builtin_add_overflow:
949 case Builtin::BI__builtin_sub_overflow:
950 case Builtin::BI__builtin_mul_overflow:
Craig Toppera86e70d2015-11-07 06:16:14 +0000951 if (SemaBuiltinOverflow(*this, TheCall))
952 return ExprError();
953 break;
Richard Smith760520b2014-06-03 23:27:44 +0000954 case Builtin::BI__builtin_operator_new:
955 case Builtin::BI__builtin_operator_delete:
956 if (!getLangOpts().CPlusPlus) {
957 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
958 << (BuiltinID == Builtin::BI__builtin_operator_new
959 ? "__builtin_operator_new"
960 : "__builtin_operator_delete")
961 << "C++";
962 return ExprError();
963 }
964 // CodeGen assumes it can find the global new and delete to call,
965 // so ensure that they are declared.
966 DeclareGlobalNewDelete();
967 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000968
969 // check secure string manipulation functions where overflows
970 // are detectable at compile time
971 case Builtin::BI__builtin___memcpy_chk:
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000972 case Builtin::BI__builtin___memmove_chk:
973 case Builtin::BI__builtin___memset_chk:
974 case Builtin::BI__builtin___strlcat_chk:
975 case Builtin::BI__builtin___strlcpy_chk:
976 case Builtin::BI__builtin___strncat_chk:
977 case Builtin::BI__builtin___strncpy_chk:
978 case Builtin::BI__builtin___stpncpy_chk:
979 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
980 break;
Steven Wu566c14e2014-09-24 04:37:33 +0000981 case Builtin::BI__builtin___memccpy_chk:
982 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
983 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000984 case Builtin::BI__builtin___snprintf_chk:
985 case Builtin::BI__builtin___vsnprintf_chk:
986 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
987 break;
Peter Collingbournef7706832014-12-12 23:41:25 +0000988 case Builtin::BI__builtin_call_with_static_chain:
989 if (SemaBuiltinCallWithStaticChain(*this, TheCall))
990 return ExprError();
991 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +0000992 case Builtin::BI__exception_code:
Eugene Zelenko1ced5092016-02-12 22:53:10 +0000993 case Builtin::BI_exception_code:
Reid Kleckner1d59f992015-01-22 01:36:17 +0000994 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
995 diag::err_seh___except_block))
996 return ExprError();
997 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +0000998 case Builtin::BI__exception_info:
Eugene Zelenko1ced5092016-02-12 22:53:10 +0000999 case Builtin::BI_exception_info:
Reid Kleckner1d59f992015-01-22 01:36:17 +00001000 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1001 diag::err_seh___except_filter))
1002 return ExprError();
1003 break;
David Majnemerba3e5ec2015-03-13 18:26:17 +00001004 case Builtin::BI__GetExceptionInfo:
1005 if (checkArgCount(*this, TheCall, 1))
1006 return ExprError();
1007
1008 if (CheckCXXThrowOperand(
1009 TheCall->getLocStart(),
1010 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1011 TheCall))
1012 return ExprError();
1013
1014 TheCall->setType(Context.VoidPtrTy);
1015 break;
Anastasia Stulova7f8d6dc2016-07-04 16:07:18 +00001016 // OpenCL v2.0, s6.13.16 - Pipe functions
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001017 case Builtin::BIread_pipe:
1018 case Builtin::BIwrite_pipe:
1019 // Since those two functions are declared with var args, we need a semantic
1020 // check for the argument.
1021 if (SemaBuiltinRWPipe(*this, TheCall))
1022 return ExprError();
Alexey Baderaf17c792016-09-07 10:32:03 +00001023 TheCall->setType(Context.IntTy);
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001024 break;
1025 case Builtin::BIreserve_read_pipe:
1026 case Builtin::BIreserve_write_pipe:
1027 case Builtin::BIwork_group_reserve_read_pipe:
1028 case Builtin::BIwork_group_reserve_write_pipe:
1029 case Builtin::BIsub_group_reserve_read_pipe:
1030 case Builtin::BIsub_group_reserve_write_pipe:
1031 if (SemaBuiltinReserveRWPipe(*this, TheCall))
1032 return ExprError();
1033 // Since return type of reserve_read/write_pipe built-in function is
1034 // reserve_id_t, which is not defined in the builtin def file , we used int
1035 // as return type and need to override the return type of these functions.
1036 TheCall->setType(Context.OCLReserveIDTy);
1037 break;
1038 case Builtin::BIcommit_read_pipe:
1039 case Builtin::BIcommit_write_pipe:
1040 case Builtin::BIwork_group_commit_read_pipe:
1041 case Builtin::BIwork_group_commit_write_pipe:
1042 case Builtin::BIsub_group_commit_read_pipe:
1043 case Builtin::BIsub_group_commit_write_pipe:
1044 if (SemaBuiltinCommitRWPipe(*this, TheCall))
1045 return ExprError();
1046 break;
1047 case Builtin::BIget_pipe_num_packets:
1048 case Builtin::BIget_pipe_max_packets:
1049 if (SemaBuiltinPipePackets(*this, TheCall))
1050 return ExprError();
Alexey Baderaf17c792016-09-07 10:32:03 +00001051 TheCall->setType(Context.UnsignedIntTy);
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001052 break;
Yaxun Liuf7449a12016-05-20 19:54:38 +00001053 case Builtin::BIto_global:
1054 case Builtin::BIto_local:
1055 case Builtin::BIto_private:
1056 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1057 return ExprError();
1058 break;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00001059 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1060 case Builtin::BIenqueue_kernel:
1061 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1062 return ExprError();
1063 break;
1064 case Builtin::BIget_kernel_work_group_size:
1065 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1066 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1067 return ExprError();
Nate Begeman4904e322010-06-08 02:47:44 +00001068 }
Richard Smith760520b2014-06-03 23:27:44 +00001069
Nate Begeman4904e322010-06-08 02:47:44 +00001070 // Since the target specific builtins for each arch overlap, only check those
1071 // of the arch we are compiling for.
Artem Belevich9674a642015-09-22 17:23:05 +00001072 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001073 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +00001074 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00001075 case llvm::Triple::armeb:
Nate Begeman4904e322010-06-08 02:47:44 +00001076 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00001077 case llvm::Triple::thumbeb:
Nate Begeman4904e322010-06-08 02:47:44 +00001078 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1079 return ExprError();
1080 break;
Tim Northover25e8a672014-05-24 12:51:25 +00001081 case llvm::Triple::aarch64:
1082 case llvm::Triple::aarch64_be:
Tim Northover573cbee2014-05-24 12:52:07 +00001083 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
Tim Northovera2ee4332014-03-29 15:09:45 +00001084 return ExprError();
1085 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001086 case llvm::Triple::mips:
1087 case llvm::Triple::mipsel:
1088 case llvm::Triple::mips64:
1089 case llvm::Triple::mips64el:
1090 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1091 return ExprError();
1092 break;
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001093 case llvm::Triple::systemz:
1094 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1095 return ExprError();
1096 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001097 case llvm::Triple::x86:
1098 case llvm::Triple::x86_64:
1099 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1100 return ExprError();
1101 break;
Kit Bartone50adcb2015-03-30 19:40:59 +00001102 case llvm::Triple::ppc:
1103 case llvm::Triple::ppc64:
1104 case llvm::Triple::ppc64le:
1105 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1106 return ExprError();
1107 break;
Nate Begeman4904e322010-06-08 02:47:44 +00001108 default:
1109 break;
1110 }
1111 }
1112
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001113 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +00001114}
1115
Nate Begeman91e1fea2010-06-14 05:21:25 +00001116// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +00001117static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +00001118 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +00001119 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +00001120 switch (Type.getEltType()) {
1121 case NeonTypeFlags::Int8:
1122 case NeonTypeFlags::Poly8:
1123 return shift ? 7 : (8 << IsQuad) - 1;
1124 case NeonTypeFlags::Int16:
1125 case NeonTypeFlags::Poly16:
1126 return shift ? 15 : (4 << IsQuad) - 1;
1127 case NeonTypeFlags::Int32:
1128 return shift ? 31 : (2 << IsQuad) - 1;
1129 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +00001130 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +00001131 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +00001132 case NeonTypeFlags::Poly128:
1133 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +00001134 case NeonTypeFlags::Float16:
1135 assert(!shift && "cannot shift float types!");
1136 return (4 << IsQuad) - 1;
1137 case NeonTypeFlags::Float32:
1138 assert(!shift && "cannot shift float types!");
1139 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +00001140 case NeonTypeFlags::Float64:
1141 assert(!shift && "cannot shift float types!");
1142 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +00001143 }
David Blaikie8a40f702012-01-17 06:56:22 +00001144 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +00001145}
1146
Bob Wilsone4d77232011-11-08 05:04:11 +00001147/// getNeonEltType - Return the QualType corresponding to the elements of
1148/// the vector type specified by the NeonTypeFlags. This is used to check
1149/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +00001150static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Tim Northovera2ee4332014-03-29 15:09:45 +00001151 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilsone4d77232011-11-08 05:04:11 +00001152 switch (Flags.getEltType()) {
1153 case NeonTypeFlags::Int8:
1154 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1155 case NeonTypeFlags::Int16:
1156 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1157 case NeonTypeFlags::Int32:
1158 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1159 case NeonTypeFlags::Int64:
Tim Northovera2ee4332014-03-29 15:09:45 +00001160 if (IsInt64Long)
Kevin Qinad64f6d2014-02-24 02:45:03 +00001161 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1162 else
1163 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1164 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001165 case NeonTypeFlags::Poly8:
Tim Northovera2ee4332014-03-29 15:09:45 +00001166 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001167 case NeonTypeFlags::Poly16:
Tim Northovera2ee4332014-03-29 15:09:45 +00001168 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qincaac85e2013-11-14 03:29:16 +00001169 case NeonTypeFlags::Poly64:
Kevin Qin78b86532015-05-14 08:18:05 +00001170 if (IsInt64Long)
1171 return Context.UnsignedLongTy;
1172 else
1173 return Context.UnsignedLongLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +00001174 case NeonTypeFlags::Poly128:
1175 break;
Bob Wilsone4d77232011-11-08 05:04:11 +00001176 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +00001177 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001178 case NeonTypeFlags::Float32:
1179 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +00001180 case NeonTypeFlags::Float64:
1181 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001182 }
David Blaikie8a40f702012-01-17 06:56:22 +00001183 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +00001184}
1185
Tim Northover12670412014-02-19 10:37:05 +00001186bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +00001187 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +00001188 uint64_t mask = 0;
1189 unsigned TV = 0;
1190 int PtrArgNum = -1;
1191 bool HasConstPtr = false;
1192 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +00001193#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001194#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +00001195#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001196 }
1197
1198 // For NEON intrinsics which are overloaded on vector element type, validate
1199 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +00001200 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +00001201 if (mask) {
1202 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1203 return true;
1204
1205 TV = Result.getLimitedValue(64);
1206 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1207 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Tim Northover12670412014-02-19 10:37:05 +00001208 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +00001209 }
1210
1211 if (PtrArgNum >= 0) {
1212 // Check that pointer arguments have the specified type.
1213 Expr *Arg = TheCall->getArg(PtrArgNum);
1214 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1215 Arg = ICE->getSubExpr();
1216 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1217 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +00001218
Tim Northovera2ee4332014-03-29 15:09:45 +00001219 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Tim Northover40956e62014-07-23 12:32:58 +00001220 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64;
Tim Northovera2ee4332014-03-29 15:09:45 +00001221 bool IsInt64Long =
1222 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1223 QualType EltTy =
1224 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northover2fe823a2013-08-01 09:23:19 +00001225 if (HasConstPtr)
1226 EltTy = EltTy.withConst();
1227 QualType LHSTy = Context.getPointerType(EltTy);
1228 AssignConvertType ConvTy;
1229 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1230 if (RHS.isInvalid())
1231 return true;
1232 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
1233 RHS.get(), AA_Assigning))
1234 return true;
1235 }
1236
1237 // For NEON intrinsics which take an immediate value as part of the
1238 // instruction, range check them here.
1239 unsigned i = 0, l = 0, u = 0;
1240 switch (BuiltinID) {
1241 default:
1242 return false;
Tim Northover12670412014-02-19 10:37:05 +00001243#define GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001244#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +00001245#undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001246 }
Tim Northover2fe823a2013-08-01 09:23:19 +00001247
Richard Sandiford28940af2014-04-16 08:47:51 +00001248 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northover2fe823a2013-08-01 09:23:19 +00001249}
1250
Tim Northovera2ee4332014-03-29 15:09:45 +00001251bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1252 unsigned MaxWidth) {
Tim Northover6aacd492013-07-16 09:47:53 +00001253 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001254 BuiltinID == ARM::BI__builtin_arm_ldaex ||
Tim Northovera2ee4332014-03-29 15:09:45 +00001255 BuiltinID == ARM::BI__builtin_arm_strex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001256 BuiltinID == ARM::BI__builtin_arm_stlex ||
Tim Northover573cbee2014-05-24 12:52:07 +00001257 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001258 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1259 BuiltinID == AArch64::BI__builtin_arm_strex ||
1260 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
Tim Northover6aacd492013-07-16 09:47:53 +00001261 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +00001262 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001263 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1264 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1265 BuiltinID == AArch64::BI__builtin_arm_ldaex;
Tim Northover6aacd492013-07-16 09:47:53 +00001266
1267 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1268
1269 // Ensure that we have the proper number of arguments.
1270 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1271 return true;
1272
1273 // Inspect the pointer argument of the atomic builtin. This should always be
1274 // a pointer type, whose element is an integral scalar or pointer type.
1275 // Because it is a pointer type, we don't have to worry about any implicit
1276 // casts here.
1277 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1278 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1279 if (PointerArgRes.isInvalid())
1280 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001281 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001282
1283 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1284 if (!pointerType) {
1285 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1286 << PointerArg->getType() << PointerArg->getSourceRange();
1287 return true;
1288 }
1289
1290 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1291 // task is to insert the appropriate casts into the AST. First work out just
1292 // what the appropriate type is.
1293 QualType ValType = pointerType->getPointeeType();
1294 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1295 if (IsLdrex)
1296 AddrType.addConst();
1297
1298 // Issue a warning if the cast is dodgy.
1299 CastKind CastNeeded = CK_NoOp;
1300 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1301 CastNeeded = CK_BitCast;
1302 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
1303 << PointerArg->getType()
1304 << Context.getPointerType(AddrType)
1305 << AA_Passing << PointerArg->getSourceRange();
1306 }
1307
1308 // Finally, do the cast and replace the argument with the corrected version.
1309 AddrType = Context.getPointerType(AddrType);
1310 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1311 if (PointerArgRes.isInvalid())
1312 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001313 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001314
1315 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1316
1317 // In general, we allow ints, floats and pointers to be loaded and stored.
1318 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1319 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1320 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1321 << PointerArg->getType() << PointerArg->getSourceRange();
1322 return true;
1323 }
1324
1325 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +00001326 if (Context.getTypeSize(ValType) > MaxWidth) {
1327 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover6aacd492013-07-16 09:47:53 +00001328 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
1329 << PointerArg->getType() << PointerArg->getSourceRange();
1330 return true;
1331 }
1332
1333 switch (ValType.getObjCLifetime()) {
1334 case Qualifiers::OCL_None:
1335 case Qualifiers::OCL_ExplicitNone:
1336 // okay
1337 break;
1338
1339 case Qualifiers::OCL_Weak:
1340 case Qualifiers::OCL_Strong:
1341 case Qualifiers::OCL_Autoreleasing:
1342 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1343 << ValType << PointerArg->getSourceRange();
1344 return true;
1345 }
1346
Tim Northover6aacd492013-07-16 09:47:53 +00001347 if (IsLdrex) {
1348 TheCall->setType(ValType);
1349 return false;
1350 }
1351
1352 // Initialize the argument to be stored.
1353 ExprResult ValArg = TheCall->getArg(0);
1354 InitializedEntity Entity = InitializedEntity::InitializeParameter(
1355 Context, ValType, /*consume*/ false);
1356 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1357 if (ValArg.isInvalid())
1358 return true;
Tim Northover6aacd492013-07-16 09:47:53 +00001359 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +00001360
1361 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1362 // but the custom checker bypasses all default analysis.
1363 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +00001364 return false;
1365}
1366
Nate Begeman4904e322010-06-08 02:47:44 +00001367bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman55483092010-06-09 01:10:23 +00001368 llvm::APSInt Result;
1369
Tim Northover6aacd492013-07-16 09:47:53 +00001370 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001371 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1372 BuiltinID == ARM::BI__builtin_arm_strex ||
1373 BuiltinID == ARM::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001374 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +00001375 }
1376
Yi Kong26d104a2014-08-13 19:18:14 +00001377 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1378 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1379 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1380 }
1381
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001382 if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1383 BuiltinID == ARM::BI__builtin_arm_wsr64)
1384 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1385
1386 if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1387 BuiltinID == ARM::BI__builtin_arm_rsrp ||
1388 BuiltinID == ARM::BI__builtin_arm_wsr ||
1389 BuiltinID == ARM::BI__builtin_arm_wsrp)
1390 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1391
Tim Northover12670412014-02-19 10:37:05 +00001392 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1393 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +00001394
Yi Kong4efadfb2014-07-03 16:01:25 +00001395 // For intrinsics which take an immediate value as part of the instruction,
1396 // range check them here.
Nate Begeman91e1fea2010-06-14 05:21:25 +00001397 unsigned i = 0, l = 0, u = 0;
Nate Begemand773fe62010-06-13 04:47:52 +00001398 switch (BuiltinID) {
1399 default: return false;
Nate Begeman1194bd22010-07-29 22:48:34 +00001400 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
1401 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begemanf568b072010-08-03 21:32:34 +00001402 case ARM::BI__builtin_arm_vcvtr_f:
1403 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Weiming Zhao87bb4922013-11-12 21:42:50 +00001404 case ARM::BI__builtin_arm_dmb:
Yi Kong4efadfb2014-07-03 16:01:25 +00001405 case ARM::BI__builtin_arm_dsb:
Yi Kong1d268af2014-08-26 12:48:06 +00001406 case ARM::BI__builtin_arm_isb:
1407 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00001408 }
Nate Begemand773fe62010-06-13 04:47:52 +00001409
Nate Begemanf568b072010-08-03 21:32:34 +00001410 // FIXME: VFP Intrinsics should error if VFP not present.
Richard Sandiford28940af2014-04-16 08:47:51 +00001411 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001412}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001413
Tim Northover573cbee2014-05-24 12:52:07 +00001414bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +00001415 CallExpr *TheCall) {
1416 llvm::APSInt Result;
1417
Tim Northover573cbee2014-05-24 12:52:07 +00001418 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001419 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1420 BuiltinID == AArch64::BI__builtin_arm_strex ||
1421 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001422 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1423 }
1424
Yi Konga5548432014-08-13 19:18:20 +00001425 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1426 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1427 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1428 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1429 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1430 }
1431
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001432 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1433 BuiltinID == AArch64::BI__builtin_arm_wsr64)
Tim Northover54e50002016-04-13 17:08:55 +00001434 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001435
1436 if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1437 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1438 BuiltinID == AArch64::BI__builtin_arm_wsr ||
1439 BuiltinID == AArch64::BI__builtin_arm_wsrp)
1440 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1441
Tim Northovera2ee4332014-03-29 15:09:45 +00001442 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1443 return true;
1444
Yi Kong19a29ac2014-07-17 10:52:06 +00001445 // For intrinsics which take an immediate value as part of the instruction,
1446 // range check them here.
1447 unsigned i = 0, l = 0, u = 0;
1448 switch (BuiltinID) {
1449 default: return false;
1450 case AArch64::BI__builtin_arm_dmb:
1451 case AArch64::BI__builtin_arm_dsb:
1452 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1453 }
1454
Yi Kong19a29ac2014-07-17 10:52:06 +00001455 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northovera2ee4332014-03-29 15:09:45 +00001456}
1457
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001458bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1459 unsigned i = 0, l = 0, u = 0;
1460 switch (BuiltinID) {
1461 default: return false;
1462 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
1463 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +00001464 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
1465 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
1466 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
1467 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
1468 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00001469 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001470
Richard Sandiford28940af2014-04-16 08:47:51 +00001471 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001472}
1473
Kit Bartone50adcb2015-03-30 19:40:59 +00001474bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1475 unsigned i = 0, l = 0, u = 0;
Nemanja Ivanovic239eec72015-04-09 23:58:16 +00001476 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
1477 BuiltinID == PPC::BI__builtin_divdeu ||
1478 BuiltinID == PPC::BI__builtin_bpermd;
1479 bool IsTarget64Bit = Context.getTargetInfo()
1480 .getTypeWidth(Context
1481 .getTargetInfo()
1482 .getIntPtrType()) == 64;
1483 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
1484 BuiltinID == PPC::BI__builtin_divweu ||
1485 BuiltinID == PPC::BI__builtin_divde ||
1486 BuiltinID == PPC::BI__builtin_divdeu;
1487
1488 if (Is64BitBltin && !IsTarget64Bit)
1489 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
1490 << TheCall->getSourceRange();
1491
1492 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
1493 (BuiltinID == PPC::BI__builtin_bpermd &&
1494 !Context.getTargetInfo().hasFeature("bpermd")))
1495 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
1496 << TheCall->getSourceRange();
1497
Kit Bartone50adcb2015-03-30 19:40:59 +00001498 switch (BuiltinID) {
1499 default: return false;
1500 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
1501 case PPC::BI__builtin_altivec_crypto_vshasigmad:
1502 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1503 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1504 case PPC::BI__builtin_tbegin:
1505 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
1506 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
1507 case PPC::BI__builtin_tabortwc:
1508 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
1509 case PPC::BI__builtin_tabortwci:
1510 case PPC::BI__builtin_tabortdci:
1511 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
1512 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
1513 }
1514 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1515}
1516
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001517bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
1518 CallExpr *TheCall) {
1519 if (BuiltinID == SystemZ::BI__builtin_tabort) {
1520 Expr *Arg = TheCall->getArg(0);
1521 llvm::APSInt AbortCode(32);
1522 if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
1523 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
1524 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
1525 << Arg->getSourceRange();
1526 }
1527
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001528 // For intrinsics which take an immediate value as part of the instruction,
1529 // range check them here.
1530 unsigned i = 0, l = 0, u = 0;
1531 switch (BuiltinID) {
1532 default: return false;
1533 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
1534 case SystemZ::BI__builtin_s390_verimb:
1535 case SystemZ::BI__builtin_s390_verimh:
1536 case SystemZ::BI__builtin_s390_verimf:
1537 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
1538 case SystemZ::BI__builtin_s390_vfaeb:
1539 case SystemZ::BI__builtin_s390_vfaeh:
1540 case SystemZ::BI__builtin_s390_vfaef:
1541 case SystemZ::BI__builtin_s390_vfaebs:
1542 case SystemZ::BI__builtin_s390_vfaehs:
1543 case SystemZ::BI__builtin_s390_vfaefs:
1544 case SystemZ::BI__builtin_s390_vfaezb:
1545 case SystemZ::BI__builtin_s390_vfaezh:
1546 case SystemZ::BI__builtin_s390_vfaezf:
1547 case SystemZ::BI__builtin_s390_vfaezbs:
1548 case SystemZ::BI__builtin_s390_vfaezhs:
1549 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
1550 case SystemZ::BI__builtin_s390_vfidb:
1551 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1552 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1553 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
1554 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
1555 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
1556 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
1557 case SystemZ::BI__builtin_s390_vstrcb:
1558 case SystemZ::BI__builtin_s390_vstrch:
1559 case SystemZ::BI__builtin_s390_vstrcf:
1560 case SystemZ::BI__builtin_s390_vstrczb:
1561 case SystemZ::BI__builtin_s390_vstrczh:
1562 case SystemZ::BI__builtin_s390_vstrczf:
1563 case SystemZ::BI__builtin_s390_vstrcbs:
1564 case SystemZ::BI__builtin_s390_vstrchs:
1565 case SystemZ::BI__builtin_s390_vstrcfs:
1566 case SystemZ::BI__builtin_s390_vstrczbs:
1567 case SystemZ::BI__builtin_s390_vstrczhs:
1568 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
1569 }
1570 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001571}
1572
Craig Topper5ba2c502015-11-07 08:08:31 +00001573/// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
1574/// This checks that the target supports __builtin_cpu_supports and
1575/// that the string argument is constant and valid.
1576static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
1577 Expr *Arg = TheCall->getArg(0);
1578
1579 // Check if the argument is a string literal.
1580 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1581 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1582 << Arg->getSourceRange();
1583
1584 // Check the contents of the string.
1585 StringRef Feature =
1586 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1587 if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
1588 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
1589 << Arg->getSourceRange();
1590 return false;
1591}
1592
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001593bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Craig Topper39c87102016-05-18 03:18:12 +00001594 int i = 0, l = 0, u = 0;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001595 switch (BuiltinID) {
Richard Trieucc3949d2016-02-18 22:34:54 +00001596 default:
1597 return false;
Eric Christopherd9832702015-06-29 21:00:05 +00001598 case X86::BI__builtin_cpu_supports:
Craig Topper5ba2c502015-11-07 08:08:31 +00001599 return SemaBuiltinCpuSupports(*this, TheCall);
Charles Davisc7d5c942015-09-17 20:55:33 +00001600 case X86::BI__builtin_ms_va_start:
1601 return SemaBuiltinMSVAStart(TheCall);
Craig Topperfe22d592016-07-21 07:38:43 +00001602 case X86::BI__builtin_ia32_addcarryx_u64:
1603 case X86::BI__builtin_ia32_addcarry_u64:
1604 case X86::BI__builtin_ia32_subborrow_u64:
1605 case X86::BI__builtin_ia32_readeflags_u64:
1606 case X86::BI__builtin_ia32_writeeflags_u64:
1607 case X86::BI__builtin_ia32_bextr_u64:
1608 case X86::BI__builtin_ia32_bextri_u64:
1609 case X86::BI__builtin_ia32_bzhi_di:
1610 case X86::BI__builtin_ia32_pdep_di:
1611 case X86::BI__builtin_ia32_pext_di:
1612 case X86::BI__builtin_ia32_crc32di:
1613 case X86::BI__builtin_ia32_fxsave64:
1614 case X86::BI__builtin_ia32_fxrstor64:
1615 case X86::BI__builtin_ia32_xsave64:
1616 case X86::BI__builtin_ia32_xrstor64:
1617 case X86::BI__builtin_ia32_xsaveopt64:
1618 case X86::BI__builtin_ia32_xrstors64:
1619 case X86::BI__builtin_ia32_xsavec64:
1620 case X86::BI__builtin_ia32_xsaves64:
1621 case X86::BI__builtin_ia32_rdfsbase64:
1622 case X86::BI__builtin_ia32_rdgsbase64:
1623 case X86::BI__builtin_ia32_wrfsbase64:
1624 case X86::BI__builtin_ia32_wrgsbase64:
Craig Topper351ed422016-07-24 14:58:06 +00001625 case X86::BI__builtin_ia32_pbroadcastq512_gpr_mask:
1626 case X86::BI__builtin_ia32_pbroadcastq256_gpr_mask:
1627 case X86::BI__builtin_ia32_pbroadcastq128_gpr_mask:
Craig Topperfe22d592016-07-21 07:38:43 +00001628 case X86::BI__builtin_ia32_vcvtsd2si64:
1629 case X86::BI__builtin_ia32_vcvtsd2usi64:
1630 case X86::BI__builtin_ia32_vcvtss2si64:
1631 case X86::BI__builtin_ia32_vcvtss2usi64:
1632 case X86::BI__builtin_ia32_vcvttsd2si64:
1633 case X86::BI__builtin_ia32_vcvttsd2usi64:
1634 case X86::BI__builtin_ia32_vcvttss2si64:
1635 case X86::BI__builtin_ia32_vcvttss2usi64:
1636 case X86::BI__builtin_ia32_cvtss2si64:
1637 case X86::BI__builtin_ia32_cvttss2si64:
1638 case X86::BI__builtin_ia32_cvtsd2si64:
1639 case X86::BI__builtin_ia32_cvttsd2si64:
1640 case X86::BI__builtin_ia32_cvtsi2sd64:
1641 case X86::BI__builtin_ia32_cvtsi2ss64:
1642 case X86::BI__builtin_ia32_cvtusi2sd64:
1643 case X86::BI__builtin_ia32_cvtusi2ss64:
1644 case X86::BI__builtin_ia32_rdseed64_step: {
1645 // These builtins only work on x86-64 targets.
1646 const llvm::Triple &TT = Context.getTargetInfo().getTriple();
1647 if (TT.getArch() != llvm::Triple::x86_64)
1648 return Diag(TheCall->getCallee()->getLocStart(),
1649 diag::err_x86_builtin_32_bit_tgt);
1650 return false;
1651 }
Craig Topper39c87102016-05-18 03:18:12 +00001652 case X86::BI__builtin_ia32_extractf64x4_mask:
1653 case X86::BI__builtin_ia32_extracti64x4_mask:
1654 case X86::BI__builtin_ia32_extractf32x8_mask:
1655 case X86::BI__builtin_ia32_extracti32x8_mask:
1656 case X86::BI__builtin_ia32_extractf64x2_256_mask:
1657 case X86::BI__builtin_ia32_extracti64x2_256_mask:
1658 case X86::BI__builtin_ia32_extractf32x4_256_mask:
1659 case X86::BI__builtin_ia32_extracti32x4_256_mask:
1660 i = 1; l = 0; u = 1;
1661 break;
Richard Trieucc3949d2016-02-18 22:34:54 +00001662 case X86::BI_mm_prefetch:
Craig Topper39c87102016-05-18 03:18:12 +00001663 case X86::BI__builtin_ia32_extractf32x4_mask:
1664 case X86::BI__builtin_ia32_extracti32x4_mask:
Craig Topper39c87102016-05-18 03:18:12 +00001665 case X86::BI__builtin_ia32_extractf64x2_512_mask:
1666 case X86::BI__builtin_ia32_extracti64x2_512_mask:
1667 i = 1; l = 0; u = 3;
1668 break;
1669 case X86::BI__builtin_ia32_insertf32x8_mask:
1670 case X86::BI__builtin_ia32_inserti32x8_mask:
1671 case X86::BI__builtin_ia32_insertf64x4_mask:
1672 case X86::BI__builtin_ia32_inserti64x4_mask:
1673 case X86::BI__builtin_ia32_insertf64x2_256_mask:
1674 case X86::BI__builtin_ia32_inserti64x2_256_mask:
1675 case X86::BI__builtin_ia32_insertf32x4_256_mask:
1676 case X86::BI__builtin_ia32_inserti32x4_256_mask:
1677 i = 2; l = 0; u = 1;
Richard Trieucc3949d2016-02-18 22:34:54 +00001678 break;
1679 case X86::BI__builtin_ia32_sha1rnds4:
Craig Topper39c87102016-05-18 03:18:12 +00001680 case X86::BI__builtin_ia32_shuf_f32x4_256_mask:
1681 case X86::BI__builtin_ia32_shuf_f64x2_256_mask:
1682 case X86::BI__builtin_ia32_shuf_i32x4_256_mask:
1683 case X86::BI__builtin_ia32_shuf_i64x2_256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00001684 case X86::BI__builtin_ia32_insertf64x2_512_mask:
1685 case X86::BI__builtin_ia32_inserti64x2_512_mask:
1686 case X86::BI__builtin_ia32_insertf32x4_mask:
1687 case X86::BI__builtin_ia32_inserti32x4_mask:
1688 i = 2; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00001689 break;
Craig Topper1a8b0472015-01-31 08:57:52 +00001690 case X86::BI__builtin_ia32_vpermil2pd:
1691 case X86::BI__builtin_ia32_vpermil2pd256:
1692 case X86::BI__builtin_ia32_vpermil2ps:
Richard Trieucc3949d2016-02-18 22:34:54 +00001693 case X86::BI__builtin_ia32_vpermil2ps256:
Craig Topper39c87102016-05-18 03:18:12 +00001694 i = 3; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00001695 break;
Craig Topper95b0d732015-01-25 23:30:05 +00001696 case X86::BI__builtin_ia32_cmpb128_mask:
1697 case X86::BI__builtin_ia32_cmpw128_mask:
1698 case X86::BI__builtin_ia32_cmpd128_mask:
1699 case X86::BI__builtin_ia32_cmpq128_mask:
1700 case X86::BI__builtin_ia32_cmpb256_mask:
1701 case X86::BI__builtin_ia32_cmpw256_mask:
1702 case X86::BI__builtin_ia32_cmpd256_mask:
1703 case X86::BI__builtin_ia32_cmpq256_mask:
1704 case X86::BI__builtin_ia32_cmpb512_mask:
1705 case X86::BI__builtin_ia32_cmpw512_mask:
1706 case X86::BI__builtin_ia32_cmpd512_mask:
1707 case X86::BI__builtin_ia32_cmpq512_mask:
1708 case X86::BI__builtin_ia32_ucmpb128_mask:
1709 case X86::BI__builtin_ia32_ucmpw128_mask:
1710 case X86::BI__builtin_ia32_ucmpd128_mask:
1711 case X86::BI__builtin_ia32_ucmpq128_mask:
1712 case X86::BI__builtin_ia32_ucmpb256_mask:
1713 case X86::BI__builtin_ia32_ucmpw256_mask:
1714 case X86::BI__builtin_ia32_ucmpd256_mask:
1715 case X86::BI__builtin_ia32_ucmpq256_mask:
1716 case X86::BI__builtin_ia32_ucmpb512_mask:
1717 case X86::BI__builtin_ia32_ucmpw512_mask:
1718 case X86::BI__builtin_ia32_ucmpd512_mask:
Richard Trieucc3949d2016-02-18 22:34:54 +00001719 case X86::BI__builtin_ia32_ucmpq512_mask:
Craig Topper8dd7d0d2015-02-13 06:04:48 +00001720 case X86::BI__builtin_ia32_vpcomub:
1721 case X86::BI__builtin_ia32_vpcomuw:
1722 case X86::BI__builtin_ia32_vpcomud:
1723 case X86::BI__builtin_ia32_vpcomuq:
1724 case X86::BI__builtin_ia32_vpcomb:
1725 case X86::BI__builtin_ia32_vpcomw:
1726 case X86::BI__builtin_ia32_vpcomd:
Richard Trieucc3949d2016-02-18 22:34:54 +00001727 case X86::BI__builtin_ia32_vpcomq:
Craig Topper39c87102016-05-18 03:18:12 +00001728 i = 2; l = 0; u = 7;
1729 break;
1730 case X86::BI__builtin_ia32_roundps:
1731 case X86::BI__builtin_ia32_roundpd:
1732 case X86::BI__builtin_ia32_roundps256:
1733 case X86::BI__builtin_ia32_roundpd256:
Craig Topper39c87102016-05-18 03:18:12 +00001734 i = 1; l = 0; u = 15;
1735 break;
1736 case X86::BI__builtin_ia32_roundss:
1737 case X86::BI__builtin_ia32_roundsd:
1738 case X86::BI__builtin_ia32_rangepd128_mask:
1739 case X86::BI__builtin_ia32_rangepd256_mask:
1740 case X86::BI__builtin_ia32_rangepd512_mask:
1741 case X86::BI__builtin_ia32_rangeps128_mask:
1742 case X86::BI__builtin_ia32_rangeps256_mask:
1743 case X86::BI__builtin_ia32_rangeps512_mask:
1744 case X86::BI__builtin_ia32_getmantsd_round_mask:
1745 case X86::BI__builtin_ia32_getmantss_round_mask:
Craig Topper39c87102016-05-18 03:18:12 +00001746 i = 2; l = 0; u = 15;
1747 break;
1748 case X86::BI__builtin_ia32_cmpps:
1749 case X86::BI__builtin_ia32_cmpss:
1750 case X86::BI__builtin_ia32_cmppd:
1751 case X86::BI__builtin_ia32_cmpsd:
1752 case X86::BI__builtin_ia32_cmpps256:
1753 case X86::BI__builtin_ia32_cmppd256:
1754 case X86::BI__builtin_ia32_cmpps128_mask:
1755 case X86::BI__builtin_ia32_cmppd128_mask:
1756 case X86::BI__builtin_ia32_cmpps256_mask:
1757 case X86::BI__builtin_ia32_cmppd256_mask:
1758 case X86::BI__builtin_ia32_cmpps512_mask:
1759 case X86::BI__builtin_ia32_cmppd512_mask:
1760 case X86::BI__builtin_ia32_cmpsd_mask:
1761 case X86::BI__builtin_ia32_cmpss_mask:
1762 i = 2; l = 0; u = 31;
1763 break;
1764 case X86::BI__builtin_ia32_xabort:
1765 i = 0; l = -128; u = 255;
1766 break;
1767 case X86::BI__builtin_ia32_pshufw:
1768 case X86::BI__builtin_ia32_aeskeygenassist128:
1769 i = 1; l = -128; u = 255;
1770 break;
1771 case X86::BI__builtin_ia32_vcvtps2ph:
1772 case X86::BI__builtin_ia32_vcvtps2ph256:
Craig Topper39c87102016-05-18 03:18:12 +00001773 case X86::BI__builtin_ia32_rndscaleps_128_mask:
1774 case X86::BI__builtin_ia32_rndscalepd_128_mask:
1775 case X86::BI__builtin_ia32_rndscaleps_256_mask:
1776 case X86::BI__builtin_ia32_rndscalepd_256_mask:
1777 case X86::BI__builtin_ia32_rndscaleps_mask:
1778 case X86::BI__builtin_ia32_rndscalepd_mask:
1779 case X86::BI__builtin_ia32_reducepd128_mask:
1780 case X86::BI__builtin_ia32_reducepd256_mask:
1781 case X86::BI__builtin_ia32_reducepd512_mask:
1782 case X86::BI__builtin_ia32_reduceps128_mask:
1783 case X86::BI__builtin_ia32_reduceps256_mask:
1784 case X86::BI__builtin_ia32_reduceps512_mask:
1785 case X86::BI__builtin_ia32_prold512_mask:
1786 case X86::BI__builtin_ia32_prolq512_mask:
1787 case X86::BI__builtin_ia32_prold128_mask:
1788 case X86::BI__builtin_ia32_prold256_mask:
1789 case X86::BI__builtin_ia32_prolq128_mask:
1790 case X86::BI__builtin_ia32_prolq256_mask:
1791 case X86::BI__builtin_ia32_prord128_mask:
1792 case X86::BI__builtin_ia32_prord256_mask:
1793 case X86::BI__builtin_ia32_prorq128_mask:
1794 case X86::BI__builtin_ia32_prorq256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00001795 case X86::BI__builtin_ia32_psllwi512_mask:
1796 case X86::BI__builtin_ia32_psllwi128_mask:
1797 case X86::BI__builtin_ia32_psllwi256_mask:
1798 case X86::BI__builtin_ia32_psrldi128_mask:
1799 case X86::BI__builtin_ia32_psrldi256_mask:
1800 case X86::BI__builtin_ia32_psrldi512_mask:
1801 case X86::BI__builtin_ia32_psrlqi128_mask:
1802 case X86::BI__builtin_ia32_psrlqi256_mask:
1803 case X86::BI__builtin_ia32_psrlqi512_mask:
1804 case X86::BI__builtin_ia32_psrawi512_mask:
1805 case X86::BI__builtin_ia32_psrawi128_mask:
1806 case X86::BI__builtin_ia32_psrawi256_mask:
1807 case X86::BI__builtin_ia32_psrlwi512_mask:
1808 case X86::BI__builtin_ia32_psrlwi128_mask:
1809 case X86::BI__builtin_ia32_psrlwi256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00001810 case X86::BI__builtin_ia32_psradi128_mask:
1811 case X86::BI__builtin_ia32_psradi256_mask:
1812 case X86::BI__builtin_ia32_psradi512_mask:
1813 case X86::BI__builtin_ia32_psraqi128_mask:
1814 case X86::BI__builtin_ia32_psraqi256_mask:
1815 case X86::BI__builtin_ia32_psraqi512_mask:
1816 case X86::BI__builtin_ia32_pslldi128_mask:
1817 case X86::BI__builtin_ia32_pslldi256_mask:
1818 case X86::BI__builtin_ia32_pslldi512_mask:
1819 case X86::BI__builtin_ia32_psllqi128_mask:
1820 case X86::BI__builtin_ia32_psllqi256_mask:
1821 case X86::BI__builtin_ia32_psllqi512_mask:
Craig Topper39c87102016-05-18 03:18:12 +00001822 case X86::BI__builtin_ia32_fpclasspd128_mask:
1823 case X86::BI__builtin_ia32_fpclasspd256_mask:
1824 case X86::BI__builtin_ia32_fpclassps128_mask:
1825 case X86::BI__builtin_ia32_fpclassps256_mask:
1826 case X86::BI__builtin_ia32_fpclassps512_mask:
1827 case X86::BI__builtin_ia32_fpclasspd512_mask:
1828 case X86::BI__builtin_ia32_fpclasssd_mask:
1829 case X86::BI__builtin_ia32_fpclassss_mask:
Craig Topper39c87102016-05-18 03:18:12 +00001830 i = 1; l = 0; u = 255;
1831 break;
1832 case X86::BI__builtin_ia32_palignr:
1833 case X86::BI__builtin_ia32_insertps128:
1834 case X86::BI__builtin_ia32_dpps:
1835 case X86::BI__builtin_ia32_dppd:
1836 case X86::BI__builtin_ia32_dpps256:
1837 case X86::BI__builtin_ia32_mpsadbw128:
1838 case X86::BI__builtin_ia32_mpsadbw256:
1839 case X86::BI__builtin_ia32_pcmpistrm128:
1840 case X86::BI__builtin_ia32_pcmpistri128:
1841 case X86::BI__builtin_ia32_pcmpistria128:
1842 case X86::BI__builtin_ia32_pcmpistric128:
1843 case X86::BI__builtin_ia32_pcmpistrio128:
1844 case X86::BI__builtin_ia32_pcmpistris128:
1845 case X86::BI__builtin_ia32_pcmpistriz128:
1846 case X86::BI__builtin_ia32_pclmulqdq128:
1847 case X86::BI__builtin_ia32_vperm2f128_pd256:
1848 case X86::BI__builtin_ia32_vperm2f128_ps256:
1849 case X86::BI__builtin_ia32_vperm2f128_si256:
1850 case X86::BI__builtin_ia32_permti256:
1851 i = 2; l = -128; u = 255;
1852 break;
1853 case X86::BI__builtin_ia32_palignr128:
1854 case X86::BI__builtin_ia32_palignr256:
1855 case X86::BI__builtin_ia32_palignr128_mask:
1856 case X86::BI__builtin_ia32_palignr256_mask:
1857 case X86::BI__builtin_ia32_palignr512_mask:
1858 case X86::BI__builtin_ia32_alignq512_mask:
1859 case X86::BI__builtin_ia32_alignd512_mask:
1860 case X86::BI__builtin_ia32_alignd128_mask:
1861 case X86::BI__builtin_ia32_alignd256_mask:
1862 case X86::BI__builtin_ia32_alignq128_mask:
1863 case X86::BI__builtin_ia32_alignq256_mask:
1864 case X86::BI__builtin_ia32_vcomisd:
1865 case X86::BI__builtin_ia32_vcomiss:
1866 case X86::BI__builtin_ia32_shuf_f32x4_mask:
1867 case X86::BI__builtin_ia32_shuf_f64x2_mask:
1868 case X86::BI__builtin_ia32_shuf_i32x4_mask:
1869 case X86::BI__builtin_ia32_shuf_i64x2_mask:
Craig Topper39c87102016-05-18 03:18:12 +00001870 case X86::BI__builtin_ia32_dbpsadbw128_mask:
1871 case X86::BI__builtin_ia32_dbpsadbw256_mask:
1872 case X86::BI__builtin_ia32_dbpsadbw512_mask:
1873 i = 2; l = 0; u = 255;
1874 break;
1875 case X86::BI__builtin_ia32_fixupimmpd512_mask:
1876 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
1877 case X86::BI__builtin_ia32_fixupimmps512_mask:
1878 case X86::BI__builtin_ia32_fixupimmps512_maskz:
1879 case X86::BI__builtin_ia32_fixupimmsd_mask:
1880 case X86::BI__builtin_ia32_fixupimmsd_maskz:
1881 case X86::BI__builtin_ia32_fixupimmss_mask:
1882 case X86::BI__builtin_ia32_fixupimmss_maskz:
1883 case X86::BI__builtin_ia32_fixupimmpd128_mask:
1884 case X86::BI__builtin_ia32_fixupimmpd128_maskz:
1885 case X86::BI__builtin_ia32_fixupimmpd256_mask:
1886 case X86::BI__builtin_ia32_fixupimmpd256_maskz:
1887 case X86::BI__builtin_ia32_fixupimmps128_mask:
1888 case X86::BI__builtin_ia32_fixupimmps128_maskz:
1889 case X86::BI__builtin_ia32_fixupimmps256_mask:
1890 case X86::BI__builtin_ia32_fixupimmps256_maskz:
1891 case X86::BI__builtin_ia32_pternlogd512_mask:
1892 case X86::BI__builtin_ia32_pternlogd512_maskz:
1893 case X86::BI__builtin_ia32_pternlogq512_mask:
1894 case X86::BI__builtin_ia32_pternlogq512_maskz:
1895 case X86::BI__builtin_ia32_pternlogd128_mask:
1896 case X86::BI__builtin_ia32_pternlogd128_maskz:
1897 case X86::BI__builtin_ia32_pternlogd256_mask:
1898 case X86::BI__builtin_ia32_pternlogd256_maskz:
1899 case X86::BI__builtin_ia32_pternlogq128_mask:
1900 case X86::BI__builtin_ia32_pternlogq128_maskz:
1901 case X86::BI__builtin_ia32_pternlogq256_mask:
1902 case X86::BI__builtin_ia32_pternlogq256_maskz:
1903 i = 3; l = 0; u = 255;
1904 break;
1905 case X86::BI__builtin_ia32_pcmpestrm128:
1906 case X86::BI__builtin_ia32_pcmpestri128:
1907 case X86::BI__builtin_ia32_pcmpestria128:
1908 case X86::BI__builtin_ia32_pcmpestric128:
1909 case X86::BI__builtin_ia32_pcmpestrio128:
1910 case X86::BI__builtin_ia32_pcmpestris128:
1911 case X86::BI__builtin_ia32_pcmpestriz128:
1912 i = 4; l = -128; u = 255;
1913 break;
1914 case X86::BI__builtin_ia32_rndscalesd_round_mask:
1915 case X86::BI__builtin_ia32_rndscaless_round_mask:
1916 i = 4; l = 0; u = 255;
Richard Trieucc3949d2016-02-18 22:34:54 +00001917 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001918 }
Craig Topperdd84ec52014-12-27 07:00:08 +00001919 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001920}
1921
Richard Smith55ce3522012-06-25 20:30:08 +00001922/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
1923/// parameter with the FormatAttr's correct format_idx and firstDataArg.
1924/// Returns true when the format fits the function and the FormatStringInfo has
1925/// been populated.
1926bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
1927 FormatStringInfo *FSI) {
1928 FSI->HasVAListArg = Format->getFirstArg() == 0;
1929 FSI->FormatIdx = Format->getFormatIdx() - 1;
1930 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001931
Richard Smith55ce3522012-06-25 20:30:08 +00001932 // The way the format attribute works in GCC, the implicit this argument
1933 // of member functions is counted. However, it doesn't appear in our own
1934 // lists, so decrement format_idx in that case.
1935 if (IsCXXMember) {
1936 if(FSI->FormatIdx == 0)
1937 return false;
1938 --FSI->FormatIdx;
1939 if (FSI->FirstDataArg != 0)
1940 --FSI->FirstDataArg;
1941 }
1942 return true;
1943}
Mike Stump11289f42009-09-09 15:08:12 +00001944
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001945/// Checks if a the given expression evaluates to null.
1946///
1947/// \brief Returns true if the value evaluates to null.
George Burgess IV850269a2015-12-08 22:02:00 +00001948static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00001949 // If the expression has non-null type, it doesn't evaluate to null.
1950 if (auto nullability
1951 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
1952 if (*nullability == NullabilityKind::NonNull)
1953 return false;
1954 }
1955
Ted Kremeneka146db32014-01-17 06:24:47 +00001956 // As a special case, transparent unions initialized with zero are
1957 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001958 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +00001959 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
1960 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001961 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +00001962 if (const InitListExpr *ILE =
1963 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001964 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +00001965 }
1966
1967 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +00001968 return (!Expr->isValueDependent() &&
1969 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
1970 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001971}
1972
1973static void CheckNonNullArgument(Sema &S,
1974 const Expr *ArgExpr,
1975 SourceLocation CallSiteLoc) {
1976 if (CheckNonNullExpr(S, ArgExpr))
Eric Fiselier18677d52015-10-09 00:17:57 +00001977 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
1978 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
Ted Kremeneka146db32014-01-17 06:24:47 +00001979}
1980
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001981bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
1982 FormatStringInfo FSI;
1983 if ((GetFormatStringType(Format) == FST_NSString) &&
1984 getFormatStringInfo(Format, false, &FSI)) {
1985 Idx = FSI.FormatIdx;
1986 return true;
1987 }
1988 return false;
1989}
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001990/// \brief Diagnose use of %s directive in an NSString which is being passed
1991/// as formatting string to formatting method.
1992static void
1993DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
1994 const NamedDecl *FDecl,
1995 Expr **Args,
1996 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001997 unsigned Idx = 0;
1998 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001999 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
2000 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002001 Idx = 2;
2002 Format = true;
2003 }
2004 else
2005 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2006 if (S.GetFormatNSStringIdx(I, Idx)) {
2007 Format = true;
2008 break;
2009 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002010 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002011 if (!Format || NumArgs <= Idx)
2012 return;
2013 const Expr *FormatExpr = Args[Idx];
2014 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
2015 FormatExpr = CSCE->getSubExpr();
2016 const StringLiteral *FormatString;
2017 if (const ObjCStringLiteral *OSL =
2018 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
2019 FormatString = OSL->getString();
2020 else
2021 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
2022 if (!FormatString)
2023 return;
2024 if (S.FormatStringHasSArg(FormatString)) {
2025 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2026 << "%s" << 1 << 1;
2027 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
2028 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002029 }
2030}
2031
Douglas Gregorb4866e82015-06-19 18:13:19 +00002032/// Determine whether the given type has a non-null nullability annotation.
2033static bool isNonNullType(ASTContext &ctx, QualType type) {
2034 if (auto nullability = type->getNullability(ctx))
2035 return *nullability == NullabilityKind::NonNull;
2036
2037 return false;
2038}
2039
Ted Kremenek2bc73332014-01-17 06:24:43 +00002040static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00002041 const NamedDecl *FDecl,
Douglas Gregorb4866e82015-06-19 18:13:19 +00002042 const FunctionProtoType *Proto,
Richard Smith588bd9b2014-08-27 04:59:42 +00002043 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00002044 SourceLocation CallSiteLoc) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002045 assert((FDecl || Proto) && "Need a function declaration or prototype");
2046
Ted Kremenek9aedc152014-01-17 06:24:56 +00002047 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00002048 llvm::SmallBitVector NonNullArgs;
Douglas Gregorb4866e82015-06-19 18:13:19 +00002049 if (FDecl) {
2050 // Handle the nonnull attribute on the function/method declaration itself.
2051 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
2052 if (!NonNull->args_size()) {
2053 // Easy case: all pointer arguments are nonnull.
2054 for (const auto *Arg : Args)
2055 if (S.isValidPointerAttrType(Arg->getType()))
2056 CheckNonNullArgument(S, Arg, CallSiteLoc);
2057 return;
2058 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002059
Douglas Gregorb4866e82015-06-19 18:13:19 +00002060 for (unsigned Val : NonNull->args()) {
2061 if (Val >= Args.size())
2062 continue;
2063 if (NonNullArgs.empty())
2064 NonNullArgs.resize(Args.size());
2065 NonNullArgs.set(Val);
2066 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002067 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00002068 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00002069
Douglas Gregorb4866e82015-06-19 18:13:19 +00002070 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
2071 // Handle the nonnull attribute on the parameters of the
2072 // function/method.
2073 ArrayRef<ParmVarDecl*> parms;
2074 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
2075 parms = FD->parameters();
2076 else
2077 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
2078
2079 unsigned ParamIndex = 0;
2080 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
2081 I != E; ++I, ++ParamIndex) {
2082 const ParmVarDecl *PVD = *I;
2083 if (PVD->hasAttr<NonNullAttr>() ||
2084 isNonNullType(S.Context, PVD->getType())) {
2085 if (NonNullArgs.empty())
2086 NonNullArgs.resize(Args.size());
Ted Kremenek9aedc152014-01-17 06:24:56 +00002087
Douglas Gregorb4866e82015-06-19 18:13:19 +00002088 NonNullArgs.set(ParamIndex);
2089 }
2090 }
2091 } else {
2092 // If we have a non-function, non-method declaration but no
2093 // function prototype, try to dig out the function prototype.
2094 if (!Proto) {
2095 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
2096 QualType type = VD->getType().getNonReferenceType();
2097 if (auto pointerType = type->getAs<PointerType>())
2098 type = pointerType->getPointeeType();
2099 else if (auto blockType = type->getAs<BlockPointerType>())
2100 type = blockType->getPointeeType();
2101 // FIXME: data member pointers?
2102
2103 // Dig out the function prototype, if there is one.
2104 Proto = type->getAs<FunctionProtoType>();
2105 }
2106 }
2107
2108 // Fill in non-null argument information from the nullability
2109 // information on the parameter types (if we have them).
2110 if (Proto) {
2111 unsigned Index = 0;
2112 for (auto paramType : Proto->getParamTypes()) {
2113 if (isNonNullType(S.Context, paramType)) {
2114 if (NonNullArgs.empty())
2115 NonNullArgs.resize(Args.size());
2116
2117 NonNullArgs.set(Index);
2118 }
2119
2120 ++Index;
2121 }
2122 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00002123 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002124
Douglas Gregorb4866e82015-06-19 18:13:19 +00002125 // Check for non-null arguments.
2126 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
2127 ArgIndex != ArgIndexEnd; ++ArgIndex) {
Richard Smith588bd9b2014-08-27 04:59:42 +00002128 if (NonNullArgs[ArgIndex])
2129 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00002130 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00002131}
2132
Richard Smith55ce3522012-06-25 20:30:08 +00002133/// Handles the checks for format strings, non-POD arguments to vararg
2134/// functions, and NULL arguments passed to non-NULL parameters.
Douglas Gregorb4866e82015-06-19 18:13:19 +00002135void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
2136 ArrayRef<const Expr *> Args, bool IsMemberFunction,
Alp Toker9cacbab2014-01-20 20:26:09 +00002137 SourceLocation Loc, SourceRange Range,
Richard Smith55ce3522012-06-25 20:30:08 +00002138 VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00002139 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00002140 if (CurContext->isDependentContext())
2141 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00002142
Ted Kremenekb8176da2010-09-09 04:33:05 +00002143 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00002144 llvm::SmallBitVector CheckedVarArgs;
2145 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002146 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00002147 // Only create vector if there are format attributes.
2148 CheckedVarArgs.resize(Args.size());
2149
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002150 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00002151 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00002152 }
Richard Smithd7293d72013-08-05 18:49:43 +00002153 }
Richard Smith55ce3522012-06-25 20:30:08 +00002154
2155 // Refuse POD arguments that weren't caught by the format string
2156 // checks above.
Richard Smithd7293d72013-08-05 18:49:43 +00002157 if (CallType != VariadicDoesNotApply) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002158 unsigned NumParams = Proto ? Proto->getNumParams()
2159 : FDecl && isa<FunctionDecl>(FDecl)
2160 ? cast<FunctionDecl>(FDecl)->getNumParams()
2161 : FDecl && isa<ObjCMethodDecl>(FDecl)
2162 ? cast<ObjCMethodDecl>(FDecl)->param_size()
2163 : 0;
2164
Alp Toker9cacbab2014-01-20 20:26:09 +00002165 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00002166 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00002167 if (const Expr *Arg = Args[ArgIdx]) {
2168 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
2169 checkVariadicArgument(Arg, CallType);
2170 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00002171 }
Richard Smithd7293d72013-08-05 18:49:43 +00002172 }
Mike Stump11289f42009-09-09 15:08:12 +00002173
Douglas Gregorb4866e82015-06-19 18:13:19 +00002174 if (FDecl || Proto) {
2175 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00002176
Richard Trieu41bc0992013-06-22 00:20:41 +00002177 // Type safety checking.
Douglas Gregorb4866e82015-06-19 18:13:19 +00002178 if (FDecl) {
2179 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
2180 CheckArgumentWithTypeTag(I, Args.data());
2181 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00002182 }
Richard Smith55ce3522012-06-25 20:30:08 +00002183}
2184
2185/// CheckConstructorCall - Check a constructor call for correctness and safety
2186/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002187void Sema::CheckConstructorCall(FunctionDecl *FDecl,
2188 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002189 const FunctionProtoType *Proto,
2190 SourceLocation Loc) {
2191 VariadicCallType CallType =
2192 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Douglas Gregorb4866e82015-06-19 18:13:19 +00002193 checkCall(FDecl, Proto, Args, /*IsMemberFunction=*/true, Loc, SourceRange(),
2194 CallType);
Richard Smith55ce3522012-06-25 20:30:08 +00002195}
2196
2197/// CheckFunctionCall - Check a direct function call for various correctness
2198/// and safety properties not strictly enforced by the C type system.
2199bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
2200 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00002201 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
2202 isa<CXXMethodDecl>(FDecl);
2203 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
2204 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00002205 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
2206 TheCall->getCallee());
Eli Friedman726d11c2012-10-11 00:30:58 +00002207 Expr** Args = TheCall->getArgs();
2208 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmanadf42182012-10-11 00:34:15 +00002209 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00002210 // If this is a call to a member operator, hide the first argument
2211 // from checkCall.
2212 // FIXME: Our choice of AST representation here is less than ideal.
2213 ++Args;
2214 --NumArgs;
2215 }
Douglas Gregorb4866e82015-06-19 18:13:19 +00002216 checkCall(FDecl, Proto, llvm::makeArrayRef(Args, NumArgs),
Richard Smith55ce3522012-06-25 20:30:08 +00002217 IsMemberFunction, TheCall->getRParenLoc(),
2218 TheCall->getCallee()->getSourceRange(), CallType);
2219
2220 IdentifierInfo *FnInfo = FDecl->getIdentifier();
2221 // None of the checks below are needed for functions that don't have
2222 // simple names (e.g., C++ conversion functions).
2223 if (!FnInfo)
2224 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002225
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00002226 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002227 if (getLangOpts().ObjC1)
2228 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00002229
Anna Zaks22122702012-01-17 00:37:07 +00002230 unsigned CMId = FDecl->getMemoryFunctionKind();
2231 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00002232 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00002233
Anna Zaks201d4892012-01-13 21:52:01 +00002234 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00002235 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00002236 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00002237 else if (CMId == Builtin::BIstrncat)
2238 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00002239 else
Anna Zaks22122702012-01-17 00:37:07 +00002240 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00002241
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002242 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00002243}
2244
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002245bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00002246 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00002247 VariadicCallType CallType =
2248 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002249
Douglas Gregorb4866e82015-06-19 18:13:19 +00002250 checkCall(Method, nullptr, Args,
2251 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
2252 CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002253
2254 return false;
2255}
2256
Richard Trieu664c4c62013-06-20 21:03:13 +00002257bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
2258 const FunctionProtoType *Proto) {
Aaron Ballmanb673c652015-04-23 16:14:19 +00002259 QualType Ty;
2260 if (const auto *V = dyn_cast<VarDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00002261 Ty = V->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00002262 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00002263 Ty = F->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00002264 else
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002265 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002266
Douglas Gregorb4866e82015-06-19 18:13:19 +00002267 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
2268 !Ty->isFunctionProtoType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002269 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002270
Richard Trieu664c4c62013-06-20 21:03:13 +00002271 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00002272 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00002273 CallType = VariadicDoesNotApply;
2274 } else if (Ty->isBlockPointerType()) {
2275 CallType = VariadicBlock;
2276 } else { // Ty->isFunctionPointerType()
2277 CallType = VariadicFunction;
2278 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002279
Douglas Gregorb4866e82015-06-19 18:13:19 +00002280 checkCall(NDecl, Proto,
2281 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2282 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00002283 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00002284
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002285 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00002286}
2287
Richard Trieu41bc0992013-06-22 00:20:41 +00002288/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
2289/// such as function pointers returned from functions.
2290bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002291 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00002292 TheCall->getCallee());
Douglas Gregorb4866e82015-06-19 18:13:19 +00002293 checkCall(/*FDecl=*/nullptr, Proto,
Craig Topper8c2a2a02014-08-30 16:55:39 +00002294 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Douglas Gregorb4866e82015-06-19 18:13:19 +00002295 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00002296 TheCall->getCallee()->getSourceRange(), CallType);
2297
2298 return false;
2299}
2300
Tim Northovere94a34c2014-03-11 10:49:14 +00002301static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
JF Bastiendda2cb12016-04-18 18:01:49 +00002302 if (!llvm::isValidAtomicOrderingCABI(Ordering))
Tim Northovere94a34c2014-03-11 10:49:14 +00002303 return false;
2304
JF Bastiendda2cb12016-04-18 18:01:49 +00002305 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
Tim Northovere94a34c2014-03-11 10:49:14 +00002306 switch (Op) {
2307 case AtomicExpr::AO__c11_atomic_init:
2308 llvm_unreachable("There is no ordering argument for an init");
2309
2310 case AtomicExpr::AO__c11_atomic_load:
2311 case AtomicExpr::AO__atomic_load_n:
2312 case AtomicExpr::AO__atomic_load:
JF Bastiendda2cb12016-04-18 18:01:49 +00002313 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
2314 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00002315
2316 case AtomicExpr::AO__c11_atomic_store:
2317 case AtomicExpr::AO__atomic_store:
2318 case AtomicExpr::AO__atomic_store_n:
JF Bastiendda2cb12016-04-18 18:01:49 +00002319 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
2320 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
2321 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00002322
2323 default:
2324 return true;
2325 }
2326}
2327
Richard Smithfeea8832012-04-12 05:08:17 +00002328ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
2329 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002330 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
2331 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002332
Richard Smithfeea8832012-04-12 05:08:17 +00002333 // All these operations take one of the following forms:
2334 enum {
2335 // C __c11_atomic_init(A *, C)
2336 Init,
2337 // C __c11_atomic_load(A *, int)
2338 Load,
2339 // void __atomic_load(A *, CP, int)
Eric Fiselier8d662442016-03-30 23:39:56 +00002340 LoadCopy,
2341 // void __atomic_store(A *, CP, int)
Richard Smithfeea8832012-04-12 05:08:17 +00002342 Copy,
2343 // C __c11_atomic_add(A *, M, int)
2344 Arithmetic,
2345 // C __atomic_exchange_n(A *, CP, int)
2346 Xchg,
2347 // void __atomic_exchange(A *, C *, CP, int)
2348 GNUXchg,
2349 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
2350 C11CmpXchg,
2351 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
2352 GNUCmpXchg
2353 } Form = Init;
Eric Fiselier8d662442016-03-30 23:39:56 +00002354 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
2355 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
Richard Smithfeea8832012-04-12 05:08:17 +00002356 // where:
2357 // C is an appropriate type,
2358 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
2359 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
2360 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
2361 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002362
Gabor Horvath98bd0982015-03-16 09:59:54 +00002363 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
2364 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
2365 AtomicExpr::AO__atomic_load,
2366 "need to update code for modified C11 atomics");
Richard Smithfeea8832012-04-12 05:08:17 +00002367 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
2368 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
2369 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
2370 Op == AtomicExpr::AO__atomic_store_n ||
2371 Op == AtomicExpr::AO__atomic_exchange_n ||
2372 Op == AtomicExpr::AO__atomic_compare_exchange_n;
2373 bool IsAddSub = false;
2374
2375 switch (Op) {
2376 case AtomicExpr::AO__c11_atomic_init:
2377 Form = Init;
2378 break;
2379
2380 case AtomicExpr::AO__c11_atomic_load:
2381 case AtomicExpr::AO__atomic_load_n:
2382 Form = Load;
2383 break;
2384
Richard Smithfeea8832012-04-12 05:08:17 +00002385 case AtomicExpr::AO__atomic_load:
Eric Fiselier8d662442016-03-30 23:39:56 +00002386 Form = LoadCopy;
2387 break;
2388
2389 case AtomicExpr::AO__c11_atomic_store:
Richard Smithfeea8832012-04-12 05:08:17 +00002390 case AtomicExpr::AO__atomic_store:
2391 case AtomicExpr::AO__atomic_store_n:
2392 Form = Copy;
2393 break;
2394
2395 case AtomicExpr::AO__c11_atomic_fetch_add:
2396 case AtomicExpr::AO__c11_atomic_fetch_sub:
2397 case AtomicExpr::AO__atomic_fetch_add:
2398 case AtomicExpr::AO__atomic_fetch_sub:
2399 case AtomicExpr::AO__atomic_add_fetch:
2400 case AtomicExpr::AO__atomic_sub_fetch:
2401 IsAddSub = true;
2402 // Fall through.
2403 case AtomicExpr::AO__c11_atomic_fetch_and:
2404 case AtomicExpr::AO__c11_atomic_fetch_or:
2405 case AtomicExpr::AO__c11_atomic_fetch_xor:
2406 case AtomicExpr::AO__atomic_fetch_and:
2407 case AtomicExpr::AO__atomic_fetch_or:
2408 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00002409 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00002410 case AtomicExpr::AO__atomic_and_fetch:
2411 case AtomicExpr::AO__atomic_or_fetch:
2412 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00002413 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00002414 Form = Arithmetic;
2415 break;
2416
2417 case AtomicExpr::AO__c11_atomic_exchange:
2418 case AtomicExpr::AO__atomic_exchange_n:
2419 Form = Xchg;
2420 break;
2421
2422 case AtomicExpr::AO__atomic_exchange:
2423 Form = GNUXchg;
2424 break;
2425
2426 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
2427 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
2428 Form = C11CmpXchg;
2429 break;
2430
2431 case AtomicExpr::AO__atomic_compare_exchange:
2432 case AtomicExpr::AO__atomic_compare_exchange_n:
2433 Form = GNUCmpXchg;
2434 break;
2435 }
2436
2437 // Check we have the right number of arguments.
2438 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002439 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithfeea8832012-04-12 05:08:17 +00002440 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002441 << TheCall->getCallee()->getSourceRange();
2442 return ExprError();
Richard Smithfeea8832012-04-12 05:08:17 +00002443 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
2444 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002445 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00002446 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002447 << TheCall->getCallee()->getSourceRange();
2448 return ExprError();
2449 }
2450
Richard Smithfeea8832012-04-12 05:08:17 +00002451 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002452 Expr *Ptr = TheCall->getArg(0);
George Burgess IV92b43a42016-07-21 03:28:13 +00002453 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
2454 if (ConvertedPtr.isInvalid())
2455 return ExprError();
2456
2457 Ptr = ConvertedPtr.get();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002458 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
2459 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00002460 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002461 << Ptr->getType() << Ptr->getSourceRange();
2462 return ExprError();
2463 }
2464
Richard Smithfeea8832012-04-12 05:08:17 +00002465 // For a __c11 builtin, this should be a pointer to an _Atomic type.
2466 QualType AtomTy = pointerType->getPointeeType(); // 'A'
2467 QualType ValType = AtomTy; // 'C'
2468 if (IsC11) {
2469 if (!AtomTy->isAtomicType()) {
2470 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
2471 << Ptr->getType() << Ptr->getSourceRange();
2472 return ExprError();
2473 }
Richard Smithe00921a2012-09-15 06:09:58 +00002474 if (AtomTy.isConstQualified()) {
2475 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
2476 << Ptr->getType() << Ptr->getSourceRange();
2477 return ExprError();
2478 }
Richard Smithfeea8832012-04-12 05:08:17 +00002479 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eric Fiselier8d662442016-03-30 23:39:56 +00002480 } else if (Form != Load && Form != LoadCopy) {
Eric Fiseliera3a7c562015-10-04 00:11:02 +00002481 if (ValType.isConstQualified()) {
2482 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
2483 << Ptr->getType() << Ptr->getSourceRange();
2484 return ExprError();
2485 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002486 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002487
Richard Smithfeea8832012-04-12 05:08:17 +00002488 // For an arithmetic operation, the implied arithmetic must be well-formed.
2489 if (Form == Arithmetic) {
2490 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
2491 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
2492 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
2493 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2494 return ExprError();
2495 }
2496 if (!IsAddSub && !ValType->isIntegerType()) {
2497 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
2498 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2499 return ExprError();
2500 }
David Majnemere85cff82015-01-28 05:48:06 +00002501 if (IsC11 && ValType->isPointerType() &&
2502 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
2503 diag::err_incomplete_type)) {
2504 return ExprError();
2505 }
Richard Smithfeea8832012-04-12 05:08:17 +00002506 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
2507 // For __atomic_*_n operations, the value type must be a scalar integral or
2508 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002509 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00002510 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2511 return ExprError();
2512 }
2513
Eli Friedmanaa769812013-09-11 03:49:34 +00002514 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
2515 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00002516 // For GNU atomics, require a trivially-copyable type. This is not part of
2517 // the GNU atomics specification, but we enforce it for sanity.
2518 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002519 << Ptr->getType() << Ptr->getSourceRange();
2520 return ExprError();
2521 }
2522
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002523 switch (ValType.getObjCLifetime()) {
2524 case Qualifiers::OCL_None:
2525 case Qualifiers::OCL_ExplicitNone:
2526 // okay
2527 break;
2528
2529 case Qualifiers::OCL_Weak:
2530 case Qualifiers::OCL_Strong:
2531 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00002532 // FIXME: Can this happen? By this point, ValType should be known
2533 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002534 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
2535 << ValType << Ptr->getSourceRange();
2536 return ExprError();
2537 }
2538
David Majnemerc6eb6502015-06-03 00:26:35 +00002539 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the
2540 // volatile-ness of the pointee-type inject itself into the result or the
Eric Fiselier8d662442016-03-30 23:39:56 +00002541 // other operands. Similarly atomic_load can take a pointer to a const 'A'.
David Majnemerc6eb6502015-06-03 00:26:35 +00002542 ValType.removeLocalVolatile();
Eric Fiselier8d662442016-03-30 23:39:56 +00002543 ValType.removeLocalConst();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002544 QualType ResultType = ValType;
Eric Fiselier8d662442016-03-30 23:39:56 +00002545 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002546 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00002547 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002548 ResultType = Context.BoolTy;
2549
Richard Smithfeea8832012-04-12 05:08:17 +00002550 // The type of a parameter passed 'by value'. In the GNU atomics, such
2551 // arguments are actually passed as pointers.
2552 QualType ByValType = ValType; // 'CP'
2553 if (!IsC11 && !IsN)
2554 ByValType = Ptr->getType();
2555
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002556 // The first argument --- the pointer --- has a fixed type; we
2557 // deduce the types of the rest of the arguments accordingly. Walk
2558 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00002559 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002560 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00002561 if (i < NumVals[Form] + 1) {
2562 switch (i) {
2563 case 1:
2564 // The second argument is the non-atomic operand. For arithmetic, this
2565 // is always passed by value, and for a compare_exchange it is always
2566 // passed by address. For the rest, GNU uses by-address and C11 uses
2567 // by-value.
2568 assert(Form != Load);
2569 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
2570 Ty = ValType;
2571 else if (Form == Copy || Form == Xchg)
2572 Ty = ByValType;
2573 else if (Form == Arithmetic)
2574 Ty = Context.getPointerDiffType();
Anastasia Stulova76fd1052015-12-22 15:14:54 +00002575 else {
2576 Expr *ValArg = TheCall->getArg(i);
2577 unsigned AS = 0;
2578 // Keep address space of non-atomic pointer type.
2579 if (const PointerType *PtrTy =
2580 ValArg->getType()->getAs<PointerType>()) {
2581 AS = PtrTy->getPointeeType().getAddressSpace();
2582 }
2583 Ty = Context.getPointerType(
2584 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
2585 }
Richard Smithfeea8832012-04-12 05:08:17 +00002586 break;
2587 case 2:
2588 // The third argument to compare_exchange / GNU exchange is a
2589 // (pointer to a) desired value.
2590 Ty = ByValType;
2591 break;
2592 case 3:
2593 // The fourth argument to GNU compare_exchange is a 'weak' flag.
2594 Ty = Context.BoolTy;
2595 break;
2596 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002597 } else {
2598 // The order(s) are always converted to int.
2599 Ty = Context.IntTy;
2600 }
Richard Smithfeea8832012-04-12 05:08:17 +00002601
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002602 InitializedEntity Entity =
2603 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00002604 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002605 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2606 if (Arg.isInvalid())
2607 return true;
2608 TheCall->setArg(i, Arg.get());
2609 }
2610
Richard Smithfeea8832012-04-12 05:08:17 +00002611 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002612 SmallVector<Expr*, 5> SubExprs;
2613 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00002614 switch (Form) {
2615 case Init:
2616 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00002617 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00002618 break;
2619 case Load:
2620 SubExprs.push_back(TheCall->getArg(1)); // Order
2621 break;
Eric Fiselier8d662442016-03-30 23:39:56 +00002622 case LoadCopy:
Richard Smithfeea8832012-04-12 05:08:17 +00002623 case Copy:
2624 case Arithmetic:
2625 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002626 SubExprs.push_back(TheCall->getArg(2)); // Order
2627 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00002628 break;
2629 case GNUXchg:
2630 // Note, AtomicExpr::getVal2() has a special case for this atomic.
2631 SubExprs.push_back(TheCall->getArg(3)); // Order
2632 SubExprs.push_back(TheCall->getArg(1)); // Val1
2633 SubExprs.push_back(TheCall->getArg(2)); // Val2
2634 break;
2635 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002636 SubExprs.push_back(TheCall->getArg(3)); // Order
2637 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002638 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00002639 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00002640 break;
2641 case GNUCmpXchg:
2642 SubExprs.push_back(TheCall->getArg(4)); // Order
2643 SubExprs.push_back(TheCall->getArg(1)); // Val1
2644 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
2645 SubExprs.push_back(TheCall->getArg(2)); // Val2
2646 SubExprs.push_back(TheCall->getArg(3)); // Weak
2647 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002648 }
Tim Northovere94a34c2014-03-11 10:49:14 +00002649
2650 if (SubExprs.size() >= 2 && Form != Init) {
2651 llvm::APSInt Result(32);
2652 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
2653 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00002654 Diag(SubExprs[1]->getLocStart(),
2655 diag::warn_atomic_op_has_invalid_memory_order)
2656 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00002657 }
2658
Fariborz Jahanian615de762013-05-28 17:37:39 +00002659 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
2660 SubExprs, ResultType, Op,
2661 TheCall->getRParenLoc());
2662
2663 if ((Op == AtomicExpr::AO__c11_atomic_load ||
2664 (Op == AtomicExpr::AO__c11_atomic_store)) &&
2665 Context.AtomicUsesUnsupportedLibcall(AE))
2666 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
2667 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002668
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002669 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002670}
2671
John McCall29ad95b2011-08-27 01:09:30 +00002672/// checkBuiltinArgument - Given a call to a builtin function, perform
2673/// normal type-checking on the given argument, updating the call in
2674/// place. This is useful when a builtin function requires custom
2675/// type-checking for some of its arguments but not necessarily all of
2676/// them.
2677///
2678/// Returns true on error.
2679static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
2680 FunctionDecl *Fn = E->getDirectCallee();
2681 assert(Fn && "builtin call without direct callee!");
2682
2683 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
2684 InitializedEntity Entity =
2685 InitializedEntity::InitializeParameter(S.Context, Param);
2686
2687 ExprResult Arg = E->getArg(0);
2688 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
2689 if (Arg.isInvalid())
2690 return true;
2691
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002692 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00002693 return false;
2694}
2695
Chris Lattnerdc046542009-05-08 06:58:22 +00002696/// SemaBuiltinAtomicOverloaded - We have a call to a function like
2697/// __sync_fetch_and_add, which is an overloaded function based on the pointer
2698/// type of its first argument. The main ActOnCallExpr routines have already
2699/// promoted the types of arguments because all of these calls are prototyped as
2700/// void(...).
2701///
2702/// This function goes through and does final semantic checking for these
2703/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00002704ExprResult
2705Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002706 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00002707 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2708 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2709
2710 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002711 if (TheCall->getNumArgs() < 1) {
2712 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
2713 << 0 << 1 << TheCall->getNumArgs()
2714 << TheCall->getCallee()->getSourceRange();
2715 return ExprError();
2716 }
Mike Stump11289f42009-09-09 15:08:12 +00002717
Chris Lattnerdc046542009-05-08 06:58:22 +00002718 // Inspect the first argument of the atomic builtin. This should always be
2719 // a pointer type, whose element is an integral scalar or pointer type.
2720 // Because it is a pointer type, we don't have to worry about any implicit
2721 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002722 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00002723 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00002724 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
2725 if (FirstArgResult.isInvalid())
2726 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002727 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00002728 TheCall->setArg(0, FirstArg);
2729
John McCall31168b02011-06-15 23:02:42 +00002730 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
2731 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002732 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
2733 << FirstArg->getType() << FirstArg->getSourceRange();
2734 return ExprError();
2735 }
Mike Stump11289f42009-09-09 15:08:12 +00002736
John McCall31168b02011-06-15 23:02:42 +00002737 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00002738 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002739 !ValType->isBlockPointerType()) {
2740 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
2741 << FirstArg->getType() << FirstArg->getSourceRange();
2742 return ExprError();
2743 }
Chris Lattnerdc046542009-05-08 06:58:22 +00002744
John McCall31168b02011-06-15 23:02:42 +00002745 switch (ValType.getObjCLifetime()) {
2746 case Qualifiers::OCL_None:
2747 case Qualifiers::OCL_ExplicitNone:
2748 // okay
2749 break;
2750
2751 case Qualifiers::OCL_Weak:
2752 case Qualifiers::OCL_Strong:
2753 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00002754 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00002755 << ValType << FirstArg->getSourceRange();
2756 return ExprError();
2757 }
2758
John McCallb50451a2011-10-05 07:41:44 +00002759 // Strip any qualifiers off ValType.
2760 ValType = ValType.getUnqualifiedType();
2761
Chandler Carruth3973af72010-07-18 20:54:12 +00002762 // The majority of builtins return a value, but a few have special return
2763 // types, so allow them to override appropriately below.
2764 QualType ResultType = ValType;
2765
Chris Lattnerdc046542009-05-08 06:58:22 +00002766 // We need to figure out which concrete builtin this maps onto. For example,
2767 // __sync_fetch_and_add with a 2 byte object turns into
2768 // __sync_fetch_and_add_2.
2769#define BUILTIN_ROW(x) \
2770 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
2771 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00002772
Chris Lattnerdc046542009-05-08 06:58:22 +00002773 static const unsigned BuiltinIndices[][5] = {
2774 BUILTIN_ROW(__sync_fetch_and_add),
2775 BUILTIN_ROW(__sync_fetch_and_sub),
2776 BUILTIN_ROW(__sync_fetch_and_or),
2777 BUILTIN_ROW(__sync_fetch_and_and),
2778 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00002779 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00002780
Chris Lattnerdc046542009-05-08 06:58:22 +00002781 BUILTIN_ROW(__sync_add_and_fetch),
2782 BUILTIN_ROW(__sync_sub_and_fetch),
2783 BUILTIN_ROW(__sync_and_and_fetch),
2784 BUILTIN_ROW(__sync_or_and_fetch),
2785 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00002786 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00002787
Chris Lattnerdc046542009-05-08 06:58:22 +00002788 BUILTIN_ROW(__sync_val_compare_and_swap),
2789 BUILTIN_ROW(__sync_bool_compare_and_swap),
2790 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00002791 BUILTIN_ROW(__sync_lock_release),
2792 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00002793 };
Mike Stump11289f42009-09-09 15:08:12 +00002794#undef BUILTIN_ROW
2795
Chris Lattnerdc046542009-05-08 06:58:22 +00002796 // Determine the index of the size.
2797 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00002798 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00002799 case 1: SizeIndex = 0; break;
2800 case 2: SizeIndex = 1; break;
2801 case 4: SizeIndex = 2; break;
2802 case 8: SizeIndex = 3; break;
2803 case 16: SizeIndex = 4; break;
2804 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002805 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
2806 << FirstArg->getType() << FirstArg->getSourceRange();
2807 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00002808 }
Mike Stump11289f42009-09-09 15:08:12 +00002809
Chris Lattnerdc046542009-05-08 06:58:22 +00002810 // Each of these builtins has one pointer argument, followed by some number of
2811 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
2812 // that we ignore. Find out which row of BuiltinIndices to read from as well
2813 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00002814 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00002815 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00002816 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00002817 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00002818 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00002819 case Builtin::BI__sync_fetch_and_add:
2820 case Builtin::BI__sync_fetch_and_add_1:
2821 case Builtin::BI__sync_fetch_and_add_2:
2822 case Builtin::BI__sync_fetch_and_add_4:
2823 case Builtin::BI__sync_fetch_and_add_8:
2824 case Builtin::BI__sync_fetch_and_add_16:
2825 BuiltinIndex = 0;
2826 break;
2827
2828 case Builtin::BI__sync_fetch_and_sub:
2829 case Builtin::BI__sync_fetch_and_sub_1:
2830 case Builtin::BI__sync_fetch_and_sub_2:
2831 case Builtin::BI__sync_fetch_and_sub_4:
2832 case Builtin::BI__sync_fetch_and_sub_8:
2833 case Builtin::BI__sync_fetch_and_sub_16:
2834 BuiltinIndex = 1;
2835 break;
2836
2837 case Builtin::BI__sync_fetch_and_or:
2838 case Builtin::BI__sync_fetch_and_or_1:
2839 case Builtin::BI__sync_fetch_and_or_2:
2840 case Builtin::BI__sync_fetch_and_or_4:
2841 case Builtin::BI__sync_fetch_and_or_8:
2842 case Builtin::BI__sync_fetch_and_or_16:
2843 BuiltinIndex = 2;
2844 break;
2845
2846 case Builtin::BI__sync_fetch_and_and:
2847 case Builtin::BI__sync_fetch_and_and_1:
2848 case Builtin::BI__sync_fetch_and_and_2:
2849 case Builtin::BI__sync_fetch_and_and_4:
2850 case Builtin::BI__sync_fetch_and_and_8:
2851 case Builtin::BI__sync_fetch_and_and_16:
2852 BuiltinIndex = 3;
2853 break;
Mike Stump11289f42009-09-09 15:08:12 +00002854
Douglas Gregor73722482011-11-28 16:30:08 +00002855 case Builtin::BI__sync_fetch_and_xor:
2856 case Builtin::BI__sync_fetch_and_xor_1:
2857 case Builtin::BI__sync_fetch_and_xor_2:
2858 case Builtin::BI__sync_fetch_and_xor_4:
2859 case Builtin::BI__sync_fetch_and_xor_8:
2860 case Builtin::BI__sync_fetch_and_xor_16:
2861 BuiltinIndex = 4;
2862 break;
2863
Hal Finkeld2208b52014-10-02 20:53:50 +00002864 case Builtin::BI__sync_fetch_and_nand:
2865 case Builtin::BI__sync_fetch_and_nand_1:
2866 case Builtin::BI__sync_fetch_and_nand_2:
2867 case Builtin::BI__sync_fetch_and_nand_4:
2868 case Builtin::BI__sync_fetch_and_nand_8:
2869 case Builtin::BI__sync_fetch_and_nand_16:
2870 BuiltinIndex = 5;
2871 WarnAboutSemanticsChange = true;
2872 break;
2873
Douglas Gregor73722482011-11-28 16:30:08 +00002874 case Builtin::BI__sync_add_and_fetch:
2875 case Builtin::BI__sync_add_and_fetch_1:
2876 case Builtin::BI__sync_add_and_fetch_2:
2877 case Builtin::BI__sync_add_and_fetch_4:
2878 case Builtin::BI__sync_add_and_fetch_8:
2879 case Builtin::BI__sync_add_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002880 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00002881 break;
2882
2883 case Builtin::BI__sync_sub_and_fetch:
2884 case Builtin::BI__sync_sub_and_fetch_1:
2885 case Builtin::BI__sync_sub_and_fetch_2:
2886 case Builtin::BI__sync_sub_and_fetch_4:
2887 case Builtin::BI__sync_sub_and_fetch_8:
2888 case Builtin::BI__sync_sub_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002889 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00002890 break;
2891
2892 case Builtin::BI__sync_and_and_fetch:
2893 case Builtin::BI__sync_and_and_fetch_1:
2894 case Builtin::BI__sync_and_and_fetch_2:
2895 case Builtin::BI__sync_and_and_fetch_4:
2896 case Builtin::BI__sync_and_and_fetch_8:
2897 case Builtin::BI__sync_and_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002898 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00002899 break;
2900
2901 case Builtin::BI__sync_or_and_fetch:
2902 case Builtin::BI__sync_or_and_fetch_1:
2903 case Builtin::BI__sync_or_and_fetch_2:
2904 case Builtin::BI__sync_or_and_fetch_4:
2905 case Builtin::BI__sync_or_and_fetch_8:
2906 case Builtin::BI__sync_or_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002907 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00002908 break;
2909
2910 case Builtin::BI__sync_xor_and_fetch:
2911 case Builtin::BI__sync_xor_and_fetch_1:
2912 case Builtin::BI__sync_xor_and_fetch_2:
2913 case Builtin::BI__sync_xor_and_fetch_4:
2914 case Builtin::BI__sync_xor_and_fetch_8:
2915 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002916 BuiltinIndex = 10;
2917 break;
2918
2919 case Builtin::BI__sync_nand_and_fetch:
2920 case Builtin::BI__sync_nand_and_fetch_1:
2921 case Builtin::BI__sync_nand_and_fetch_2:
2922 case Builtin::BI__sync_nand_and_fetch_4:
2923 case Builtin::BI__sync_nand_and_fetch_8:
2924 case Builtin::BI__sync_nand_and_fetch_16:
2925 BuiltinIndex = 11;
2926 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00002927 break;
Mike Stump11289f42009-09-09 15:08:12 +00002928
Chris Lattnerdc046542009-05-08 06:58:22 +00002929 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00002930 case Builtin::BI__sync_val_compare_and_swap_1:
2931 case Builtin::BI__sync_val_compare_and_swap_2:
2932 case Builtin::BI__sync_val_compare_and_swap_4:
2933 case Builtin::BI__sync_val_compare_and_swap_8:
2934 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002935 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00002936 NumFixed = 2;
2937 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002938
Chris Lattnerdc046542009-05-08 06:58:22 +00002939 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00002940 case Builtin::BI__sync_bool_compare_and_swap_1:
2941 case Builtin::BI__sync_bool_compare_and_swap_2:
2942 case Builtin::BI__sync_bool_compare_and_swap_4:
2943 case Builtin::BI__sync_bool_compare_and_swap_8:
2944 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002945 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00002946 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00002947 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00002948 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002949
2950 case Builtin::BI__sync_lock_test_and_set:
2951 case Builtin::BI__sync_lock_test_and_set_1:
2952 case Builtin::BI__sync_lock_test_and_set_2:
2953 case Builtin::BI__sync_lock_test_and_set_4:
2954 case Builtin::BI__sync_lock_test_and_set_8:
2955 case Builtin::BI__sync_lock_test_and_set_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002956 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00002957 break;
2958
Chris Lattnerdc046542009-05-08 06:58:22 +00002959 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00002960 case Builtin::BI__sync_lock_release_1:
2961 case Builtin::BI__sync_lock_release_2:
2962 case Builtin::BI__sync_lock_release_4:
2963 case Builtin::BI__sync_lock_release_8:
2964 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002965 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00002966 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00002967 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00002968 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002969
2970 case Builtin::BI__sync_swap:
2971 case Builtin::BI__sync_swap_1:
2972 case Builtin::BI__sync_swap_2:
2973 case Builtin::BI__sync_swap_4:
2974 case Builtin::BI__sync_swap_8:
2975 case Builtin::BI__sync_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002976 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00002977 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00002978 }
Mike Stump11289f42009-09-09 15:08:12 +00002979
Chris Lattnerdc046542009-05-08 06:58:22 +00002980 // Now that we know how many fixed arguments we expect, first check that we
2981 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002982 if (TheCall->getNumArgs() < 1+NumFixed) {
2983 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
2984 << 0 << 1+NumFixed << TheCall->getNumArgs()
2985 << TheCall->getCallee()->getSourceRange();
2986 return ExprError();
2987 }
Mike Stump11289f42009-09-09 15:08:12 +00002988
Hal Finkeld2208b52014-10-02 20:53:50 +00002989 if (WarnAboutSemanticsChange) {
2990 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
2991 << TheCall->getCallee()->getSourceRange();
2992 }
2993
Chris Lattner5b9241b2009-05-08 15:36:58 +00002994 // Get the decl for the concrete builtin from this, we can tell what the
2995 // concrete integer type we should convert to is.
2996 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
Eric Christopher02d5d862015-08-06 01:01:12 +00002997 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00002998 FunctionDecl *NewBuiltinDecl;
2999 if (NewBuiltinID == BuiltinID)
3000 NewBuiltinDecl = FDecl;
3001 else {
3002 // Perform builtin lookup to avoid redeclaring it.
3003 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
3004 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
3005 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
3006 assert(Res.getFoundDecl());
3007 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00003008 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00003009 return ExprError();
3010 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003011
John McCallcf142162010-08-07 06:22:56 +00003012 // The first argument --- the pointer --- has a fixed type; we
3013 // deduce the types of the rest of the arguments accordingly. Walk
3014 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00003015 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00003016 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00003017
Chris Lattnerdc046542009-05-08 06:58:22 +00003018 // GCC does an implicit conversion to the pointer or integer ValType. This
3019 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00003020 // Initialize the argument.
3021 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3022 ValType, /*consume*/ false);
3023 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00003024 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003025 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003026
Chris Lattnerdc046542009-05-08 06:58:22 +00003027 // Okay, we have something that *can* be converted to the right type. Check
3028 // to see if there is a potentially weird extension going on here. This can
3029 // happen when you do an atomic operation on something like an char* and
3030 // pass in 42. The 42 gets converted to char. This is even more strange
3031 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00003032 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003033 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00003034 }
Mike Stump11289f42009-09-09 15:08:12 +00003035
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003036 ASTContext& Context = this->getASTContext();
3037
3038 // Create a new DeclRefExpr to refer to the new decl.
3039 DeclRefExpr* NewDRE = DeclRefExpr::Create(
3040 Context,
3041 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00003042 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003043 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00003044 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003045 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00003046 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003047 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00003048
Chris Lattnerdc046542009-05-08 06:58:22 +00003049 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00003050 // FIXME: This loses syntactic information.
3051 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
3052 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
3053 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003054 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00003055
Chandler Carruthbc8cab12010-07-18 07:23:17 +00003056 // Change the result type of the call to match the original value type. This
3057 // is arbitrary, but the codegen for these builtins ins design to handle it
3058 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00003059 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003060
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003061 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00003062}
3063
Michael Zolotukhin84df1232015-09-08 23:52:33 +00003064/// SemaBuiltinNontemporalOverloaded - We have a call to
3065/// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
3066/// overloaded function based on the pointer type of its last argument.
3067///
3068/// This function goes through and does final semantic checking for these
3069/// builtins.
3070ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
3071 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3072 DeclRefExpr *DRE =
3073 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3074 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3075 unsigned BuiltinID = FDecl->getBuiltinID();
3076 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
3077 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
3078 "Unexpected nontemporal load/store builtin!");
3079 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
3080 unsigned numArgs = isStore ? 2 : 1;
3081
3082 // Ensure that we have the proper number of arguments.
3083 if (checkArgCount(*this, TheCall, numArgs))
3084 return ExprError();
3085
3086 // Inspect the last argument of the nontemporal builtin. This should always
3087 // be a pointer type, from which we imply the type of the memory access.
3088 // Because it is a pointer type, we don't have to worry about any implicit
3089 // casts here.
3090 Expr *PointerArg = TheCall->getArg(numArgs - 1);
3091 ExprResult PointerArgResult =
3092 DefaultFunctionArrayLvalueConversion(PointerArg);
3093
3094 if (PointerArgResult.isInvalid())
3095 return ExprError();
3096 PointerArg = PointerArgResult.get();
3097 TheCall->setArg(numArgs - 1, PointerArg);
3098
3099 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
3100 if (!pointerType) {
3101 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
3102 << PointerArg->getType() << PointerArg->getSourceRange();
3103 return ExprError();
3104 }
3105
3106 QualType ValType = pointerType->getPointeeType();
3107
3108 // Strip any qualifiers off ValType.
3109 ValType = ValType.getUnqualifiedType();
3110 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3111 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
3112 !ValType->isVectorType()) {
3113 Diag(DRE->getLocStart(),
3114 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
3115 << PointerArg->getType() << PointerArg->getSourceRange();
3116 return ExprError();
3117 }
3118
3119 if (!isStore) {
3120 TheCall->setType(ValType);
3121 return TheCallResult;
3122 }
3123
3124 ExprResult ValArg = TheCall->getArg(0);
3125 InitializedEntity Entity = InitializedEntity::InitializeParameter(
3126 Context, ValType, /*consume*/ false);
3127 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
3128 if (ValArg.isInvalid())
3129 return ExprError();
3130
3131 TheCall->setArg(0, ValArg.get());
3132 TheCall->setType(Context.VoidTy);
3133 return TheCallResult;
3134}
3135
Chris Lattner6436fb62009-02-18 06:01:06 +00003136/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00003137/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00003138/// Note: It might also make sense to do the UTF-16 conversion here (would
3139/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00003140bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00003141 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00003142 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
3143
Douglas Gregorfb65e592011-07-27 05:40:30 +00003144 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00003145 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
3146 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00003147 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00003148 }
Mike Stump11289f42009-09-09 15:08:12 +00003149
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003150 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003151 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003152 unsigned NumBytes = String.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003153 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divackye6377112012-09-06 15:59:27 +00003154 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003155 UTF16 *ToPtr = &ToBuf[0];
3156
3157 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
3158 &ToPtr, ToPtr + NumBytes,
3159 strictConversion);
3160 // Check for conversion failure.
3161 if (Result != conversionOK)
3162 Diag(Arg->getLocStart(),
3163 diag::warn_cfstring_truncated) << Arg->getSourceRange();
3164 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00003165 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003166}
3167
Charles Davisc7d5c942015-09-17 20:55:33 +00003168/// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
3169/// for validity. Emit an error and return true on failure; return false
3170/// on success.
3171bool Sema::SemaBuiltinVAStartImpl(CallExpr *TheCall) {
Chris Lattner08464942007-12-28 05:29:59 +00003172 Expr *Fn = TheCall->getCallee();
3173 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00003174 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003175 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003176 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3177 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00003178 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003179 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00003180 return true;
3181 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00003182
3183 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00003184 return Diag(TheCall->getLocEnd(),
3185 diag::err_typecheck_call_too_few_args_at_least)
3186 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00003187 }
3188
John McCall29ad95b2011-08-27 01:09:30 +00003189 // Type-check the first argument normally.
3190 if (checkBuiltinArgument(*this, TheCall, 0))
3191 return true;
3192
Chris Lattnere202e6a2007-12-20 00:05:45 +00003193 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +00003194 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +00003195 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +00003196 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +00003197 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +00003198 else if (FunctionDecl *FD = getCurFunctionDecl())
3199 isVariadic = FD->isVariadic();
3200 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00003201 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +00003202
Chris Lattnere202e6a2007-12-20 00:05:45 +00003203 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +00003204 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
3205 return true;
3206 }
Mike Stump11289f42009-09-09 15:08:12 +00003207
Chris Lattner43be2e62007-12-19 23:59:04 +00003208 // Verify that the second argument to the builtin is the last argument of the
3209 // current function or method.
3210 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00003211 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00003212
Nico Weber9eea7642013-05-24 23:31:57 +00003213 // These are valid if SecondArgIsLastNamedArgument is false after the next
3214 // block.
3215 QualType Type;
3216 SourceLocation ParamLoc;
Aaron Ballman1de59c52016-04-24 13:30:21 +00003217 bool IsCRegister = false;
Nico Weber9eea7642013-05-24 23:31:57 +00003218
Anders Carlsson6a8350b2008-02-11 04:20:54 +00003219 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
3220 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +00003221 // FIXME: This isn't correct for methods (results in bogus warning).
3222 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +00003223 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +00003224 if (CurBlock)
David Majnemera3debed2016-06-24 05:33:44 +00003225 LastArg = CurBlock->TheDecl->parameters().back();
Steve Naroff439a3e42009-04-15 19:33:47 +00003226 else if (FunctionDecl *FD = getCurFunctionDecl())
David Majnemera3debed2016-06-24 05:33:44 +00003227 LastArg = FD->parameters().back();
Chris Lattner43be2e62007-12-19 23:59:04 +00003228 else
David Majnemera3debed2016-06-24 05:33:44 +00003229 LastArg = getCurMethodDecl()->parameters().back();
Chris Lattner43be2e62007-12-19 23:59:04 +00003230 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weber9eea7642013-05-24 23:31:57 +00003231
3232 Type = PV->getType();
3233 ParamLoc = PV->getLocation();
Aaron Ballman1de59c52016-04-24 13:30:21 +00003234 IsCRegister =
3235 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
Chris Lattner43be2e62007-12-19 23:59:04 +00003236 }
3237 }
Mike Stump11289f42009-09-09 15:08:12 +00003238
Chris Lattner43be2e62007-12-19 23:59:04 +00003239 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00003240 Diag(TheCall->getArg(1)->getLocStart(),
Aaron Ballman05164812016-04-18 18:10:53 +00003241 diag::warn_second_arg_of_va_start_not_last_named_param);
Aaron Ballman1de59c52016-04-24 13:30:21 +00003242 else if (IsCRegister || Type->isReferenceType() ||
3243 Type->isPromotableIntegerType() ||
3244 Type->isSpecificBuiltinType(BuiltinType::Float)) {
3245 unsigned Reason = 0;
3246 if (Type->isReferenceType()) Reason = 1;
3247 else if (IsCRegister) Reason = 2;
3248 Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
Nico Weber9eea7642013-05-24 23:31:57 +00003249 Diag(ParamLoc, diag::note_parameter_type) << Type;
3250 }
3251
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00003252 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00003253 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00003254}
Chris Lattner43be2e62007-12-19 23:59:04 +00003255
Charles Davisc7d5c942015-09-17 20:55:33 +00003256/// Check the arguments to '__builtin_va_start' for validity, and that
3257/// it was called from a function of the native ABI.
3258/// Emit an error and return true on failure; return false on success.
3259bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
3260 // On x86-64 Unix, don't allow this in Win64 ABI functions.
3261 // On x64 Windows, don't allow this in System V ABI functions.
3262 // (Yes, that means there's no corresponding way to support variadic
3263 // System V ABI functions on Windows.)
3264 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64) {
3265 unsigned OS = Context.getTargetInfo().getTriple().getOS();
3266 clang::CallingConv CC = CC_C;
3267 if (const FunctionDecl *FD = getCurFunctionDecl())
3268 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3269 if ((OS == llvm::Triple::Win32 && CC == CC_X86_64SysV) ||
3270 (OS != llvm::Triple::Win32 && CC == CC_X86_64Win64))
3271 return Diag(TheCall->getCallee()->getLocStart(),
3272 diag::err_va_start_used_in_wrong_abi_function)
3273 << (OS != llvm::Triple::Win32);
3274 }
3275 return SemaBuiltinVAStartImpl(TheCall);
3276}
3277
3278/// Check the arguments to '__builtin_ms_va_start' for validity, and that
3279/// it was called from a Win64 ABI function.
3280/// Emit an error and return true on failure; return false on success.
3281bool Sema::SemaBuiltinMSVAStart(CallExpr *TheCall) {
3282 // This only makes sense for x86-64.
3283 const llvm::Triple &TT = Context.getTargetInfo().getTriple();
3284 Expr *Callee = TheCall->getCallee();
3285 if (TT.getArch() != llvm::Triple::x86_64)
3286 return Diag(Callee->getLocStart(), diag::err_x86_builtin_32_bit_tgt);
3287 // Don't allow this in System V ABI functions.
3288 clang::CallingConv CC = CC_C;
3289 if (const FunctionDecl *FD = getCurFunctionDecl())
3290 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3291 if (CC == CC_X86_64SysV ||
3292 (TT.getOS() != llvm::Triple::Win32 && CC != CC_X86_64Win64))
3293 return Diag(Callee->getLocStart(),
3294 diag::err_ms_va_start_used_in_sysv_function);
3295 return SemaBuiltinVAStartImpl(TheCall);
3296}
3297
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00003298bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
3299 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
3300 // const char *named_addr);
3301
3302 Expr *Func = Call->getCallee();
3303
3304 if (Call->getNumArgs() < 3)
3305 return Diag(Call->getLocEnd(),
3306 diag::err_typecheck_call_too_few_args_at_least)
3307 << 0 /*function call*/ << 3 << Call->getNumArgs();
3308
3309 // Determine whether the current function is variadic or not.
3310 bool IsVariadic;
3311 if (BlockScopeInfo *CurBlock = getCurBlock())
3312 IsVariadic = CurBlock->TheDecl->isVariadic();
3313 else if (FunctionDecl *FD = getCurFunctionDecl())
3314 IsVariadic = FD->isVariadic();
3315 else if (ObjCMethodDecl *MD = getCurMethodDecl())
3316 IsVariadic = MD->isVariadic();
3317 else
3318 llvm_unreachable("unexpected statement type");
3319
3320 if (!IsVariadic) {
3321 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
3322 return true;
3323 }
3324
3325 // Type-check the first argument normally.
3326 if (checkBuiltinArgument(*this, Call, 0))
3327 return true;
3328
Benjamin Kramere0ca6e12015-03-01 18:09:50 +00003329 const struct {
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00003330 unsigned ArgNo;
3331 QualType Type;
3332 } ArgumentTypes[] = {
3333 { 1, Context.getPointerType(Context.CharTy.withConst()) },
3334 { 2, Context.getSizeType() },
3335 };
3336
3337 for (const auto &AT : ArgumentTypes) {
3338 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
3339 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
3340 continue;
3341 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
3342 << Arg->getType() << AT.Type << 1 /* different class */
3343 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
3344 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
3345 }
3346
3347 return false;
3348}
3349
Chris Lattner2da14fb2007-12-20 00:26:33 +00003350/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
3351/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00003352bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
3353 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00003354 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00003355 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00003356 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00003357 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003358 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003359 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00003360 << SourceRange(TheCall->getArg(2)->getLocStart(),
3361 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00003362
John Wiegley01296292011-04-08 18:41:53 +00003363 ExprResult OrigArg0 = TheCall->getArg(0);
3364 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00003365
Chris Lattner2da14fb2007-12-20 00:26:33 +00003366 // Do standard promotions between the two arguments, returning their common
3367 // type.
Chris Lattner08464942007-12-28 05:29:59 +00003368 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00003369 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
3370 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00003371
3372 // Make sure any conversions are pushed back into the call; this is
3373 // type safe since unordered compare builtins are declared as "_Bool
3374 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00003375 TheCall->setArg(0, OrigArg0.get());
3376 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00003377
John Wiegley01296292011-04-08 18:41:53 +00003378 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00003379 return false;
3380
Chris Lattner2da14fb2007-12-20 00:26:33 +00003381 // If the common type isn't a real floating type, then the arguments were
3382 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00003383 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00003384 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003385 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00003386 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
3387 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00003388
Chris Lattner2da14fb2007-12-20 00:26:33 +00003389 return false;
3390}
3391
Benjamin Kramer634fc102010-02-15 22:42:31 +00003392/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
3393/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00003394/// to check everything. We expect the last argument to be a floating point
3395/// value.
3396bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
3397 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00003398 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00003399 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00003400 if (TheCall->getNumArgs() > NumArgs)
3401 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00003402 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003403 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00003404 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00003405 (*(TheCall->arg_end()-1))->getLocEnd());
3406
Benjamin Kramer64aae502010-02-16 10:07:31 +00003407 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00003408
Eli Friedman7e4faac2009-08-31 20:06:00 +00003409 if (OrigArg->isTypeDependent())
3410 return false;
3411
Chris Lattner68784ef2010-05-06 05:50:07 +00003412 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00003413 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00003414 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00003415 diag::err_typecheck_call_invalid_unary_fp)
3416 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00003417
Chris Lattner68784ef2010-05-06 05:50:07 +00003418 // If this is an implicit conversion from float -> double, remove it.
3419 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
3420 Expr *CastArg = Cast->getSubExpr();
3421 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
3422 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
3423 "promotion from float to double is the only expected cast here");
Craig Topperc3ec1492014-05-26 06:22:03 +00003424 Cast->setSubExpr(nullptr);
Chris Lattner68784ef2010-05-06 05:50:07 +00003425 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner68784ef2010-05-06 05:50:07 +00003426 }
3427 }
3428
Eli Friedman7e4faac2009-08-31 20:06:00 +00003429 return false;
3430}
3431
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003432/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
3433// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00003434ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00003435 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003436 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00003437 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00003438 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3439 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003440
Nate Begemana0110022010-06-08 00:16:34 +00003441 // Determine which of the following types of shufflevector we're checking:
3442 // 1) unary, vector mask: (lhs, mask)
Craig Topperb3174a82016-05-18 04:11:25 +00003443 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
Nate Begemana0110022010-06-08 00:16:34 +00003444 QualType resType = TheCall->getArg(0)->getType();
3445 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00003446
Douglas Gregorc25f7662009-05-19 22:10:17 +00003447 if (!TheCall->getArg(0)->isTypeDependent() &&
3448 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00003449 QualType LHSType = TheCall->getArg(0)->getType();
3450 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00003451
Craig Topperbaca3892013-07-29 06:47:04 +00003452 if (!LHSType->isVectorType() || !RHSType->isVectorType())
3453 return ExprError(Diag(TheCall->getLocStart(),
3454 diag::err_shufflevector_non_vector)
3455 << SourceRange(TheCall->getArg(0)->getLocStart(),
3456 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00003457
Nate Begemana0110022010-06-08 00:16:34 +00003458 numElements = LHSType->getAs<VectorType>()->getNumElements();
3459 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00003460
Nate Begemana0110022010-06-08 00:16:34 +00003461 // Check to see if we have a call with 2 vector arguments, the unary shuffle
3462 // with mask. If so, verify that RHS is an integer vector type with the
3463 // same number of elts as lhs.
3464 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00003465 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00003466 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00003467 return ExprError(Diag(TheCall->getLocStart(),
3468 diag::err_shufflevector_incompatible_vector)
3469 << SourceRange(TheCall->getArg(1)->getLocStart(),
3470 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00003471 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00003472 return ExprError(Diag(TheCall->getLocStart(),
3473 diag::err_shufflevector_incompatible_vector)
3474 << SourceRange(TheCall->getArg(0)->getLocStart(),
3475 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00003476 } else if (numElements != numResElements) {
3477 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00003478 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00003479 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00003480 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003481 }
3482
3483 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00003484 if (TheCall->getArg(i)->isTypeDependent() ||
3485 TheCall->getArg(i)->isValueDependent())
3486 continue;
3487
Nate Begemana0110022010-06-08 00:16:34 +00003488 llvm::APSInt Result(32);
3489 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
3490 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00003491 diag::err_shufflevector_nonconstant_argument)
3492 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003493
Craig Topper50ad5b72013-08-03 17:40:38 +00003494 // Allow -1 which will be translated to undef in the IR.
3495 if (Result.isSigned() && Result.isAllOnesValue())
3496 continue;
3497
Chris Lattner7ab824e2008-08-10 02:05:13 +00003498 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003499 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00003500 diag::err_shufflevector_argument_too_large)
3501 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003502 }
3503
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003504 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003505
Chris Lattner7ab824e2008-08-10 02:05:13 +00003506 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003507 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00003508 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003509 }
3510
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003511 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
3512 TheCall->getCallee()->getLocStart(),
3513 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003514}
Chris Lattner43be2e62007-12-19 23:59:04 +00003515
Hal Finkelc4d7c822013-09-18 03:29:45 +00003516/// SemaConvertVectorExpr - Handle __builtin_convertvector
3517ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
3518 SourceLocation BuiltinLoc,
3519 SourceLocation RParenLoc) {
3520 ExprValueKind VK = VK_RValue;
3521 ExprObjectKind OK = OK_Ordinary;
3522 QualType DstTy = TInfo->getType();
3523 QualType SrcTy = E->getType();
3524
3525 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
3526 return ExprError(Diag(BuiltinLoc,
3527 diag::err_convertvector_non_vector)
3528 << E->getSourceRange());
3529 if (!DstTy->isVectorType() && !DstTy->isDependentType())
3530 return ExprError(Diag(BuiltinLoc,
3531 diag::err_convertvector_non_vector_type));
3532
3533 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
3534 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
3535 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
3536 if (SrcElts != DstElts)
3537 return ExprError(Diag(BuiltinLoc,
3538 diag::err_convertvector_incompatible_vector)
3539 << E->getSourceRange());
3540 }
3541
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003542 return new (Context)
3543 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00003544}
3545
Daniel Dunbarb7257262008-07-21 22:59:13 +00003546/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
3547// This is declared to take (const void*, ...) and can take two
3548// optional constant int args.
3549bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00003550 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00003551
Chris Lattner3b054132008-11-19 05:08:23 +00003552 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003553 return Diag(TheCall->getLocEnd(),
3554 diag::err_typecheck_call_too_many_args_at_most)
3555 << 0 /*function call*/ << 3 << NumArgs
3556 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00003557
3558 // Argument 0 is checked for us and the remaining arguments must be
3559 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00003560 for (unsigned i = 1; i != NumArgs; ++i)
3561 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00003562 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003563
Warren Hunt20e4a5d2014-02-21 23:08:53 +00003564 return false;
3565}
3566
Hal Finkelf0417332014-07-17 14:25:55 +00003567/// SemaBuiltinAssume - Handle __assume (MS Extension).
3568// __assume does not evaluate its arguments, and should warn if its argument
3569// has side effects.
3570bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
3571 Expr *Arg = TheCall->getArg(0);
3572 if (Arg->isInstantiationDependent()) return false;
3573
3574 if (Arg->HasSideEffects(Context))
David Majnemer51236642015-02-26 00:57:33 +00003575 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00003576 << Arg->getSourceRange()
3577 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
3578
3579 return false;
3580}
3581
3582/// Handle __builtin_assume_aligned. This is declared
3583/// as (const void*, size_t, ...) and can take one optional constant int arg.
3584bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
3585 unsigned NumArgs = TheCall->getNumArgs();
3586
3587 if (NumArgs > 3)
3588 return Diag(TheCall->getLocEnd(),
3589 diag::err_typecheck_call_too_many_args_at_most)
3590 << 0 /*function call*/ << 3 << NumArgs
3591 << TheCall->getSourceRange();
3592
3593 // The alignment must be a constant integer.
3594 Expr *Arg = TheCall->getArg(1);
3595
3596 // We can't check the value of a dependent argument.
3597 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
3598 llvm::APSInt Result;
3599 if (SemaBuiltinConstantArg(TheCall, 1, Result))
3600 return true;
3601
3602 if (!Result.isPowerOf2())
3603 return Diag(TheCall->getLocStart(),
3604 diag::err_alignment_not_power_of_two)
3605 << Arg->getSourceRange();
3606 }
3607
3608 if (NumArgs > 2) {
3609 ExprResult Arg(TheCall->getArg(2));
3610 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3611 Context.getSizeType(), false);
3612 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3613 if (Arg.isInvalid()) return true;
3614 TheCall->setArg(2, Arg.get());
3615 }
Hal Finkelf0417332014-07-17 14:25:55 +00003616
3617 return false;
3618}
3619
Eric Christopher8d0c6212010-04-17 02:26:23 +00003620/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
3621/// TheCall is a constant expression.
3622bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
3623 llvm::APSInt &Result) {
3624 Expr *Arg = TheCall->getArg(ArgNum);
3625 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3626 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3627
3628 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
3629
3630 if (!Arg->isIntegerConstantExpr(Result, Context))
3631 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00003632 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00003633
Chris Lattnerd545ad12009-09-23 06:06:36 +00003634 return false;
3635}
3636
Richard Sandiford28940af2014-04-16 08:47:51 +00003637/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
3638/// TheCall is a constant expression in the range [Low, High].
3639bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
3640 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00003641 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00003642
3643 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00003644 Expr *Arg = TheCall->getArg(ArgNum);
3645 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00003646 return false;
3647
Eric Christopher8d0c6212010-04-17 02:26:23 +00003648 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00003649 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00003650 return true;
3651
Richard Sandiford28940af2014-04-16 08:47:51 +00003652 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00003653 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00003654 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00003655
3656 return false;
3657}
3658
Luke Cheeseman59b2d832015-06-15 17:51:01 +00003659/// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
3660/// TheCall is an ARM/AArch64 special register string literal.
3661bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
3662 int ArgNum, unsigned ExpectedFieldNum,
3663 bool AllowName) {
3664 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
3665 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
3666 BuiltinID == ARM::BI__builtin_arm_rsr ||
3667 BuiltinID == ARM::BI__builtin_arm_rsrp ||
3668 BuiltinID == ARM::BI__builtin_arm_wsr ||
3669 BuiltinID == ARM::BI__builtin_arm_wsrp;
3670 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
3671 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
3672 BuiltinID == AArch64::BI__builtin_arm_rsr ||
3673 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
3674 BuiltinID == AArch64::BI__builtin_arm_wsr ||
3675 BuiltinID == AArch64::BI__builtin_arm_wsrp;
3676 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
3677
3678 // We can't check the value of a dependent argument.
3679 Expr *Arg = TheCall->getArg(ArgNum);
3680 if (Arg->isTypeDependent() || Arg->isValueDependent())
3681 return false;
3682
3683 // Check if the argument is a string literal.
3684 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3685 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
3686 << Arg->getSourceRange();
3687
3688 // Check the type of special register given.
3689 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3690 SmallVector<StringRef, 6> Fields;
3691 Reg.split(Fields, ":");
3692
3693 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
3694 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
3695 << Arg->getSourceRange();
3696
3697 // If the string is the name of a register then we cannot check that it is
3698 // valid here but if the string is of one the forms described in ACLE then we
3699 // can check that the supplied fields are integers and within the valid
3700 // ranges.
3701 if (Fields.size() > 1) {
3702 bool FiveFields = Fields.size() == 5;
3703
3704 bool ValidString = true;
3705 if (IsARMBuiltin) {
3706 ValidString &= Fields[0].startswith_lower("cp") ||
3707 Fields[0].startswith_lower("p");
3708 if (ValidString)
3709 Fields[0] =
3710 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
3711
3712 ValidString &= Fields[2].startswith_lower("c");
3713 if (ValidString)
3714 Fields[2] = Fields[2].drop_front(1);
3715
3716 if (FiveFields) {
3717 ValidString &= Fields[3].startswith_lower("c");
3718 if (ValidString)
3719 Fields[3] = Fields[3].drop_front(1);
3720 }
3721 }
3722
3723 SmallVector<int, 5> Ranges;
3724 if (FiveFields)
3725 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 7, 15, 15});
3726 else
3727 Ranges.append({15, 7, 15});
3728
3729 for (unsigned i=0; i<Fields.size(); ++i) {
3730 int IntField;
3731 ValidString &= !Fields[i].getAsInteger(10, IntField);
3732 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
3733 }
3734
3735 if (!ValidString)
3736 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
3737 << Arg->getSourceRange();
3738
3739 } else if (IsAArch64Builtin && Fields.size() == 1) {
3740 // If the register name is one of those that appear in the condition below
3741 // and the special register builtin being used is one of the write builtins,
3742 // then we require that the argument provided for writing to the register
3743 // is an integer constant expression. This is because it will be lowered to
3744 // an MSR (immediate) instruction, so we need to know the immediate at
3745 // compile time.
3746 if (TheCall->getNumArgs() != 2)
3747 return false;
3748
3749 std::string RegLower = Reg.lower();
3750 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
3751 RegLower != "pan" && RegLower != "uao")
3752 return false;
3753
3754 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
3755 }
3756
3757 return false;
3758}
3759
Eli Friedmanc97d0142009-05-03 06:04:26 +00003760/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Joerg Sonnenberger27173282015-03-11 23:46:32 +00003761/// This checks that the target supports __builtin_longjmp and
3762/// that val is a constant 1.
Eli Friedmaneed8ad22009-05-03 04:46:36 +00003763bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Joerg Sonnenberger27173282015-03-11 23:46:32 +00003764 if (!Context.getTargetInfo().hasSjLjLowering())
3765 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
3766 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
3767
Eli Friedmaneed8ad22009-05-03 04:46:36 +00003768 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00003769 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00003770
Eric Christopher8d0c6212010-04-17 02:26:23 +00003771 // TODO: This is less than ideal. Overload this to take a value.
3772 if (SemaBuiltinConstantArg(TheCall, 1, Result))
3773 return true;
3774
3775 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00003776 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
3777 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
3778
3779 return false;
3780}
3781
Joerg Sonnenberger27173282015-03-11 23:46:32 +00003782/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
3783/// This checks that the target supports __builtin_setjmp.
3784bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
3785 if (!Context.getTargetInfo().hasSjLjLowering())
3786 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
3787 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
3788 return false;
3789}
3790
Richard Smithd7293d72013-08-05 18:49:43 +00003791namespace {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003792class UncoveredArgHandler {
3793 enum { Unknown = -1, AllCovered = -2 };
3794 signed FirstUncoveredArg;
3795 SmallVector<const Expr *, 4> DiagnosticExprs;
3796
3797public:
3798 UncoveredArgHandler() : FirstUncoveredArg(Unknown) { }
3799
3800 bool hasUncoveredArg() const {
3801 return (FirstUncoveredArg >= 0);
3802 }
3803
3804 unsigned getUncoveredArg() const {
3805 assert(hasUncoveredArg() && "no uncovered argument");
3806 return FirstUncoveredArg;
3807 }
3808
3809 void setAllCovered() {
3810 // A string has been found with all arguments covered, so clear out
3811 // the diagnostics.
3812 DiagnosticExprs.clear();
3813 FirstUncoveredArg = AllCovered;
3814 }
3815
3816 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
3817 assert(NewFirstUncoveredArg >= 0 && "Outside range");
3818
3819 // Don't update if a previous string covers all arguments.
3820 if (FirstUncoveredArg == AllCovered)
3821 return;
3822
3823 // UncoveredArgHandler tracks the highest uncovered argument index
3824 // and with it all the strings that match this index.
3825 if (NewFirstUncoveredArg == FirstUncoveredArg)
3826 DiagnosticExprs.push_back(StrExpr);
3827 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
3828 DiagnosticExprs.clear();
3829 DiagnosticExprs.push_back(StrExpr);
3830 FirstUncoveredArg = NewFirstUncoveredArg;
3831 }
3832 }
3833
3834 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
3835};
3836
Richard Smithd7293d72013-08-05 18:49:43 +00003837enum StringLiteralCheckType {
3838 SLCT_NotALiteral,
3839 SLCT_UncheckedLiteral,
3840 SLCT_CheckedLiteral
3841};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00003842} // end anonymous namespace
Richard Smithd7293d72013-08-05 18:49:43 +00003843
Stephen Hines6a17e512016-09-14 20:20:14 +00003844static void CheckFormatString(Sema &S, const StringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00003845 const Expr *OrigFormatExpr,
3846 ArrayRef<const Expr *> Args,
3847 bool HasVAListArg, unsigned format_idx,
3848 unsigned firstDataArg,
3849 Sema::FormatStringType Type,
3850 bool inFunctionCall,
3851 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003852 llvm::SmallBitVector &CheckedVarArgs,
3853 UncoveredArgHandler &UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00003854
Richard Smith55ce3522012-06-25 20:30:08 +00003855// Determine if an expression is a string literal or constant string.
3856// If this function returns false on the arguments to a function expecting a
3857// format string, we will usually need to emit a warning.
3858// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00003859static StringLiteralCheckType
3860checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
3861 bool HasVAListArg, unsigned format_idx,
3862 unsigned firstDataArg, Sema::FormatStringType Type,
3863 Sema::VariadicCallType CallType, bool InFunctionCall,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003864 llvm::SmallBitVector &CheckedVarArgs,
Stephen Hines6a17e512016-09-14 20:20:14 +00003865 UncoveredArgHandler &UncoveredArg) {
Ted Kremenek808829352010-09-09 03:51:39 +00003866 tryAgain:
Douglas Gregorc25f7662009-05-19 22:10:17 +00003867 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00003868 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003869
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003870 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00003871
Richard Smithd7293d72013-08-05 18:49:43 +00003872 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00003873 // Technically -Wformat-nonliteral does not warn about this case.
3874 // The behavior of printf and friends in this case is implementation
3875 // dependent. Ideally if the format string cannot be null then
3876 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00003877 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00003878
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003879 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00003880 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003881 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00003882 // The expression is a literal if both sub-expressions were, and it was
3883 // completely checked only if both sub-expressions were checked.
3884 const AbstractConditionalOperator *C =
3885 cast<AbstractConditionalOperator>(E);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003886
3887 // Determine whether it is necessary to check both sub-expressions, for
3888 // example, because the condition expression is a constant that can be
3889 // evaluated at compile time.
3890 bool CheckLeft = true, CheckRight = true;
3891
3892 bool Cond;
3893 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
3894 if (Cond)
3895 CheckRight = false;
3896 else
3897 CheckLeft = false;
3898 }
3899
3900 StringLiteralCheckType Left;
3901 if (!CheckLeft)
3902 Left = SLCT_UncheckedLiteral;
3903 else {
3904 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
3905 HasVAListArg, format_idx, firstDataArg,
3906 Type, CallType, InFunctionCall,
Stephen Hines6a17e512016-09-14 20:20:14 +00003907 CheckedVarArgs, UncoveredArg);
3908 if (Left == SLCT_NotALiteral || !CheckRight)
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003909 return Left;
3910 }
3911
Richard Smith55ce3522012-06-25 20:30:08 +00003912 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00003913 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003914 HasVAListArg, format_idx, firstDataArg,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003915 Type, CallType, InFunctionCall, CheckedVarArgs,
Stephen Hines6a17e512016-09-14 20:20:14 +00003916 UncoveredArg);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003917
3918 return (CheckLeft && Left < Right) ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003919 }
3920
3921 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00003922 E = cast<ImplicitCastExpr>(E)->getSubExpr();
3923 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003924 }
3925
John McCallc07a0c72011-02-17 10:25:35 +00003926 case Stmt::OpaqueValueExprClass:
3927 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
3928 E = src;
3929 goto tryAgain;
3930 }
Richard Smith55ce3522012-06-25 20:30:08 +00003931 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00003932
Ted Kremeneka8890832011-02-24 23:03:04 +00003933 case Stmt::PredefinedExprClass:
3934 // While __func__, etc., are technically not string literals, they
3935 // cannot contain format specifiers and thus are not a security
3936 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00003937 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00003938
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003939 case Stmt::DeclRefExprClass: {
3940 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00003941
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003942 // As an exception, do not flag errors for variables binding to
3943 // const string literals.
3944 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
3945 bool isConstant = false;
3946 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003947
Richard Smithd7293d72013-08-05 18:49:43 +00003948 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
3949 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00003950 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00003951 isConstant = T.isConstant(S.Context) &&
3952 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00003953 } else if (T->isObjCObjectPointerType()) {
3954 // In ObjC, there is usually no "const ObjectPointer" type,
3955 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00003956 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003957 }
Mike Stump11289f42009-09-09 15:08:12 +00003958
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003959 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00003960 if (const Expr *Init = VD->getAnyInitializer()) {
3961 // Look through initializers like const char c[] = { "foo" }
3962 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
3963 if (InitList->isStringLiteralInit())
3964 Init = InitList->getInit(0)->IgnoreParenImpCasts();
3965 }
Richard Smithd7293d72013-08-05 18:49:43 +00003966 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003967 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003968 firstDataArg, Type, CallType,
Stephen Hines6a17e512016-09-14 20:20:14 +00003969 /*InFunctionCall*/false, CheckedVarArgs,
3970 UncoveredArg);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00003971 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003972 }
Mike Stump11289f42009-09-09 15:08:12 +00003973
Anders Carlssonb012ca92009-06-28 19:55:58 +00003974 // For vprintf* functions (i.e., HasVAListArg==true), we add a
3975 // special check to see if the format string is a function parameter
3976 // of the function calling the printf function. If the function
3977 // has an attribute indicating it is a printf-like function, then we
3978 // should suppress warnings concerning non-literals being used in a call
3979 // to a vprintf function. For example:
3980 //
3981 // void
3982 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
3983 // va_list ap;
3984 // va_start(ap, fmt);
3985 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
3986 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00003987 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00003988 if (HasVAListArg) {
3989 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
3990 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
3991 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00003992 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00003993 // adjust for implicit parameter
3994 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
3995 if (MD->isInstance())
3996 ++PVIndex;
3997 // We also check if the formats are compatible.
3998 // We can't pass a 'scanf' string to a 'printf' function.
3999 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00004000 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00004001 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004002 }
4003 }
4004 }
4005 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004006 }
Mike Stump11289f42009-09-09 15:08:12 +00004007
Richard Smith55ce3522012-06-25 20:30:08 +00004008 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004009 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004010
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00004011 case Stmt::CallExprClass:
4012 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00004013 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00004014 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
4015 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
4016 unsigned ArgIndex = FA->getFormatIdx();
4017 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4018 if (MD->isInstance())
4019 --ArgIndex;
4020 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00004021
Richard Smithd7293d72013-08-05 18:49:43 +00004022 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004023 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00004024 Type, CallType, InFunctionCall,
Stephen Hines6a17e512016-09-14 20:20:14 +00004025 CheckedVarArgs, UncoveredArg);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004026 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4027 unsigned BuiltinID = FD->getBuiltinID();
4028 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
4029 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
4030 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00004031 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004032 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004033 firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004034 InFunctionCall, CheckedVarArgs,
Stephen Hines6a17e512016-09-14 20:20:14 +00004035 UncoveredArg);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004036 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00004037 }
4038 }
Mike Stump11289f42009-09-09 15:08:12 +00004039
Richard Smith55ce3522012-06-25 20:30:08 +00004040 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00004041 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004042 case Stmt::ObjCStringLiteralClass:
4043 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00004044 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004045
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004046 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004047 StrE = ObjCFExpr->getString();
4048 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004049 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004050
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004051 if (StrE) {
Stephen Hines6a17e512016-09-14 20:20:14 +00004052 CheckFormatString(S, StrE, E, Args, HasVAListArg, format_idx,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004053 firstDataArg, Type, InFunctionCall, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004054 CheckedVarArgs, UncoveredArg);
Richard Smith55ce3522012-06-25 20:30:08 +00004055 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004056 }
Mike Stump11289f42009-09-09 15:08:12 +00004057
Richard Smith55ce3522012-06-25 20:30:08 +00004058 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004059 }
Mike Stump11289f42009-09-09 15:08:12 +00004060
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004061 default:
Richard Smith55ce3522012-06-25 20:30:08 +00004062 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004063 }
4064}
4065
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004066Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00004067 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004068 .Case("scanf", FST_Scanf)
4069 .Cases("printf", "printf0", FST_Printf)
4070 .Cases("NSString", "CFString", FST_NSString)
4071 .Case("strftime", FST_Strftime)
4072 .Case("strfmon", FST_Strfmon)
4073 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
Dimitry Andric6b5ed342015-02-19 22:32:33 +00004074 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00004075 .Case("os_trace", FST_OSTrace)
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004076 .Default(FST_Unknown);
4077}
4078
Jordan Rose3e0ec582012-07-19 18:10:23 +00004079/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00004080/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00004081/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004082bool Sema::CheckFormatArguments(const FormatAttr *Format,
4083 ArrayRef<const Expr *> Args,
4084 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004085 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00004086 SourceLocation Loc, SourceRange Range,
4087 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00004088 FormatStringInfo FSI;
4089 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004090 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00004091 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00004092 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00004093 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004094}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00004095
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004096bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004097 bool HasVAListArg, unsigned format_idx,
4098 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004099 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00004100 SourceLocation Loc, SourceRange Range,
4101 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00004102 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004103 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004104 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00004105 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00004106 }
Mike Stump11289f42009-09-09 15:08:12 +00004107
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004108 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00004109
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004110 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00004111 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00004112 // Dynamically generated format strings are difficult to
4113 // automatically vet at compile time. Requiring that format strings
4114 // are string literals: (1) permits the checking of format strings by
4115 // the compiler and thereby (2) can practically remove the source of
4116 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00004117
Mike Stump11289f42009-09-09 15:08:12 +00004118 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00004119 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00004120 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00004121 // the same format string checking logic for both ObjC and C strings.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004122 UncoveredArgHandler UncoveredArg;
Richard Smith55ce3522012-06-25 20:30:08 +00004123 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00004124 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
4125 format_idx, firstDataArg, Type, CallType,
Stephen Hines6a17e512016-09-14 20:20:14 +00004126 /*IsFunctionCall*/true, CheckedVarArgs,
4127 UncoveredArg);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004128
4129 // Generate a diagnostic where an uncovered argument is detected.
4130 if (UncoveredArg.hasUncoveredArg()) {
4131 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
4132 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
4133 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
4134 }
4135
Richard Smith55ce3522012-06-25 20:30:08 +00004136 if (CT != SLCT_NotALiteral)
4137 // Literal format string found, check done!
4138 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00004139
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00004140 // Strftime is particular as it always uses a single 'time' argument,
4141 // so it is safe to pass a non-literal string.
4142 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00004143 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00004144
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00004145 // Do not emit diag when the string param is a macro expansion and the
4146 // format is either NSString or CFString. This is a hack to prevent
4147 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
4148 // which are usually used in place of NS and CF string literals.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004149 SourceLocation FormatLoc = Args[format_idx]->getLocStart();
4150 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
Richard Smith55ce3522012-06-25 20:30:08 +00004151 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00004152
Chris Lattnercc5d1c22009-04-29 04:59:47 +00004153 // If there are no arguments specified, warn with -Wformat-security, otherwise
4154 // warn only with -Wformat-nonliteral.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004155 if (Args.size() == firstDataArg) {
Bob Wilson57819fc2016-03-15 20:56:38 +00004156 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
4157 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004158 switch (Type) {
4159 default:
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004160 break;
4161 case FST_Kprintf:
4162 case FST_FreeBSDKPrintf:
4163 case FST_Printf:
Bob Wilson57819fc2016-03-15 20:56:38 +00004164 Diag(FormatLoc, diag::note_format_security_fixit)
4165 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004166 break;
4167 case FST_NSString:
Bob Wilson57819fc2016-03-15 20:56:38 +00004168 Diag(FormatLoc, diag::note_format_security_fixit)
4169 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004170 break;
4171 }
4172 } else {
4173 Diag(FormatLoc, diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00004174 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004175 }
Richard Smith55ce3522012-06-25 20:30:08 +00004176 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004177}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00004178
Ted Kremenekab278de2010-01-28 23:39:18 +00004179namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00004180class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
4181protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00004182 Sema &S;
Stephen Hines6a17e512016-09-14 20:20:14 +00004183 const StringLiteral *FExpr;
Ted Kremenekab278de2010-01-28 23:39:18 +00004184 const Expr *OrigFormatExpr;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00004185 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00004186 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00004187 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00004188 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004189 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00004190 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00004191 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00004192 bool usesPositionalArgs;
4193 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00004194 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00004195 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00004196 llvm::SmallBitVector &CheckedVarArgs;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004197 UncoveredArgHandler &UncoveredArg;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004198
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004199public:
Stephen Hines6a17e512016-09-14 20:20:14 +00004200 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek4d745dd2010-03-25 03:59:12 +00004201 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004202 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004203 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004204 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00004205 Sema::VariadicCallType callType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004206 llvm::SmallBitVector &CheckedVarArgs,
4207 UncoveredArgHandler &UncoveredArg)
Ted Kremenekab278de2010-01-28 23:39:18 +00004208 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004209 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
4210 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004211 Args(Args), FormatIdx(formatIdx),
Richard Trieu03cf7b72011-10-28 00:41:25 +00004212 usesPositionalArgs(false), atFirstArg(true),
Richard Smithd7293d72013-08-05 18:49:43 +00004213 inFunctionCall(inFunctionCall), CallType(callType),
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004214 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
Richard Smithd7293d72013-08-05 18:49:43 +00004215 CoveredArgs.resize(numDataArgs);
4216 CoveredArgs.reset();
4217 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004218
Ted Kremenek019d2242010-01-29 01:50:07 +00004219 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004220
Ted Kremenek02087932010-07-16 02:11:22 +00004221 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004222 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004223
Jordan Rose92303592012-09-08 04:00:03 +00004224 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00004225 const analyze_format_string::FormatSpecifier &FS,
4226 const analyze_format_string::ConversionSpecifier &CS,
4227 const char *startSpecifier, unsigned specifierLen,
4228 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00004229
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004230 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00004231 const analyze_format_string::FormatSpecifier &FS,
4232 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004233
4234 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00004235 const analyze_format_string::ConversionSpecifier &CS,
4236 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004237
Craig Toppere14c0f82014-03-12 04:55:44 +00004238 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00004239
Craig Toppere14c0f82014-03-12 04:55:44 +00004240 void HandleInvalidPosition(const char *startSpecifier,
4241 unsigned specifierLen,
4242 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00004243
Craig Toppere14c0f82014-03-12 04:55:44 +00004244 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00004245
Craig Toppere14c0f82014-03-12 04:55:44 +00004246 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004247
Richard Trieu03cf7b72011-10-28 00:41:25 +00004248 template <typename Range>
Benjamin Kramer7320b992016-06-15 14:20:56 +00004249 static void
4250 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
4251 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
4252 bool IsStringLocation, Range StringRange,
4253 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00004254
Ted Kremenek02087932010-07-16 02:11:22 +00004255protected:
Ted Kremenekce815422010-07-19 21:25:57 +00004256 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
4257 const char *startSpec,
4258 unsigned specifierLen,
4259 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00004260
4261 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
4262 const char *startSpec,
4263 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00004264
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004265 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00004266 CharSourceRange getSpecifierRange(const char *startSpecifier,
4267 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00004268 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004269
Ted Kremenek5739de72010-01-29 01:06:55 +00004270 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004271
4272 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
4273 const analyze_format_string::ConversionSpecifier &CS,
4274 const char *startSpecifier, unsigned specifierLen,
4275 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00004276
4277 template <typename Range>
4278 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
4279 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00004280 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00004281};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004282} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00004283
Ted Kremenek02087932010-07-16 02:11:22 +00004284SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00004285 return OrigFormatExpr->getSourceRange();
4286}
4287
Ted Kremenek02087932010-07-16 02:11:22 +00004288CharSourceRange CheckFormatHandler::
4289getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00004290 SourceLocation Start = getLocationOfByte(startSpecifier);
4291 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
4292
4293 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00004294 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00004295
4296 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004297}
4298
Ted Kremenek02087932010-07-16 02:11:22 +00004299SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Stephen Hines6a17e512016-09-14 20:20:14 +00004300 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremenekab278de2010-01-28 23:39:18 +00004301}
4302
Ted Kremenek02087932010-07-16 02:11:22 +00004303void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
4304 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00004305 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
4306 getLocationOfByte(startSpecifier),
4307 /*IsStringLocation*/true,
4308 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00004309}
4310
Jordan Rose92303592012-09-08 04:00:03 +00004311void CheckFormatHandler::HandleInvalidLengthModifier(
4312 const analyze_format_string::FormatSpecifier &FS,
4313 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00004314 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00004315 using namespace analyze_format_string;
4316
4317 const LengthModifier &LM = FS.getLengthModifier();
4318 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
4319
4320 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00004321 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00004322 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00004323 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00004324 getLocationOfByte(LM.getStart()),
4325 /*IsStringLocation*/true,
4326 getSpecifierRange(startSpecifier, specifierLen));
4327
4328 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
4329 << FixedLM->toString()
4330 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
4331
4332 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00004333 FixItHint Hint;
4334 if (DiagID == diag::warn_format_nonsensical_length)
4335 Hint = FixItHint::CreateRemoval(LMRange);
4336
4337 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00004338 getLocationOfByte(LM.getStart()),
4339 /*IsStringLocation*/true,
4340 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00004341 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00004342 }
4343}
4344
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004345void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00004346 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004347 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00004348 using namespace analyze_format_string;
4349
4350 const LengthModifier &LM = FS.getLengthModifier();
4351 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
4352
4353 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00004354 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00004355 if (FixedLM) {
4356 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4357 << LM.toString() << 0,
4358 getLocationOfByte(LM.getStart()),
4359 /*IsStringLocation*/true,
4360 getSpecifierRange(startSpecifier, specifierLen));
4361
4362 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
4363 << FixedLM->toString()
4364 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
4365
4366 } else {
4367 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4368 << LM.toString() << 0,
4369 getLocationOfByte(LM.getStart()),
4370 /*IsStringLocation*/true,
4371 getSpecifierRange(startSpecifier, specifierLen));
4372 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004373}
4374
4375void CheckFormatHandler::HandleNonStandardConversionSpecifier(
4376 const analyze_format_string::ConversionSpecifier &CS,
4377 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00004378 using namespace analyze_format_string;
4379
4380 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00004381 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00004382 if (FixedCS) {
4383 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4384 << CS.toString() << /*conversion specifier*/1,
4385 getLocationOfByte(CS.getStart()),
4386 /*IsStringLocation*/true,
4387 getSpecifierRange(startSpecifier, specifierLen));
4388
4389 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
4390 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
4391 << FixedCS->toString()
4392 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
4393 } else {
4394 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4395 << CS.toString() << /*conversion specifier*/1,
4396 getLocationOfByte(CS.getStart()),
4397 /*IsStringLocation*/true,
4398 getSpecifierRange(startSpecifier, specifierLen));
4399 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004400}
4401
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00004402void CheckFormatHandler::HandlePosition(const char *startPos,
4403 unsigned posLen) {
4404 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
4405 getLocationOfByte(startPos),
4406 /*IsStringLocation*/true,
4407 getSpecifierRange(startPos, posLen));
4408}
4409
Ted Kremenekd1668192010-02-27 01:41:03 +00004410void
Ted Kremenek02087932010-07-16 02:11:22 +00004411CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
4412 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004413 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
4414 << (unsigned) p,
4415 getLocationOfByte(startPos), /*IsStringLocation*/true,
4416 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00004417}
4418
Ted Kremenek02087932010-07-16 02:11:22 +00004419void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00004420 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004421 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
4422 getLocationOfByte(startPos),
4423 /*IsStringLocation*/true,
4424 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00004425}
4426
Ted Kremenek02087932010-07-16 02:11:22 +00004427void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004428 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00004429 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00004430 EmitFormatDiagnostic(
4431 S.PDiag(diag::warn_printf_format_string_contains_null_char),
4432 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
4433 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00004434 }
Ted Kremenek02087932010-07-16 02:11:22 +00004435}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004436
Jordan Rose58bbe422012-07-19 18:10:08 +00004437// Note that this may return NULL if there was an error parsing or building
4438// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00004439const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004440 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00004441}
4442
4443void CheckFormatHandler::DoneProcessing() {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004444 // Does the number of data arguments exceed the number of
4445 // format conversions in the format string?
Ted Kremenek02087932010-07-16 02:11:22 +00004446 if (!HasVAListArg) {
4447 // Find any arguments that weren't covered.
4448 CoveredArgs.flip();
4449 signed notCoveredArg = CoveredArgs.find_first();
4450 if (notCoveredArg >= 0) {
4451 assert((unsigned)notCoveredArg < NumDataArgs);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004452 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
4453 } else {
4454 UncoveredArg.setAllCovered();
Ted Kremenek02087932010-07-16 02:11:22 +00004455 }
4456 }
4457}
4458
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004459void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
4460 const Expr *ArgExpr) {
4461 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
4462 "Invalid state");
4463
4464 if (!ArgExpr)
4465 return;
4466
4467 SourceLocation Loc = ArgExpr->getLocStart();
4468
4469 if (S.getSourceManager().isInSystemMacro(Loc))
4470 return;
4471
4472 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
4473 for (auto E : DiagnosticExprs)
4474 PDiag << E->getSourceRange();
4475
4476 CheckFormatHandler::EmitFormatDiagnostic(
4477 S, IsFunctionCall, DiagnosticExprs[0],
4478 PDiag, Loc, /*IsStringLocation*/false,
4479 DiagnosticExprs[0]->getSourceRange());
4480}
4481
Ted Kremenekce815422010-07-19 21:25:57 +00004482bool
4483CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
4484 SourceLocation Loc,
4485 const char *startSpec,
4486 unsigned specifierLen,
4487 const char *csStart,
4488 unsigned csLen) {
Ted Kremenekce815422010-07-19 21:25:57 +00004489 bool keepGoing = true;
4490 if (argIndex < NumDataArgs) {
4491 // Consider the argument coverered, even though the specifier doesn't
4492 // make sense.
4493 CoveredArgs.set(argIndex);
4494 }
4495 else {
4496 // If argIndex exceeds the number of data arguments we
4497 // don't issue a warning because that is just a cascade of warnings (and
4498 // they may have intended '%%' anyway). We don't want to continue processing
4499 // the format string after this point, however, as we will like just get
4500 // gibberish when trying to match arguments.
4501 keepGoing = false;
4502 }
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00004503
4504 StringRef Specifier(csStart, csLen);
4505
4506 // If the specifier in non-printable, it could be the first byte of a UTF-8
4507 // sequence. In that case, print the UTF-8 code point. If not, print the byte
4508 // hex value.
4509 std::string CodePointStr;
4510 if (!llvm::sys::locale::isPrint(*csStart)) {
4511 UTF32 CodePoint;
4512 const UTF8 **B = reinterpret_cast<const UTF8 **>(&csStart);
4513 const UTF8 *E =
4514 reinterpret_cast<const UTF8 *>(csStart + csLen);
4515 ConversionResult Result =
4516 llvm::convertUTF8Sequence(B, E, &CodePoint, strictConversion);
4517
4518 if (Result != conversionOK) {
4519 unsigned char FirstChar = *csStart;
4520 CodePoint = (UTF32)FirstChar;
4521 }
4522
4523 llvm::raw_string_ostream OS(CodePointStr);
4524 if (CodePoint < 256)
4525 OS << "\\x" << llvm::format("%02x", CodePoint);
4526 else if (CodePoint <= 0xFFFF)
4527 OS << "\\u" << llvm::format("%04x", CodePoint);
4528 else
4529 OS << "\\U" << llvm::format("%08x", CodePoint);
4530 OS.flush();
4531 Specifier = CodePointStr;
4532 }
4533
4534 EmitFormatDiagnostic(
4535 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
4536 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
4537
Ted Kremenekce815422010-07-19 21:25:57 +00004538 return keepGoing;
4539}
4540
Richard Trieu03cf7b72011-10-28 00:41:25 +00004541void
4542CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
4543 const char *startSpec,
4544 unsigned specifierLen) {
4545 EmitFormatDiagnostic(
4546 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
4547 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
4548}
4549
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004550bool
4551CheckFormatHandler::CheckNumArgs(
4552 const analyze_format_string::FormatSpecifier &FS,
4553 const analyze_format_string::ConversionSpecifier &CS,
4554 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
4555
4556 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004557 PartialDiagnostic PDiag = FS.usesPositionalArg()
4558 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
4559 << (argIndex+1) << NumDataArgs)
4560 : S.PDiag(diag::warn_printf_insufficient_data_args);
4561 EmitFormatDiagnostic(
4562 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
4563 getSpecifierRange(startSpecifier, specifierLen));
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004564
4565 // Since more arguments than conversion tokens are given, by extension
4566 // all arguments are covered, so mark this as so.
4567 UncoveredArg.setAllCovered();
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004568 return false;
4569 }
4570 return true;
4571}
4572
Richard Trieu03cf7b72011-10-28 00:41:25 +00004573template<typename Range>
4574void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
4575 SourceLocation Loc,
4576 bool IsStringLocation,
4577 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00004578 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004579 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00004580 Loc, IsStringLocation, StringRange, FixIt);
4581}
4582
4583/// \brief If the format string is not within the funcion call, emit a note
4584/// so that the function call and string are in diagnostic messages.
4585///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00004586/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00004587/// call and only one diagnostic message will be produced. Otherwise, an
4588/// extra note will be emitted pointing to location of the format string.
4589///
4590/// \param ArgumentExpr the expression that is passed as the format string
4591/// argument in the function call. Used for getting locations when two
4592/// diagnostics are emitted.
4593///
4594/// \param PDiag the callee should already have provided any strings for the
4595/// diagnostic message. This function only adds locations and fixits
4596/// to diagnostics.
4597///
4598/// \param Loc primary location for diagnostic. If two diagnostics are
4599/// required, one will be at Loc and a new SourceLocation will be created for
4600/// the other one.
4601///
4602/// \param IsStringLocation if true, Loc points to the format string should be
4603/// used for the note. Otherwise, Loc points to the argument list and will
4604/// be used with PDiag.
4605///
4606/// \param StringRange some or all of the string to highlight. This is
4607/// templated so it can accept either a CharSourceRange or a SourceRange.
4608///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00004609/// \param FixIt optional fix it hint for the format string.
Benjamin Kramer7320b992016-06-15 14:20:56 +00004610template <typename Range>
4611void CheckFormatHandler::EmitFormatDiagnostic(
4612 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
4613 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
4614 Range StringRange, ArrayRef<FixItHint> FixIt) {
Jordan Roseaee34382012-09-05 22:56:26 +00004615 if (InFunctionCall) {
4616 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
4617 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00004618 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00004619 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004620 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
4621 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00004622
4623 const Sema::SemaDiagnosticBuilder &Note =
4624 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
4625 diag::note_format_string_defined);
4626
4627 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00004628 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00004629 }
4630}
4631
Ted Kremenek02087932010-07-16 02:11:22 +00004632//===--- CHECK: Printf format string checking ------------------------------===//
4633
4634namespace {
4635class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004636 bool ObjCContext;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004637
Ted Kremenek02087932010-07-16 02:11:22 +00004638public:
Stephen Hines6a17e512016-09-14 20:20:14 +00004639 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek02087932010-07-16 02:11:22 +00004640 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004641 unsigned numDataArgs, bool isObjC,
Ted Kremenek02087932010-07-16 02:11:22 +00004642 const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004643 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004644 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00004645 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004646 llvm::SmallBitVector &CheckedVarArgs,
4647 UncoveredArgHandler &UncoveredArg)
Richard Smithd7293d72013-08-05 18:49:43 +00004648 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
4649 numDataArgs, beg, hasVAListArg, Args,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004650 formatIdx, inFunctionCall, CallType, CheckedVarArgs,
4651 UncoveredArg),
Richard Smithd7293d72013-08-05 18:49:43 +00004652 ObjCContext(isObjC)
Jordan Rose3e0ec582012-07-19 18:10:23 +00004653 {}
4654
Ted Kremenek02087932010-07-16 02:11:22 +00004655 bool HandleInvalidPrintfConversionSpecifier(
4656 const analyze_printf::PrintfSpecifier &FS,
4657 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004658 unsigned specifierLen) override;
4659
Ted Kremenek02087932010-07-16 02:11:22 +00004660 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
4661 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004662 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00004663 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
4664 const char *StartSpecifier,
4665 unsigned SpecifierLen,
4666 const Expr *E);
4667
Ted Kremenek02087932010-07-16 02:11:22 +00004668 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
4669 const char *startSpecifier, unsigned specifierLen);
4670 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
4671 const analyze_printf::OptionalAmount &Amt,
4672 unsigned type,
4673 const char *startSpecifier, unsigned specifierLen);
4674 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
4675 const analyze_printf::OptionalFlag &flag,
4676 const char *startSpecifier, unsigned specifierLen);
4677 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
4678 const analyze_printf::OptionalFlag &ignoredFlag,
4679 const analyze_printf::OptionalFlag &flag,
4680 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004681 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00004682 const Expr *E);
Ted Kremenek2b417712015-07-02 05:39:16 +00004683
4684 void HandleEmptyObjCModifierFlag(const char *startFlag,
4685 unsigned flagLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00004686
Ted Kremenek2b417712015-07-02 05:39:16 +00004687 void HandleInvalidObjCModifierFlag(const char *startFlag,
4688 unsigned flagLen) override;
4689
4690 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
4691 const char *flagsEnd,
4692 const char *conversionPosition)
4693 override;
4694};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004695} // end anonymous namespace
Ted Kremenek02087932010-07-16 02:11:22 +00004696
4697bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
4698 const analyze_printf::PrintfSpecifier &FS,
4699 const char *startSpecifier,
4700 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004701 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00004702 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00004703
Ted Kremenekce815422010-07-19 21:25:57 +00004704 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
4705 getLocationOfByte(CS.getStart()),
4706 startSpecifier, specifierLen,
4707 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00004708}
4709
Ted Kremenek02087932010-07-16 02:11:22 +00004710bool CheckPrintfHandler::HandleAmount(
4711 const analyze_format_string::OptionalAmount &Amt,
4712 unsigned k, const char *startSpecifier,
4713 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00004714 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00004715 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00004716 unsigned argIndex = Amt.getArgIndex();
4717 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004718 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
4719 << k,
4720 getLocationOfByte(Amt.getStart()),
4721 /*IsStringLocation*/true,
4722 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00004723 // Don't do any more checking. We will just emit
4724 // spurious errors.
4725 return false;
4726 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004727
Ted Kremenek5739de72010-01-29 01:06:55 +00004728 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00004729 // Although not in conformance with C99, we also allow the argument to be
4730 // an 'unsigned int' as that is a reasonably safe case. GCC also
4731 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00004732 CoveredArgs.set(argIndex);
4733 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00004734 if (!Arg)
4735 return false;
4736
Ted Kremenek5739de72010-01-29 01:06:55 +00004737 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004738
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004739 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
4740 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004741
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004742 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004743 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004744 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00004745 << T << Arg->getSourceRange(),
4746 getLocationOfByte(Amt.getStart()),
4747 /*IsStringLocation*/true,
4748 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00004749 // Don't do any more checking. We will just emit
4750 // spurious errors.
4751 return false;
4752 }
4753 }
4754 }
4755 return true;
4756}
Ted Kremenek5739de72010-01-29 01:06:55 +00004757
Tom Careb49ec692010-06-17 19:00:27 +00004758void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00004759 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00004760 const analyze_printf::OptionalAmount &Amt,
4761 unsigned type,
4762 const char *startSpecifier,
4763 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004764 const analyze_printf::PrintfConversionSpecifier &CS =
4765 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00004766
Richard Trieu03cf7b72011-10-28 00:41:25 +00004767 FixItHint fixit =
4768 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
4769 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
4770 Amt.getConstantLength()))
4771 : FixItHint();
4772
4773 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
4774 << type << CS.toString(),
4775 getLocationOfByte(Amt.getStart()),
4776 /*IsStringLocation*/true,
4777 getSpecifierRange(startSpecifier, specifierLen),
4778 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00004779}
4780
Ted Kremenek02087932010-07-16 02:11:22 +00004781void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00004782 const analyze_printf::OptionalFlag &flag,
4783 const char *startSpecifier,
4784 unsigned specifierLen) {
4785 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004786 const analyze_printf::PrintfConversionSpecifier &CS =
4787 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00004788 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
4789 << flag.toString() << CS.toString(),
4790 getLocationOfByte(flag.getPosition()),
4791 /*IsStringLocation*/true,
4792 getSpecifierRange(startSpecifier, specifierLen),
4793 FixItHint::CreateRemoval(
4794 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00004795}
4796
4797void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00004798 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00004799 const analyze_printf::OptionalFlag &ignoredFlag,
4800 const analyze_printf::OptionalFlag &flag,
4801 const char *startSpecifier,
4802 unsigned specifierLen) {
4803 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00004804 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
4805 << ignoredFlag.toString() << flag.toString(),
4806 getLocationOfByte(ignoredFlag.getPosition()),
4807 /*IsStringLocation*/true,
4808 getSpecifierRange(startSpecifier, specifierLen),
4809 FixItHint::CreateRemoval(
4810 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00004811}
4812
Ted Kremenek2b417712015-07-02 05:39:16 +00004813// void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
4814// bool IsStringLocation, Range StringRange,
4815// ArrayRef<FixItHint> Fixit = None);
4816
4817void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
4818 unsigned flagLen) {
4819 // Warn about an empty flag.
4820 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
4821 getLocationOfByte(startFlag),
4822 /*IsStringLocation*/true,
4823 getSpecifierRange(startFlag, flagLen));
4824}
4825
4826void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
4827 unsigned flagLen) {
4828 // Warn about an invalid flag.
4829 auto Range = getSpecifierRange(startFlag, flagLen);
4830 StringRef flag(startFlag, flagLen);
4831 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
4832 getLocationOfByte(startFlag),
4833 /*IsStringLocation*/true,
4834 Range, FixItHint::CreateRemoval(Range));
4835}
4836
4837void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
4838 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
4839 // Warn about using '[...]' without a '@' conversion.
4840 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
4841 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
4842 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
4843 getLocationOfByte(conversionPosition),
4844 /*IsStringLocation*/true,
4845 Range, FixItHint::CreateRemoval(Range));
4846}
4847
Richard Smith55ce3522012-06-25 20:30:08 +00004848// Determines if the specified is a C++ class or struct containing
4849// a member with the specified name and kind (e.g. a CXXMethodDecl named
4850// "c_str()").
4851template<typename MemberKind>
4852static llvm::SmallPtrSet<MemberKind*, 1>
4853CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
4854 const RecordType *RT = Ty->getAs<RecordType>();
4855 llvm::SmallPtrSet<MemberKind*, 1> Results;
4856
4857 if (!RT)
4858 return Results;
4859 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00004860 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00004861 return Results;
4862
Alp Tokerb6cc5922014-05-03 03:45:55 +00004863 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00004864 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00004865 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00004866
4867 // We just need to include all members of the right kind turned up by the
4868 // filter, at this point.
4869 if (S.LookupQualifiedName(R, RT->getDecl()))
4870 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
4871 NamedDecl *decl = (*I)->getUnderlyingDecl();
4872 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
4873 Results.insert(FK);
4874 }
4875 return Results;
4876}
4877
Richard Smith2868a732014-02-28 01:36:39 +00004878/// Check if we could call '.c_str()' on an object.
4879///
4880/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
4881/// allow the call, or if it would be ambiguous).
4882bool Sema::hasCStrMethod(const Expr *E) {
4883 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
4884 MethodSet Results =
4885 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
4886 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
4887 MI != ME; ++MI)
4888 if ((*MI)->getMinRequiredArguments() == 0)
4889 return true;
4890 return false;
4891}
4892
Richard Smith55ce3522012-06-25 20:30:08 +00004893// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004894// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00004895// Returns true when a c_str() conversion method is found.
4896bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00004897 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00004898 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
4899
4900 MethodSet Results =
4901 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
4902
4903 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
4904 MI != ME; ++MI) {
4905 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00004906 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00004907 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00004908 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00004909 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00004910 S.Diag(E->getLocStart(), diag::note_printf_c_str)
4911 << "c_str()"
4912 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
4913 return true;
4914 }
4915 }
4916
4917 return false;
4918}
4919
Ted Kremenekab278de2010-01-28 23:39:18 +00004920bool
Ted Kremenek02087932010-07-16 02:11:22 +00004921CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00004922 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00004923 const char *startSpecifier,
4924 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004925 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00004926 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004927 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00004928
Ted Kremenek6cd69422010-07-19 22:01:06 +00004929 if (FS.consumesDataArgument()) {
4930 if (atFirstArg) {
4931 atFirstArg = false;
4932 usesPositionalArgs = FS.usesPositionalArg();
4933 }
4934 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004935 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
4936 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00004937 return false;
4938 }
Ted Kremenek5739de72010-01-29 01:06:55 +00004939 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004940
Ted Kremenekd1668192010-02-27 01:41:03 +00004941 // First check if the field width, precision, and conversion specifier
4942 // have matching data arguments.
4943 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
4944 startSpecifier, specifierLen)) {
4945 return false;
4946 }
4947
4948 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
4949 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00004950 return false;
4951 }
4952
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004953 if (!CS.consumesDataArgument()) {
4954 // FIXME: Technically specifying a precision or field width here
4955 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00004956 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004957 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004958
Ted Kremenek4a49d982010-02-26 19:18:41 +00004959 // Consume the argument.
4960 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00004961 if (argIndex < NumDataArgs) {
4962 // The check to see if the argIndex is valid will come later.
4963 // We set the bit here because we may exit early from this
4964 // function if we encounter some other error.
4965 CoveredArgs.set(argIndex);
4966 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00004967
Dimitry Andric6b5ed342015-02-19 22:32:33 +00004968 // FreeBSD kernel extensions.
4969 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
4970 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
4971 // We need at least two arguments.
4972 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
4973 return false;
4974
4975 // Claim the second argument.
4976 CoveredArgs.set(argIndex + 1);
4977
4978 // Type check the first argument (int for %b, pointer for %D)
4979 const Expr *Ex = getDataArg(argIndex);
4980 const analyze_printf::ArgType &AT =
4981 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
4982 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
4983 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
4984 EmitFormatDiagnostic(
4985 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4986 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
4987 << false << Ex->getSourceRange(),
4988 Ex->getLocStart(), /*IsStringLocation*/false,
4989 getSpecifierRange(startSpecifier, specifierLen));
4990
4991 // Type check the second argument (char * for both %b and %D)
4992 Ex = getDataArg(argIndex + 1);
4993 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
4994 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
4995 EmitFormatDiagnostic(
4996 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4997 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
4998 << false << Ex->getSourceRange(),
4999 Ex->getLocStart(), /*IsStringLocation*/false,
5000 getSpecifierRange(startSpecifier, specifierLen));
5001
5002 return true;
5003 }
5004
Ted Kremenek4a49d982010-02-26 19:18:41 +00005005 // Check for using an Objective-C specific conversion specifier
5006 // in a non-ObjC literal.
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005007 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00005008 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5009 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00005010 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005011
Tom Careb49ec692010-06-17 19:00:27 +00005012 // Check for invalid use of field width
5013 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00005014 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00005015 startSpecifier, specifierLen);
5016 }
5017
5018 // Check for invalid use of precision
5019 if (!FS.hasValidPrecision()) {
5020 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
5021 startSpecifier, specifierLen);
5022 }
5023
5024 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00005025 if (!FS.hasValidThousandsGroupingPrefix())
5026 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00005027 if (!FS.hasValidLeadingZeros())
5028 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
5029 if (!FS.hasValidPlusPrefix())
5030 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00005031 if (!FS.hasValidSpacePrefix())
5032 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00005033 if (!FS.hasValidAlternativeForm())
5034 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
5035 if (!FS.hasValidLeftJustified())
5036 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
5037
5038 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00005039 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
5040 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
5041 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00005042 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
5043 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
5044 startSpecifier, specifierLen);
5045
5046 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00005047 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00005048 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5049 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00005050 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00005051 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00005052 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00005053 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5054 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00005055
Jordan Rose92303592012-09-08 04:00:03 +00005056 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
5057 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
5058
Ted Kremenek9fcd8302010-01-29 01:43:31 +00005059 // The remaining checks depend on the data arguments.
5060 if (HasVAListArg)
5061 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005062
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005063 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00005064 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005065
Jordan Rose58bbe422012-07-19 18:10:08 +00005066 const Expr *Arg = getDataArg(argIndex);
5067 if (!Arg)
5068 return true;
5069
5070 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00005071}
5072
Jordan Roseaee34382012-09-05 22:56:26 +00005073static bool requiresParensToAddCast(const Expr *E) {
5074 // FIXME: We should have a general way to reason about operator
5075 // precedence and whether parens are actually needed here.
5076 // Take care of a few common cases where they aren't.
5077 const Expr *Inside = E->IgnoreImpCasts();
5078 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
5079 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
5080
5081 switch (Inside->getStmtClass()) {
5082 case Stmt::ArraySubscriptExprClass:
5083 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005084 case Stmt::CharacterLiteralClass:
5085 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005086 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005087 case Stmt::FloatingLiteralClass:
5088 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005089 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005090 case Stmt::ObjCArrayLiteralClass:
5091 case Stmt::ObjCBoolLiteralExprClass:
5092 case Stmt::ObjCBoxedExprClass:
5093 case Stmt::ObjCDictionaryLiteralClass:
5094 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005095 case Stmt::ObjCIvarRefExprClass:
5096 case Stmt::ObjCMessageExprClass:
5097 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005098 case Stmt::ObjCStringLiteralClass:
5099 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005100 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005101 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005102 case Stmt::UnaryOperatorClass:
5103 return false;
5104 default:
5105 return true;
5106 }
5107}
5108
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005109static std::pair<QualType, StringRef>
5110shouldNotPrintDirectly(const ASTContext &Context,
5111 QualType IntendedTy,
5112 const Expr *E) {
5113 // Use a 'while' to peel off layers of typedefs.
5114 QualType TyTy = IntendedTy;
5115 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
5116 StringRef Name = UserTy->getDecl()->getName();
5117 QualType CastTy = llvm::StringSwitch<QualType>(Name)
5118 .Case("NSInteger", Context.LongTy)
5119 .Case("NSUInteger", Context.UnsignedLongTy)
5120 .Case("SInt32", Context.IntTy)
5121 .Case("UInt32", Context.UnsignedIntTy)
5122 .Default(QualType());
5123
5124 if (!CastTy.isNull())
5125 return std::make_pair(CastTy, Name);
5126
5127 TyTy = UserTy->desugar();
5128 }
5129
5130 // Strip parens if necessary.
5131 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
5132 return shouldNotPrintDirectly(Context,
5133 PE->getSubExpr()->getType(),
5134 PE->getSubExpr());
5135
5136 // If this is a conditional expression, then its result type is constructed
5137 // via usual arithmetic conversions and thus there might be no necessary
5138 // typedef sugar there. Recurse to operands to check for NSInteger &
5139 // Co. usage condition.
5140 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
5141 QualType TrueTy, FalseTy;
5142 StringRef TrueName, FalseName;
5143
5144 std::tie(TrueTy, TrueName) =
5145 shouldNotPrintDirectly(Context,
5146 CO->getTrueExpr()->getType(),
5147 CO->getTrueExpr());
5148 std::tie(FalseTy, FalseName) =
5149 shouldNotPrintDirectly(Context,
5150 CO->getFalseExpr()->getType(),
5151 CO->getFalseExpr());
5152
5153 if (TrueTy == FalseTy)
5154 return std::make_pair(TrueTy, TrueName);
5155 else if (TrueTy.isNull())
5156 return std::make_pair(FalseTy, FalseName);
5157 else if (FalseTy.isNull())
5158 return std::make_pair(TrueTy, TrueName);
5159 }
5160
5161 return std::make_pair(QualType(), StringRef());
5162}
5163
Richard Smith55ce3522012-06-25 20:30:08 +00005164bool
5165CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5166 const char *StartSpecifier,
5167 unsigned SpecifierLen,
5168 const Expr *E) {
5169 using namespace analyze_format_string;
5170 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005171 // Now type check the data expression that matches the
5172 // format specifier.
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005173 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
5174 ObjCContext);
Jordan Rose22b74712012-09-05 22:56:19 +00005175 if (!AT.isValid())
5176 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00005177
Jordan Rose598ec092012-12-05 18:44:40 +00005178 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00005179 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
5180 ExprTy = TET->getUnderlyingExpr()->getType();
5181 }
5182
Seth Cantrellb4802962015-03-04 03:12:10 +00005183 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
5184
5185 if (match == analyze_printf::ArgType::Match) {
Jordan Rose22b74712012-09-05 22:56:19 +00005186 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00005187 }
Jordan Rose98709982012-06-04 22:48:57 +00005188
Jordan Rose22b74712012-09-05 22:56:19 +00005189 // Look through argument promotions for our error message's reported type.
5190 // This includes the integral and floating promotions, but excludes array
5191 // and function pointer decay; seeing that an argument intended to be a
5192 // string has type 'char [6]' is probably more confusing than 'char *'.
5193 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5194 if (ICE->getCastKind() == CK_IntegralCast ||
5195 ICE->getCastKind() == CK_FloatingCast) {
5196 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00005197 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00005198
5199 // Check if we didn't match because of an implicit cast from a 'char'
5200 // or 'short' to an 'int'. This is done because printf is a varargs
5201 // function.
5202 if (ICE->getType() == S.Context.IntTy ||
5203 ICE->getType() == S.Context.UnsignedIntTy) {
5204 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00005205 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00005206 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00005207 }
Jordan Rose98709982012-06-04 22:48:57 +00005208 }
Jordan Rose598ec092012-12-05 18:44:40 +00005209 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
5210 // Special case for 'a', which has type 'int' in C.
5211 // Note, however, that we do /not/ want to treat multibyte constants like
5212 // 'MooV' as characters! This form is deprecated but still exists.
5213 if (ExprTy == S.Context.IntTy)
5214 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
5215 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00005216 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005217
Jordan Rosebc53ed12014-05-31 04:12:14 +00005218 // Look through enums to their underlying type.
5219 bool IsEnum = false;
5220 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
5221 ExprTy = EnumTy->getDecl()->getIntegerType();
5222 IsEnum = true;
5223 }
5224
Jordan Rose0e5badd2012-12-05 18:44:49 +00005225 // %C in an Objective-C context prints a unichar, not a wchar_t.
5226 // If the argument is an integer of some kind, believe the %C and suggest
5227 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00005228 QualType IntendedTy = ExprTy;
Jordan Rose0e5badd2012-12-05 18:44:49 +00005229 if (ObjCContext &&
5230 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
5231 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
5232 !ExprTy->isCharType()) {
5233 // 'unichar' is defined as a typedef of unsigned short, but we should
5234 // prefer using the typedef if it is visible.
5235 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00005236
5237 // While we are here, check if the value is an IntegerLiteral that happens
5238 // to be within the valid range.
5239 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
5240 const llvm::APInt &V = IL->getValue();
5241 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
5242 return true;
5243 }
5244
Jordan Rose0e5badd2012-12-05 18:44:49 +00005245 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
5246 Sema::LookupOrdinaryName);
5247 if (S.LookupName(Result, S.getCurScope())) {
5248 NamedDecl *ND = Result.getFoundDecl();
5249 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
5250 if (TD->getUnderlyingType() == IntendedTy)
5251 IntendedTy = S.Context.getTypedefType(TD);
5252 }
5253 }
5254 }
5255
5256 // Special-case some of Darwin's platform-independence types by suggesting
5257 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005258 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00005259 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005260 QualType CastTy;
5261 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
5262 if (!CastTy.isNull()) {
5263 IntendedTy = CastTy;
5264 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00005265 }
5266 }
5267
Jordan Rose22b74712012-09-05 22:56:19 +00005268 // We may be able to offer a FixItHint if it is a supported type.
5269 PrintfSpecifier fixedFS = FS;
Jordan Roseaee34382012-09-05 22:56:26 +00005270 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose22b74712012-09-05 22:56:19 +00005271 S.Context, ObjCContext);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005272
Jordan Rose22b74712012-09-05 22:56:19 +00005273 if (success) {
5274 // Get the fix string from the fixed format specifier
5275 SmallString<16> buf;
5276 llvm::raw_svector_ostream os(buf);
5277 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005278
Jordan Roseaee34382012-09-05 22:56:26 +00005279 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
5280
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005281 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Daniel Jasperad8d8492015-03-04 14:18:20 +00005282 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
5283 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
5284 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
5285 }
Jordan Rose0e5badd2012-12-05 18:44:49 +00005286 // In this case, the specifier is wrong and should be changed to match
5287 // the argument.
Daniel Jasperad8d8492015-03-04 14:18:20 +00005288 EmitFormatDiagnostic(S.PDiag(diag)
5289 << AT.getRepresentativeTypeName(S.Context)
5290 << IntendedTy << IsEnum << E->getSourceRange(),
5291 E->getLocStart(),
5292 /*IsStringLocation*/ false, SpecRange,
5293 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00005294 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00005295 // The canonical type for formatting this value is different from the
5296 // actual type of the expression. (This occurs, for example, with Darwin's
5297 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
5298 // should be printed as 'long' for 64-bit compatibility.)
5299 // Rather than emitting a normal format/argument mismatch, we want to
5300 // add a cast to the recommended type (and correct the format string
5301 // if necessary).
5302 SmallString<16> CastBuf;
5303 llvm::raw_svector_ostream CastFix(CastBuf);
5304 CastFix << "(";
5305 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
5306 CastFix << ")";
5307
5308 SmallVector<FixItHint,4> Hints;
5309 if (!AT.matchesType(S.Context, IntendedTy))
5310 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
5311
5312 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
5313 // If there's already a cast present, just replace it.
5314 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
5315 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
5316
5317 } else if (!requiresParensToAddCast(E)) {
5318 // If the expression has high enough precedence,
5319 // just write the C-style cast.
5320 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
5321 CastFix.str()));
5322 } else {
5323 // Otherwise, add parens around the expression as well as the cast.
5324 CastFix << "(";
5325 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
5326 CastFix.str()));
5327
Alp Tokerb6cc5922014-05-03 03:45:55 +00005328 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00005329 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
5330 }
5331
Jordan Rose0e5badd2012-12-05 18:44:49 +00005332 if (ShouldNotPrintDirectly) {
5333 // The expression has a type that should not be printed directly.
5334 // We extract the name from the typedef because we don't want to show
5335 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005336 StringRef Name;
5337 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
5338 Name = TypedefTy->getDecl()->getName();
5339 else
5340 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00005341 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00005342 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00005343 << E->getSourceRange(),
5344 E->getLocStart(), /*IsStringLocation=*/false,
5345 SpecRange, Hints);
5346 } else {
5347 // In this case, the expression could be printed using a different
5348 // specifier, but we've decided that the specifier is probably correct
5349 // and we should cast instead. Just use the normal warning message.
5350 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00005351 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5352 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00005353 << E->getSourceRange(),
5354 E->getLocStart(), /*IsStringLocation*/false,
5355 SpecRange, Hints);
5356 }
Jordan Roseaee34382012-09-05 22:56:26 +00005357 }
Jordan Rose22b74712012-09-05 22:56:19 +00005358 } else {
5359 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
5360 SpecifierLen);
5361 // Since the warning for passing non-POD types to variadic functions
5362 // was deferred until now, we emit a warning for non-POD
5363 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00005364 switch (S.isValidVarArgType(ExprTy)) {
5365 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00005366 case Sema::VAK_ValidInCXX11: {
5367 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
5368 if (match == analyze_printf::ArgType::NoMatchPedantic) {
5369 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
5370 }
Richard Smithd7293d72013-08-05 18:49:43 +00005371
Seth Cantrellb4802962015-03-04 03:12:10 +00005372 EmitFormatDiagnostic(
5373 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
5374 << IsEnum << CSR << E->getSourceRange(),
5375 E->getLocStart(), /*IsStringLocation*/ false, CSR);
5376 break;
5377 }
Richard Smithd7293d72013-08-05 18:49:43 +00005378 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00005379 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00005380 EmitFormatDiagnostic(
5381 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005382 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00005383 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00005384 << CallType
5385 << AT.getRepresentativeTypeName(S.Context)
5386 << CSR
5387 << E->getSourceRange(),
5388 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00005389 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00005390 break;
5391
5392 case Sema::VAK_Invalid:
5393 if (ExprTy->isObjCObjectType())
5394 EmitFormatDiagnostic(
5395 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
5396 << S.getLangOpts().CPlusPlus11
5397 << ExprTy
5398 << CallType
5399 << AT.getRepresentativeTypeName(S.Context)
5400 << CSR
5401 << E->getSourceRange(),
5402 E->getLocStart(), /*IsStringLocation*/false, CSR);
5403 else
5404 // FIXME: If this is an initializer list, suggest removing the braces
5405 // or inserting a cast to the target type.
5406 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
5407 << isa<InitListExpr>(E) << ExprTy << CallType
5408 << AT.getRepresentativeTypeName(S.Context)
5409 << E->getSourceRange();
5410 break;
5411 }
5412
5413 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
5414 "format string specifier index out of range");
5415 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005416 }
5417
Ted Kremenekab278de2010-01-28 23:39:18 +00005418 return true;
5419}
5420
Ted Kremenek02087932010-07-16 02:11:22 +00005421//===--- CHECK: Scanf format string checking ------------------------------===//
5422
5423namespace {
5424class CheckScanfHandler : public CheckFormatHandler {
5425public:
Stephen Hines6a17e512016-09-14 20:20:14 +00005426 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek02087932010-07-16 02:11:22 +00005427 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005428 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005429 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005430 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00005431 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005432 llvm::SmallBitVector &CheckedVarArgs,
5433 UncoveredArgHandler &UncoveredArg)
Richard Smithd7293d72013-08-05 18:49:43 +00005434 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
5435 numDataArgs, beg, hasVAListArg,
5436 Args, formatIdx, inFunctionCall, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005437 CheckedVarArgs, UncoveredArg)
Jordan Rose3e0ec582012-07-19 18:10:23 +00005438 {}
Ted Kremenek02087932010-07-16 02:11:22 +00005439
5440 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
5441 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005442 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00005443
5444 bool HandleInvalidScanfConversionSpecifier(
5445 const analyze_scanf::ScanfSpecifier &FS,
5446 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005447 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00005448
Craig Toppere14c0f82014-03-12 04:55:44 +00005449 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00005450};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005451} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00005452
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00005453void CheckScanfHandler::HandleIncompleteScanList(const char *start,
5454 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005455 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
5456 getLocationOfByte(end), /*IsStringLocation*/true,
5457 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00005458}
5459
Ted Kremenekce815422010-07-19 21:25:57 +00005460bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
5461 const analyze_scanf::ScanfSpecifier &FS,
5462 const char *startSpecifier,
5463 unsigned specifierLen) {
5464
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005465 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00005466 FS.getConversionSpecifier();
5467
5468 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
5469 getLocationOfByte(CS.getStart()),
5470 startSpecifier, specifierLen,
5471 CS.getStart(), CS.getLength());
5472}
5473
Ted Kremenek02087932010-07-16 02:11:22 +00005474bool CheckScanfHandler::HandleScanfSpecifier(
5475 const analyze_scanf::ScanfSpecifier &FS,
5476 const char *startSpecifier,
5477 unsigned specifierLen) {
Ted Kremenek02087932010-07-16 02:11:22 +00005478 using namespace analyze_scanf;
5479 using namespace analyze_format_string;
5480
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005481 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00005482
Ted Kremenek6cd69422010-07-19 22:01:06 +00005483 // Handle case where '%' and '*' don't consume an argument. These shouldn't
5484 // be used to decide if we are using positional arguments consistently.
5485 if (FS.consumesDataArgument()) {
5486 if (atFirstArg) {
5487 atFirstArg = false;
5488 usesPositionalArgs = FS.usesPositionalArg();
5489 }
5490 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005491 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
5492 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00005493 return false;
5494 }
Ted Kremenek02087932010-07-16 02:11:22 +00005495 }
5496
5497 // Check if the field with is non-zero.
5498 const OptionalAmount &Amt = FS.getFieldWidth();
5499 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
5500 if (Amt.getConstantAmount() == 0) {
5501 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
5502 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00005503 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
5504 getLocationOfByte(Amt.getStart()),
5505 /*IsStringLocation*/true, R,
5506 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00005507 }
5508 }
Seth Cantrellb4802962015-03-04 03:12:10 +00005509
Ted Kremenek02087932010-07-16 02:11:22 +00005510 if (!FS.consumesDataArgument()) {
5511 // FIXME: Technically specifying a precision or field width here
5512 // makes no sense. Worth issuing a warning at some point.
5513 return true;
5514 }
Seth Cantrellb4802962015-03-04 03:12:10 +00005515
Ted Kremenek02087932010-07-16 02:11:22 +00005516 // Consume the argument.
5517 unsigned argIndex = FS.getArgIndex();
5518 if (argIndex < NumDataArgs) {
5519 // The check to see if the argIndex is valid will come later.
5520 // We set the bit here because we may exit early from this
5521 // function if we encounter some other error.
5522 CoveredArgs.set(argIndex);
5523 }
Seth Cantrellb4802962015-03-04 03:12:10 +00005524
Ted Kremenek4407ea42010-07-20 20:04:47 +00005525 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00005526 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00005527 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5528 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00005529 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00005530 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00005531 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00005532 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5533 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005534
Jordan Rose92303592012-09-08 04:00:03 +00005535 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
5536 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
5537
Ted Kremenek02087932010-07-16 02:11:22 +00005538 // The remaining checks depend on the data arguments.
5539 if (HasVAListArg)
5540 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00005541
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005542 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00005543 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00005544
Hans Wennborgb1a5e092011-12-10 13:20:11 +00005545 // Check that the argument type matches the format specifier.
5546 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00005547 if (!Ex)
5548 return true;
5549
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00005550 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00005551
5552 if (!AT.isValid()) {
5553 return true;
5554 }
5555
Seth Cantrellb4802962015-03-04 03:12:10 +00005556 analyze_format_string::ArgType::MatchKind match =
5557 AT.matchesType(S.Context, Ex->getType());
Seth Cantrell79340072015-03-04 05:58:08 +00005558 if (match == analyze_format_string::ArgType::Match) {
5559 return true;
5560 }
Seth Cantrellb4802962015-03-04 03:12:10 +00005561
Seth Cantrell79340072015-03-04 05:58:08 +00005562 ScanfSpecifier fixedFS = FS;
5563 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
5564 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00005565
Seth Cantrell79340072015-03-04 05:58:08 +00005566 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
5567 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
5568 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
5569 }
Hans Wennborgb1a5e092011-12-10 13:20:11 +00005570
Seth Cantrell79340072015-03-04 05:58:08 +00005571 if (success) {
5572 // Get the fix string from the fixed format specifier.
5573 SmallString<128> buf;
5574 llvm::raw_svector_ostream os(buf);
5575 fixedFS.toString(os);
5576
5577 EmitFormatDiagnostic(
5578 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
5579 << Ex->getType() << false << Ex->getSourceRange(),
5580 Ex->getLocStart(),
5581 /*IsStringLocation*/ false,
5582 getSpecifierRange(startSpecifier, specifierLen),
5583 FixItHint::CreateReplacement(
5584 getSpecifierRange(startSpecifier, specifierLen), os.str()));
5585 } else {
5586 EmitFormatDiagnostic(S.PDiag(diag)
5587 << AT.getRepresentativeTypeName(S.Context)
5588 << Ex->getType() << false << Ex->getSourceRange(),
5589 Ex->getLocStart(),
5590 /*IsStringLocation*/ false,
5591 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00005592 }
5593
Ted Kremenek02087932010-07-16 02:11:22 +00005594 return true;
5595}
5596
Stephen Hines6a17e512016-09-14 20:20:14 +00005597static void CheckFormatString(Sema &S, const StringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005598 const Expr *OrigFormatExpr,
5599 ArrayRef<const Expr *> Args,
5600 bool HasVAListArg, unsigned format_idx,
5601 unsigned firstDataArg,
5602 Sema::FormatStringType Type,
5603 bool inFunctionCall,
5604 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005605 llvm::SmallBitVector &CheckedVarArgs,
5606 UncoveredArgHandler &UncoveredArg) {
Ted Kremenekab278de2010-01-28 23:39:18 +00005607 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00005608 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005609 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005610 S, inFunctionCall, Args[format_idx],
5611 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00005612 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00005613 return;
5614 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005615
Ted Kremenekab278de2010-01-28 23:39:18 +00005616 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005617 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00005618 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00005619 // Account for cases where the string literal is truncated in a declaration.
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005620 const ConstantArrayType *T =
5621 S.Context.getAsConstantArrayType(FExpr->getType());
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00005622 assert(T && "String literal not of constant array type!");
5623 size_t TypeSize = T->getSize().getZExtValue();
5624 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005625 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00005626
5627 // Emit a warning if the string literal is truncated and does not contain an
5628 // embedded null character.
5629 if (TypeSize <= StrRef.size() &&
5630 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
5631 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005632 S, inFunctionCall, Args[format_idx],
5633 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00005634 FExpr->getLocStart(),
5635 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
5636 return;
5637 }
5638
Ted Kremenekab278de2010-01-28 23:39:18 +00005639 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00005640 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005641 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005642 S, inFunctionCall, Args[format_idx],
5643 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00005644 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00005645 return;
5646 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005647
5648 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
5649 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSTrace) {
5650 CheckPrintfHandler H(S, FExpr, OrigFormatExpr, firstDataArg,
5651 numDataArgs, (Type == Sema::FST_NSString ||
5652 Type == Sema::FST_OSTrace),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005653 Str, HasVAListArg, Args, format_idx,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005654 inFunctionCall, CallType, CheckedVarArgs,
5655 UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005656
Hans Wennborg23926bd2011-12-15 10:25:47 +00005657 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005658 S.getLangOpts(),
5659 S.Context.getTargetInfo(),
5660 Type == Sema::FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00005661 H.DoneProcessing();
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005662 } else if (Type == Sema::FST_Scanf) {
5663 CheckScanfHandler H(S, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005664 Str, HasVAListArg, Args, format_idx,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005665 inFunctionCall, CallType, CheckedVarArgs,
5666 UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005667
Hans Wennborg23926bd2011-12-15 10:25:47 +00005668 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005669 S.getLangOpts(),
5670 S.Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00005671 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005672 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00005673}
5674
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00005675bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
5676 // Str - The format string. NOTE: this is NOT null-terminated!
5677 StringRef StrRef = FExpr->getString();
5678 const char *Str = StrRef.data();
5679 // Account for cases where the string literal is truncated in a declaration.
5680 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
5681 assert(T && "String literal not of constant array type!");
5682 size_t TypeSize = T->getSize().getZExtValue();
5683 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
5684 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
5685 getLangOpts(),
5686 Context.getTargetInfo());
5687}
5688
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005689//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
5690
5691// Returns the related absolute value function that is larger, of 0 if one
5692// does not exist.
5693static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
5694 switch (AbsFunction) {
5695 default:
5696 return 0;
5697
5698 case Builtin::BI__builtin_abs:
5699 return Builtin::BI__builtin_labs;
5700 case Builtin::BI__builtin_labs:
5701 return Builtin::BI__builtin_llabs;
5702 case Builtin::BI__builtin_llabs:
5703 return 0;
5704
5705 case Builtin::BI__builtin_fabsf:
5706 return Builtin::BI__builtin_fabs;
5707 case Builtin::BI__builtin_fabs:
5708 return Builtin::BI__builtin_fabsl;
5709 case Builtin::BI__builtin_fabsl:
5710 return 0;
5711
5712 case Builtin::BI__builtin_cabsf:
5713 return Builtin::BI__builtin_cabs;
5714 case Builtin::BI__builtin_cabs:
5715 return Builtin::BI__builtin_cabsl;
5716 case Builtin::BI__builtin_cabsl:
5717 return 0;
5718
5719 case Builtin::BIabs:
5720 return Builtin::BIlabs;
5721 case Builtin::BIlabs:
5722 return Builtin::BIllabs;
5723 case Builtin::BIllabs:
5724 return 0;
5725
5726 case Builtin::BIfabsf:
5727 return Builtin::BIfabs;
5728 case Builtin::BIfabs:
5729 return Builtin::BIfabsl;
5730 case Builtin::BIfabsl:
5731 return 0;
5732
5733 case Builtin::BIcabsf:
5734 return Builtin::BIcabs;
5735 case Builtin::BIcabs:
5736 return Builtin::BIcabsl;
5737 case Builtin::BIcabsl:
5738 return 0;
5739 }
5740}
5741
5742// Returns the argument type of the absolute value function.
5743static QualType getAbsoluteValueArgumentType(ASTContext &Context,
5744 unsigned AbsType) {
5745 if (AbsType == 0)
5746 return QualType();
5747
5748 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
5749 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
5750 if (Error != ASTContext::GE_None)
5751 return QualType();
5752
5753 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
5754 if (!FT)
5755 return QualType();
5756
5757 if (FT->getNumParams() != 1)
5758 return QualType();
5759
5760 return FT->getParamType(0);
5761}
5762
5763// Returns the best absolute value function, or zero, based on type and
5764// current absolute value function.
5765static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
5766 unsigned AbsFunctionKind) {
5767 unsigned BestKind = 0;
5768 uint64_t ArgSize = Context.getTypeSize(ArgType);
5769 for (unsigned Kind = AbsFunctionKind; Kind != 0;
5770 Kind = getLargerAbsoluteValueFunction(Kind)) {
5771 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
5772 if (Context.getTypeSize(ParamType) >= ArgSize) {
5773 if (BestKind == 0)
5774 BestKind = Kind;
5775 else if (Context.hasSameType(ParamType, ArgType)) {
5776 BestKind = Kind;
5777 break;
5778 }
5779 }
5780 }
5781 return BestKind;
5782}
5783
5784enum AbsoluteValueKind {
5785 AVK_Integer,
5786 AVK_Floating,
5787 AVK_Complex
5788};
5789
5790static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
5791 if (T->isIntegralOrEnumerationType())
5792 return AVK_Integer;
5793 if (T->isRealFloatingType())
5794 return AVK_Floating;
5795 if (T->isAnyComplexType())
5796 return AVK_Complex;
5797
5798 llvm_unreachable("Type not integer, floating, or complex");
5799}
5800
5801// Changes the absolute value function to a different type. Preserves whether
5802// the function is a builtin.
5803static unsigned changeAbsFunction(unsigned AbsKind,
5804 AbsoluteValueKind ValueKind) {
5805 switch (ValueKind) {
5806 case AVK_Integer:
5807 switch (AbsKind) {
5808 default:
5809 return 0;
5810 case Builtin::BI__builtin_fabsf:
5811 case Builtin::BI__builtin_fabs:
5812 case Builtin::BI__builtin_fabsl:
5813 case Builtin::BI__builtin_cabsf:
5814 case Builtin::BI__builtin_cabs:
5815 case Builtin::BI__builtin_cabsl:
5816 return Builtin::BI__builtin_abs;
5817 case Builtin::BIfabsf:
5818 case Builtin::BIfabs:
5819 case Builtin::BIfabsl:
5820 case Builtin::BIcabsf:
5821 case Builtin::BIcabs:
5822 case Builtin::BIcabsl:
5823 return Builtin::BIabs;
5824 }
5825 case AVK_Floating:
5826 switch (AbsKind) {
5827 default:
5828 return 0;
5829 case Builtin::BI__builtin_abs:
5830 case Builtin::BI__builtin_labs:
5831 case Builtin::BI__builtin_llabs:
5832 case Builtin::BI__builtin_cabsf:
5833 case Builtin::BI__builtin_cabs:
5834 case Builtin::BI__builtin_cabsl:
5835 return Builtin::BI__builtin_fabsf;
5836 case Builtin::BIabs:
5837 case Builtin::BIlabs:
5838 case Builtin::BIllabs:
5839 case Builtin::BIcabsf:
5840 case Builtin::BIcabs:
5841 case Builtin::BIcabsl:
5842 return Builtin::BIfabsf;
5843 }
5844 case AVK_Complex:
5845 switch (AbsKind) {
5846 default:
5847 return 0;
5848 case Builtin::BI__builtin_abs:
5849 case Builtin::BI__builtin_labs:
5850 case Builtin::BI__builtin_llabs:
5851 case Builtin::BI__builtin_fabsf:
5852 case Builtin::BI__builtin_fabs:
5853 case Builtin::BI__builtin_fabsl:
5854 return Builtin::BI__builtin_cabsf;
5855 case Builtin::BIabs:
5856 case Builtin::BIlabs:
5857 case Builtin::BIllabs:
5858 case Builtin::BIfabsf:
5859 case Builtin::BIfabs:
5860 case Builtin::BIfabsl:
5861 return Builtin::BIcabsf;
5862 }
5863 }
5864 llvm_unreachable("Unable to convert function");
5865}
5866
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00005867static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005868 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
5869 if (!FnInfo)
5870 return 0;
5871
5872 switch (FDecl->getBuiltinID()) {
5873 default:
5874 return 0;
5875 case Builtin::BI__builtin_abs:
5876 case Builtin::BI__builtin_fabs:
5877 case Builtin::BI__builtin_fabsf:
5878 case Builtin::BI__builtin_fabsl:
5879 case Builtin::BI__builtin_labs:
5880 case Builtin::BI__builtin_llabs:
5881 case Builtin::BI__builtin_cabs:
5882 case Builtin::BI__builtin_cabsf:
5883 case Builtin::BI__builtin_cabsl:
5884 case Builtin::BIabs:
5885 case Builtin::BIlabs:
5886 case Builtin::BIllabs:
5887 case Builtin::BIfabs:
5888 case Builtin::BIfabsf:
5889 case Builtin::BIfabsl:
5890 case Builtin::BIcabs:
5891 case Builtin::BIcabsf:
5892 case Builtin::BIcabsl:
5893 return FDecl->getBuiltinID();
5894 }
5895 llvm_unreachable("Unknown Builtin type");
5896}
5897
5898// If the replacement is valid, emit a note with replacement function.
5899// Additionally, suggest including the proper header if not already included.
5900static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00005901 unsigned AbsKind, QualType ArgType) {
5902 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00005903 const char *HeaderName = nullptr;
5904 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00005905 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
5906 FunctionName = "std::abs";
5907 if (ArgType->isIntegralOrEnumerationType()) {
5908 HeaderName = "cstdlib";
5909 } else if (ArgType->isRealFloatingType()) {
5910 HeaderName = "cmath";
5911 } else {
5912 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005913 }
Richard Trieubeffb832014-04-15 23:47:53 +00005914
5915 // Lookup all std::abs
5916 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00005917 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00005918 R.suppressDiagnostics();
5919 S.LookupQualifiedName(R, Std);
5920
5921 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005922 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00005923 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
5924 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
5925 } else {
5926 FDecl = dyn_cast<FunctionDecl>(I);
5927 }
5928 if (!FDecl)
5929 continue;
5930
5931 // Found std::abs(), check that they are the right ones.
5932 if (FDecl->getNumParams() != 1)
5933 continue;
5934
5935 // Check that the parameter type can handle the argument.
5936 QualType ParamType = FDecl->getParamDecl(0)->getType();
5937 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
5938 S.Context.getTypeSize(ArgType) <=
5939 S.Context.getTypeSize(ParamType)) {
5940 // Found a function, don't need the header hint.
5941 EmitHeaderHint = false;
5942 break;
5943 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005944 }
Richard Trieubeffb832014-04-15 23:47:53 +00005945 }
5946 } else {
Eric Christopher02d5d862015-08-06 01:01:12 +00005947 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
Richard Trieubeffb832014-04-15 23:47:53 +00005948 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
5949
5950 if (HeaderName) {
5951 DeclarationName DN(&S.Context.Idents.get(FunctionName));
5952 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
5953 R.suppressDiagnostics();
5954 S.LookupName(R, S.getCurScope());
5955
5956 if (R.isSingleResult()) {
5957 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
5958 if (FD && FD->getBuiltinID() == AbsKind) {
5959 EmitHeaderHint = false;
5960 } else {
5961 return;
5962 }
5963 } else if (!R.empty()) {
5964 return;
5965 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005966 }
5967 }
5968
5969 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00005970 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005971
Richard Trieubeffb832014-04-15 23:47:53 +00005972 if (!HeaderName)
5973 return;
5974
5975 if (!EmitHeaderHint)
5976 return;
5977
Alp Toker5d96e0a2014-07-11 20:53:51 +00005978 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
5979 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00005980}
5981
5982static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
5983 if (!FDecl)
5984 return false;
5985
5986 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
5987 return false;
5988
5989 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
5990
5991 while (ND && ND->isInlineNamespace()) {
5992 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005993 }
Richard Trieubeffb832014-04-15 23:47:53 +00005994
5995 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
5996 return false;
5997
5998 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
5999 return false;
6000
6001 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006002}
6003
6004// Warn when using the wrong abs() function.
6005void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
6006 const FunctionDecl *FDecl,
6007 IdentifierInfo *FnInfo) {
6008 if (Call->getNumArgs() != 1)
6009 return;
6010
6011 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieubeffb832014-04-15 23:47:53 +00006012 bool IsStdAbs = IsFunctionStdAbs(FDecl);
6013 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006014 return;
6015
6016 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
6017 QualType ParamType = Call->getArg(0)->getType();
6018
Alp Toker5d96e0a2014-07-11 20:53:51 +00006019 // Unsigned types cannot be negative. Suggest removing the absolute value
6020 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006021 if (ArgType->isUnsignedIntegerType()) {
Richard Trieubeffb832014-04-15 23:47:53 +00006022 const char *FunctionName =
Eric Christopher02d5d862015-08-06 01:01:12 +00006023 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006024 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
6025 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00006026 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006027 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
6028 return;
6029 }
6030
David Majnemer7f77eb92015-11-15 03:04:34 +00006031 // Taking the absolute value of a pointer is very suspicious, they probably
6032 // wanted to index into an array, dereference a pointer, call a function, etc.
6033 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
6034 unsigned DiagType = 0;
6035 if (ArgType->isFunctionType())
6036 DiagType = 1;
6037 else if (ArgType->isArrayType())
6038 DiagType = 2;
6039
6040 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
6041 return;
6042 }
6043
Richard Trieubeffb832014-04-15 23:47:53 +00006044 // std::abs has overloads which prevent most of the absolute value problems
6045 // from occurring.
6046 if (IsStdAbs)
6047 return;
6048
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006049 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
6050 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
6051
6052 // The argument and parameter are the same kind. Check if they are the right
6053 // size.
6054 if (ArgValueKind == ParamValueKind) {
6055 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
6056 return;
6057
6058 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
6059 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
6060 << FDecl << ArgType << ParamType;
6061
6062 if (NewAbsKind == 0)
6063 return;
6064
6065 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00006066 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006067 return;
6068 }
6069
6070 // ArgValueKind != ParamValueKind
6071 // The wrong type of absolute value function was used. Attempt to find the
6072 // proper one.
6073 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
6074 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
6075 if (NewAbsKind == 0)
6076 return;
6077
6078 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
6079 << FDecl << ParamValueKind << ArgValueKind;
6080
6081 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00006082 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006083}
6084
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006085//===--- CHECK: Standard memory functions ---------------------------------===//
6086
Nico Weber0e6daef2013-12-26 23:38:39 +00006087/// \brief Takes the expression passed to the size_t parameter of functions
6088/// such as memcmp, strncat, etc and warns if it's a comparison.
6089///
6090/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
6091static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
6092 IdentifierInfo *FnName,
6093 SourceLocation FnLoc,
6094 SourceLocation RParenLoc) {
6095 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
6096 if (!Size)
6097 return false;
6098
6099 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
6100 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
6101 return false;
6102
Nico Weber0e6daef2013-12-26 23:38:39 +00006103 SourceRange SizeRange = Size->getSourceRange();
6104 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
6105 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00006106 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00006107 << FnName << FixItHint::CreateInsertion(
6108 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00006109 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00006110 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00006111 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00006112 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
6113 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00006114
6115 return true;
6116}
6117
Reid Kleckner5fb5b122014-06-27 23:58:21 +00006118/// \brief Determine whether the given type is or contains a dynamic class type
6119/// (e.g., whether it has a vtable).
6120static const CXXRecordDecl *getContainedDynamicClass(QualType T,
6121 bool &IsContained) {
6122 // Look through array types while ignoring qualifiers.
6123 const Type *Ty = T->getBaseElementTypeUnsafe();
6124 IsContained = false;
6125
6126 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
6127 RD = RD ? RD->getDefinition() : nullptr;
Richard Trieu1c7237a2016-03-31 04:18:07 +00006128 if (!RD || RD->isInvalidDecl())
Reid Kleckner5fb5b122014-06-27 23:58:21 +00006129 return nullptr;
6130
6131 if (RD->isDynamicClass())
6132 return RD;
6133
6134 // Check all the fields. If any bases were dynamic, the class is dynamic.
6135 // It's impossible for a class to transitively contain itself by value, so
6136 // infinite recursion is impossible.
6137 for (auto *FD : RD->fields()) {
6138 bool SubContained;
6139 if (const CXXRecordDecl *ContainedRD =
6140 getContainedDynamicClass(FD->getType(), SubContained)) {
6141 IsContained = true;
6142 return ContainedRD;
6143 }
6144 }
6145
6146 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00006147}
6148
Chandler Carruth889ed862011-06-21 23:04:20 +00006149/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006150/// otherwise returns NULL.
Nico Weberc44b35e2015-03-21 17:37:46 +00006151static const Expr *getSizeOfExprArg(const Expr *E) {
Nico Weberc5e73862011-06-14 16:14:58 +00006152 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006153 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
6154 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
6155 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00006156
Craig Topperc3ec1492014-05-26 06:22:03 +00006157 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006158}
6159
Chandler Carruth889ed862011-06-21 23:04:20 +00006160/// \brief If E is a sizeof expression, returns its argument type.
Nico Weberc44b35e2015-03-21 17:37:46 +00006161static QualType getSizeOfArgType(const Expr *E) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006162 if (const UnaryExprOrTypeTraitExpr *SizeOf =
6163 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
6164 if (SizeOf->getKind() == clang::UETT_SizeOf)
6165 return SizeOf->getTypeOfArgument();
6166
6167 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00006168}
6169
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006170/// \brief Check for dangerous or invalid arguments to memset().
6171///
Chandler Carruthac687262011-06-03 06:23:57 +00006172/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00006173/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
6174/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006175///
6176/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00006177void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00006178 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00006179 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00006180 assert(BId != 0);
6181
Ted Kremenekb5fabb22011-04-28 01:38:02 +00006182 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00006183 // we have enough arguments, and if not, abort further checking.
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00006184 unsigned ExpectedNumArgs =
6185 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00006186 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00006187 return;
6188
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00006189 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
Anna Zaks22122702012-01-17 00:37:07 +00006190 BId == Builtin::BIstrndup ? 1 : 2);
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00006191 unsigned LenArg =
6192 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00006193 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006194
Nico Weber0e6daef2013-12-26 23:38:39 +00006195 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
6196 Call->getLocStart(), Call->getRParenLoc()))
6197 return;
6198
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006199 // We have special checking when the length is a sizeof expression.
6200 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
6201 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
6202 llvm::FoldingSetNodeID SizeOfArgID;
6203
Bruno Cardoso Lopesc73e4c32016-08-11 18:33:15 +00006204 // Although widely used, 'bzero' is not a standard function. Be more strict
6205 // with the argument types before allowing diagnostics and only allow the
6206 // form bzero(ptr, sizeof(...)).
6207 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
6208 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
6209 return;
6210
Douglas Gregor3bb2a812011-05-03 20:37:33 +00006211 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
6212 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00006213 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006214
Douglas Gregor3bb2a812011-05-03 20:37:33 +00006215 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00006216 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00006217 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00006218 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00006219
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006220 // Never warn about void type pointers. This can be used to suppress
6221 // false positives.
6222 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00006223 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006224
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006225 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
6226 // actually comparing the expressions for equality. Because computing the
6227 // expression IDs can be expensive, we only do this if the diagnostic is
6228 // enabled.
6229 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00006230 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
6231 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006232 // We only compute IDs for expressions if the warning is enabled, and
6233 // cache the sizeof arg's ID.
6234 if (SizeOfArgID == llvm::FoldingSetNodeID())
6235 SizeOfArg->Profile(SizeOfArgID, Context, true);
6236 llvm::FoldingSetNodeID DestID;
6237 Dest->Profile(DestID, Context, true);
6238 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00006239 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
6240 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006241 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00006242 StringRef ReadableName = FnName->getName();
6243
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006244 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00006245 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006246 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00006247 if (!PointeeTy->isIncompleteType() &&
6248 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006249 ActionIdx = 2; // If the pointee's size is sizeof(char),
6250 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00006251
6252 // If the function is defined as a builtin macro, do not show macro
6253 // expansion.
6254 SourceLocation SL = SizeOfArg->getExprLoc();
6255 SourceRange DSR = Dest->getSourceRange();
6256 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00006257 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00006258
6259 if (SM.isMacroArgExpansion(SL)) {
6260 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
6261 SL = SM.getSpellingLoc(SL);
6262 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
6263 SM.getSpellingLoc(DSR.getEnd()));
6264 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
6265 SM.getSpellingLoc(SSR.getEnd()));
6266 }
6267
Anna Zaksd08d9152012-05-30 23:14:52 +00006268 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006269 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00006270 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00006271 << PointeeTy
6272 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00006273 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00006274 << SSR);
6275 DiagRuntimeBehavior(SL, SizeOfArg,
6276 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
6277 << ActionIdx
6278 << SSR);
6279
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006280 break;
6281 }
6282 }
6283
6284 // Also check for cases where the sizeof argument is the exact same
6285 // type as the memory argument, and where it points to a user-defined
6286 // record type.
6287 if (SizeOfArgTy != QualType()) {
6288 if (PointeeTy->isRecordType() &&
6289 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
6290 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
6291 PDiag(diag::warn_sizeof_pointer_type_memaccess)
6292 << FnName << SizeOfArgTy << ArgIdx
6293 << PointeeTy << Dest->getSourceRange()
6294 << LenExpr->getSourceRange());
6295 break;
6296 }
Nico Weberc5e73862011-06-14 16:14:58 +00006297 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00006298 } else if (DestTy->isArrayType()) {
6299 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00006300 }
Nico Weberc5e73862011-06-14 16:14:58 +00006301
Nico Weberc44b35e2015-03-21 17:37:46 +00006302 if (PointeeTy == QualType())
6303 continue;
Anna Zaks22122702012-01-17 00:37:07 +00006304
Nico Weberc44b35e2015-03-21 17:37:46 +00006305 // Always complain about dynamic classes.
6306 bool IsContained;
6307 if (const CXXRecordDecl *ContainedRD =
6308 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00006309
Nico Weberc44b35e2015-03-21 17:37:46 +00006310 unsigned OperationType = 0;
6311 // "overwritten" if we're warning about the destination for any call
6312 // but memcmp; otherwise a verb appropriate to the call.
6313 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
6314 if (BId == Builtin::BImemcpy)
6315 OperationType = 1;
6316 else if(BId == Builtin::BImemmove)
6317 OperationType = 2;
6318 else if (BId == Builtin::BImemcmp)
6319 OperationType = 3;
6320 }
6321
John McCall31168b02011-06-15 23:02:42 +00006322 DiagRuntimeBehavior(
6323 Dest->getExprLoc(), Dest,
Nico Weberc44b35e2015-03-21 17:37:46 +00006324 PDiag(diag::warn_dyn_class_memaccess)
6325 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
6326 << FnName << IsContained << ContainedRD << OperationType
6327 << Call->getCallee()->getSourceRange());
6328 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
6329 BId != Builtin::BImemset)
6330 DiagRuntimeBehavior(
6331 Dest->getExprLoc(), Dest,
6332 PDiag(diag::warn_arc_object_memaccess)
6333 << ArgIdx << FnName << PointeeTy
6334 << Call->getCallee()->getSourceRange());
6335 else
6336 continue;
6337
6338 DiagRuntimeBehavior(
6339 Dest->getExprLoc(), Dest,
6340 PDiag(diag::note_bad_memaccess_silence)
6341 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
6342 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006343 }
6344}
6345
Ted Kremenek6865f772011-08-18 20:55:45 +00006346// A little helper routine: ignore addition and subtraction of integer literals.
6347// This intentionally does not ignore all integer constant expressions because
6348// we don't want to remove sizeof().
6349static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
6350 Ex = Ex->IgnoreParenCasts();
6351
6352 for (;;) {
6353 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
6354 if (!BO || !BO->isAdditiveOp())
6355 break;
6356
6357 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
6358 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
6359
6360 if (isa<IntegerLiteral>(RHS))
6361 Ex = LHS;
6362 else if (isa<IntegerLiteral>(LHS))
6363 Ex = RHS;
6364 else
6365 break;
6366 }
6367
6368 return Ex;
6369}
6370
Anna Zaks13b08572012-08-08 21:42:23 +00006371static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
6372 ASTContext &Context) {
6373 // Only handle constant-sized or VLAs, but not flexible members.
6374 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
6375 // Only issue the FIXIT for arrays of size > 1.
6376 if (CAT->getSize().getSExtValue() <= 1)
6377 return false;
6378 } else if (!Ty->isVariableArrayType()) {
6379 return false;
6380 }
6381 return true;
6382}
6383
Ted Kremenek6865f772011-08-18 20:55:45 +00006384// Warn if the user has made the 'size' argument to strlcpy or strlcat
6385// be the size of the source, instead of the destination.
6386void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
6387 IdentifierInfo *FnName) {
6388
6389 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00006390 unsigned NumArgs = Call->getNumArgs();
6391 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00006392 return;
6393
6394 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
6395 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00006396 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00006397
6398 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
6399 Call->getLocStart(), Call->getRParenLoc()))
6400 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00006401
6402 // Look for 'strlcpy(dst, x, sizeof(x))'
6403 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
6404 CompareWithSrc = Ex;
6405 else {
6406 // Look for 'strlcpy(dst, x, strlen(x))'
6407 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00006408 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
6409 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00006410 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
6411 }
6412 }
6413
6414 if (!CompareWithSrc)
6415 return;
6416
6417 // Determine if the argument to sizeof/strlen is equal to the source
6418 // argument. In principle there's all kinds of things you could do
6419 // here, for instance creating an == expression and evaluating it with
6420 // EvaluateAsBooleanCondition, but this uses a more direct technique:
6421 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
6422 if (!SrcArgDRE)
6423 return;
6424
6425 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
6426 if (!CompareWithSrcDRE ||
6427 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
6428 return;
6429
6430 const Expr *OriginalSizeArg = Call->getArg(2);
6431 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
6432 << OriginalSizeArg->getSourceRange() << FnName;
6433
6434 // Output a FIXIT hint if the destination is an array (rather than a
6435 // pointer to an array). This could be enhanced to handle some
6436 // pointers if we know the actual size, like if DstArg is 'array+2'
6437 // we could say 'sizeof(array)-2'.
6438 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00006439 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00006440 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00006441
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00006442 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00006443 llvm::raw_svector_ostream OS(sizeString);
6444 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00006445 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00006446 OS << ")";
6447
6448 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
6449 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
6450 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00006451}
6452
Anna Zaks314cd092012-02-01 19:08:57 +00006453/// Check if two expressions refer to the same declaration.
6454static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
6455 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
6456 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
6457 return D1->getDecl() == D2->getDecl();
6458 return false;
6459}
6460
6461static const Expr *getStrlenExprArg(const Expr *E) {
6462 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
6463 const FunctionDecl *FD = CE->getDirectCallee();
6464 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00006465 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00006466 return CE->getArg(0)->IgnoreParenCasts();
6467 }
Craig Topperc3ec1492014-05-26 06:22:03 +00006468 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00006469}
6470
6471// Warn on anti-patterns as the 'size' argument to strncat.
6472// The correct size argument should look like following:
6473// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
6474void Sema::CheckStrncatArguments(const CallExpr *CE,
6475 IdentifierInfo *FnName) {
6476 // Don't crash if the user has the wrong number of arguments.
6477 if (CE->getNumArgs() < 3)
6478 return;
6479 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
6480 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
6481 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
6482
Nico Weber0e6daef2013-12-26 23:38:39 +00006483 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
6484 CE->getRParenLoc()))
6485 return;
6486
Anna Zaks314cd092012-02-01 19:08:57 +00006487 // Identify common expressions, which are wrongly used as the size argument
6488 // to strncat and may lead to buffer overflows.
6489 unsigned PatternType = 0;
6490 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
6491 // - sizeof(dst)
6492 if (referToTheSameDecl(SizeOfArg, DstArg))
6493 PatternType = 1;
6494 // - sizeof(src)
6495 else if (referToTheSameDecl(SizeOfArg, SrcArg))
6496 PatternType = 2;
6497 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
6498 if (BE->getOpcode() == BO_Sub) {
6499 const Expr *L = BE->getLHS()->IgnoreParenCasts();
6500 const Expr *R = BE->getRHS()->IgnoreParenCasts();
6501 // - sizeof(dst) - strlen(dst)
6502 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
6503 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
6504 PatternType = 1;
6505 // - sizeof(src) - (anything)
6506 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
6507 PatternType = 2;
6508 }
6509 }
6510
6511 if (PatternType == 0)
6512 return;
6513
Anna Zaks5069aa32012-02-03 01:27:37 +00006514 // Generate the diagnostic.
6515 SourceLocation SL = LenArg->getLocStart();
6516 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00006517 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00006518
6519 // If the function is defined as a builtin macro, do not show macro expansion.
6520 if (SM.isMacroArgExpansion(SL)) {
6521 SL = SM.getSpellingLoc(SL);
6522 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
6523 SM.getSpellingLoc(SR.getEnd()));
6524 }
6525
Anna Zaks13b08572012-08-08 21:42:23 +00006526 // Check if the destination is an array (rather than a pointer to an array).
6527 QualType DstTy = DstArg->getType();
6528 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
6529 Context);
6530 if (!isKnownSizeArray) {
6531 if (PatternType == 1)
6532 Diag(SL, diag::warn_strncat_wrong_size) << SR;
6533 else
6534 Diag(SL, diag::warn_strncat_src_size) << SR;
6535 return;
6536 }
6537
Anna Zaks314cd092012-02-01 19:08:57 +00006538 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00006539 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00006540 else
Anna Zaks5069aa32012-02-03 01:27:37 +00006541 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00006542
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00006543 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00006544 llvm::raw_svector_ostream OS(sizeString);
6545 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00006546 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00006547 OS << ") - ";
6548 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00006549 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00006550 OS << ") - 1";
6551
Anna Zaks5069aa32012-02-03 01:27:37 +00006552 Diag(SL, diag::note_strncat_wrong_size)
6553 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00006554}
6555
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006556//===--- CHECK: Return Address of Stack Variable --------------------------===//
6557
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006558static const Expr *EvalVal(const Expr *E,
6559 SmallVectorImpl<const DeclRefExpr *> &refVars,
6560 const Decl *ParentDecl);
6561static const Expr *EvalAddr(const Expr *E,
6562 SmallVectorImpl<const DeclRefExpr *> &refVars,
6563 const Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006564
6565/// CheckReturnStackAddr - Check if a return statement returns the address
6566/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006567static void
6568CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
6569 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00006570
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006571 const Expr *stackE = nullptr;
6572 SmallVector<const DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006573
6574 // Perform checking for returned stack addresses, local blocks,
6575 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00006576 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006577 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006578 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00006579 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006580 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006581 }
6582
Craig Topperc3ec1492014-05-26 06:22:03 +00006583 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006584 return; // Nothing suspicious was found.
6585
Richard Trieu81b6c562016-08-05 23:24:47 +00006586 // Parameters are initalized in the calling scope, so taking the address
6587 // of a parameter reference doesn't need a warning.
6588 for (auto *DRE : refVars)
6589 if (isa<ParmVarDecl>(DRE->getDecl()))
6590 return;
6591
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006592 SourceLocation diagLoc;
6593 SourceRange diagRange;
6594 if (refVars.empty()) {
6595 diagLoc = stackE->getLocStart();
6596 diagRange = stackE->getSourceRange();
6597 } else {
6598 // We followed through a reference variable. 'stackE' contains the
6599 // problematic expression but we will warn at the return statement pointing
6600 // at the reference variable. We will later display the "trail" of
6601 // reference variables using notes.
6602 diagLoc = refVars[0]->getLocStart();
6603 diagRange = refVars[0]->getSourceRange();
6604 }
6605
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006606 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
6607 // address of local var
Craig Topperda7b27f2015-11-17 05:40:09 +00006608 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006609 << DR->getDecl()->getDeclName() << diagRange;
6610 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006611 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006612 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006613 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006614 } else { // local temporary.
Richard Trieu81b6c562016-08-05 23:24:47 +00006615 // If there is an LValue->RValue conversion, then the value of the
6616 // reference type is used, not the reference.
6617 if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
6618 if (ICE->getCastKind() == CK_LValueToRValue) {
6619 return;
6620 }
6621 }
Craig Topperda7b27f2015-11-17 05:40:09 +00006622 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
6623 << lhsType->isReferenceType() << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006624 }
6625
6626 // Display the "trail" of reference variables that we followed until we
6627 // found the problematic expression using notes.
6628 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006629 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006630 // If this var binds to another reference var, show the range of the next
6631 // var, otherwise the var binds to the problematic expression, in which case
6632 // show the range of the expression.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006633 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
6634 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006635 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
6636 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006637 }
6638}
6639
6640/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
6641/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006642/// to a location on the stack, a local block, an address of a label, or a
6643/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006644/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006645/// encounter a subexpression that (1) clearly does not lead to one of the
6646/// above problematic expressions (2) is something we cannot determine leads to
6647/// a problematic expression based on such local checking.
6648///
6649/// Both EvalAddr and EvalVal follow through reference variables to evaluate
6650/// the expression that they point to. Such variables are added to the
6651/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006652///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00006653/// EvalAddr processes expressions that are pointers that are used as
6654/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006655/// At the base case of the recursion is a check for the above problematic
6656/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006657///
6658/// This implementation handles:
6659///
6660/// * pointer-to-pointer casts
6661/// * implicit conversions from array references to pointers
6662/// * taking the address of fields
6663/// * arbitrary interplay between "&" and "*" operators
6664/// * pointer arithmetic from an address of a stack variable
6665/// * taking the address of an array element where the array is on the stack
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006666static const Expr *EvalAddr(const Expr *E,
6667 SmallVectorImpl<const DeclRefExpr *> &refVars,
6668 const Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006669 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00006670 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006671
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006672 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00006673 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00006674 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006675 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00006676 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00006677
Peter Collingbourne91147592011-04-15 00:35:48 +00006678 E = E->IgnoreParens();
6679
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006680 // Our "symbolic interpreter" is just a dispatch off the currently
6681 // viewed AST node. We then recursively traverse the AST by calling
6682 // EvalAddr and EvalVal appropriately.
6683 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006684 case Stmt::DeclRefExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006685 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006686
Richard Smith40f08eb2014-01-30 22:05:38 +00006687 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00006688 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00006689 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00006690
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006691 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006692 // If this is a reference variable, follow through to the expression that
6693 // it points to.
6694 if (V->hasLocalStorage() &&
6695 V->getType()->isReferenceType() && V->hasInit()) {
6696 // Add the reference variable to the "trail".
6697 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006698 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006699 }
6700
Craig Topperc3ec1492014-05-26 06:22:03 +00006701 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006702 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006703
Chris Lattner934edb22007-12-28 05:31:15 +00006704 case Stmt::UnaryOperatorClass: {
6705 // The only unary operator that make sense to handle here
6706 // is AddrOf. All others don't make sense as pointers.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006707 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00006708
John McCalle3027922010-08-25 11:45:40 +00006709 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006710 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006711 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006712 }
Mike Stump11289f42009-09-09 15:08:12 +00006713
Chris Lattner934edb22007-12-28 05:31:15 +00006714 case Stmt::BinaryOperatorClass: {
6715 // Handle pointer arithmetic. All other binary operators are not valid
6716 // in this context.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006717 const BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00006718 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00006719
John McCalle3027922010-08-25 11:45:40 +00006720 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00006721 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00006722
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006723 const Expr *Base = B->getLHS();
Chris Lattner934edb22007-12-28 05:31:15 +00006724
6725 // Determine which argument is the real pointer base. It could be
6726 // the RHS argument instead of the LHS.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006727 if (!Base->getType()->isPointerType())
6728 Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00006729
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006730 assert(Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006731 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00006732 }
Steve Naroff2752a172008-09-10 19:17:48 +00006733
Chris Lattner934edb22007-12-28 05:31:15 +00006734 // For conditional operators we need to see if either the LHS or RHS are
6735 // valid DeclRefExpr*s. If one of them is valid, we return it.
6736 case Stmt::ConditionalOperatorClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006737 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00006738
Chris Lattner934edb22007-12-28 05:31:15 +00006739 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006740 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006741 if (const Expr *LHSExpr = C->getLHS()) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006742 // In C++, we can have a throw-expression, which has 'void' type.
6743 if (!LHSExpr->getType()->isVoidType())
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006744 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00006745 return LHS;
6746 }
Chris Lattner934edb22007-12-28 05:31:15 +00006747
Douglas Gregor270b2ef2010-10-21 16:21:08 +00006748 // In C++, we can have a throw-expression, which has 'void' type.
6749 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00006750 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00006751
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006752 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00006753 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006754
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006755 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00006756 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006757 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00006758 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006759
6760 case Stmt::AddrLabelExprClass:
6761 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00006762
John McCall28fc7092011-11-10 05:35:25 +00006763 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006764 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
6765 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00006766
Ted Kremenekc3b4c522008-08-07 00:49:01 +00006767 // For casts, we need to handle conversions from arrays to
6768 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00006769 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00006770 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00006771 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00006772 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00006773 case Stmt::CXXStaticCastExprClass:
6774 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00006775 case Stmt::CXXConstCastExprClass:
6776 case Stmt::CXXReinterpretCastExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006777 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Eli Friedman8195ad72012-02-23 23:04:32 +00006778 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00006779 case CK_LValueToRValue:
6780 case CK_NoOp:
6781 case CK_BaseToDerived:
6782 case CK_DerivedToBase:
6783 case CK_UncheckedDerivedToBase:
6784 case CK_Dynamic:
6785 case CK_CPointerToObjCPointerCast:
6786 case CK_BlockPointerToObjCPointerCast:
6787 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006788 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00006789
6790 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006791 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00006792
Richard Trieudadefde2014-07-02 04:39:38 +00006793 case CK_BitCast:
6794 if (SubExpr->getType()->isAnyPointerType() ||
6795 SubExpr->getType()->isBlockPointerType() ||
6796 SubExpr->getType()->isObjCQualifiedIdType())
6797 return EvalAddr(SubExpr, refVars, ParentDecl);
6798 else
6799 return nullptr;
6800
Eli Friedman8195ad72012-02-23 23:04:32 +00006801 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00006802 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00006803 }
Chris Lattner934edb22007-12-28 05:31:15 +00006804 }
Mike Stump11289f42009-09-09 15:08:12 +00006805
Douglas Gregorfe314812011-06-21 17:03:29 +00006806 case Stmt::MaterializeTemporaryExprClass:
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006807 if (const Expr *Result =
6808 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
6809 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00006810 return Result;
Douglas Gregorfe314812011-06-21 17:03:29 +00006811 return E;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006812
Chris Lattner934edb22007-12-28 05:31:15 +00006813 // Everything else: we simply don't reason about them.
6814 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00006815 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00006816 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006817}
Mike Stump11289f42009-09-09 15:08:12 +00006818
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006819/// EvalVal - This function is complements EvalAddr in the mutual recursion.
6820/// See the comments for EvalAddr for more details.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006821static const Expr *EvalVal(const Expr *E,
6822 SmallVectorImpl<const DeclRefExpr *> &refVars,
6823 const Decl *ParentDecl) {
6824 do {
6825 // We should only be called for evaluating non-pointer expressions, or
6826 // expressions with a pointer type that are not used as references but
6827 // instead
6828 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00006829
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006830 // Our "symbolic interpreter" is just a dispatch off the currently
6831 // viewed AST node. We then recursively traverse the AST by calling
6832 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00006833
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006834 E = E->IgnoreParens();
6835 switch (E->getStmtClass()) {
6836 case Stmt::ImplicitCastExprClass: {
6837 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
6838 if (IE->getValueKind() == VK_LValue) {
6839 E = IE->getSubExpr();
6840 continue;
6841 }
Craig Topperc3ec1492014-05-26 06:22:03 +00006842 return nullptr;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006843 }
Richard Smith40f08eb2014-01-30 22:05:38 +00006844
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006845 case Stmt::ExprWithCleanupsClass:
6846 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
6847 ParentDecl);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006848
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006849 case Stmt::DeclRefExprClass: {
6850 // When we hit a DeclRefExpr we are looking at code that refers to a
6851 // variable's name. If it's not a reference variable we check if it has
6852 // local storage within the function, and if so, return the expression.
6853 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
6854
6855 // If we leave the immediate function, the lifetime isn't about to end.
6856 if (DR->refersToEnclosingVariableOrCapture())
6857 return nullptr;
6858
6859 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
6860 // Check if it refers to itself, e.g. "int& i = i;".
6861 if (V == ParentDecl)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006862 return DR;
6863
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006864 if (V->hasLocalStorage()) {
6865 if (!V->getType()->isReferenceType())
6866 return DR;
6867
6868 // Reference variable, follow through to the expression that
6869 // it points to.
6870 if (V->hasInit()) {
6871 // Add the reference variable to the "trail".
6872 refVars.push_back(DR);
6873 return EvalVal(V->getInit(), refVars, V);
6874 }
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006875 }
6876 }
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006877
6878 return nullptr;
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006879 }
Mike Stump11289f42009-09-09 15:08:12 +00006880
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006881 case Stmt::UnaryOperatorClass: {
6882 // The only unary operator that make sense to handle here
6883 // is Deref. All others don't resolve to a "name." This includes
6884 // handling all sorts of rvalues passed to a unary operator.
6885 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00006886
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006887 if (U->getOpcode() == UO_Deref)
6888 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Mike Stump11289f42009-09-09 15:08:12 +00006889
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006890 return nullptr;
6891 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006892
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006893 case Stmt::ArraySubscriptExprClass: {
6894 // Array subscripts are potential references to data on the stack. We
6895 // retrieve the DeclRefExpr* for the array variable if it indeed
6896 // has local storage.
Saleem Abdulrasoolcfd45532016-02-15 01:51:24 +00006897 const auto *ASE = cast<ArraySubscriptExpr>(E);
6898 if (ASE->isTypeDependent())
6899 return nullptr;
6900 return EvalAddr(ASE->getBase(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006901 }
Mike Stump11289f42009-09-09 15:08:12 +00006902
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006903 case Stmt::OMPArraySectionExprClass: {
6904 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
6905 ParentDecl);
6906 }
Mike Stump11289f42009-09-09 15:08:12 +00006907
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006908 case Stmt::ConditionalOperatorClass: {
6909 // For conditional operators we need to see if either the LHS or RHS are
6910 // non-NULL Expr's. If one is non-NULL, we return it.
6911 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Alexey Bataev1a3320e2015-08-25 14:24:04 +00006912
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006913 // Handle the GNU extension for missing LHS.
6914 if (const Expr *LHSExpr = C->getLHS()) {
6915 // In C++, we can have a throw-expression, which has 'void' type.
6916 if (!LHSExpr->getType()->isVoidType())
6917 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
6918 return LHS;
6919 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006920
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006921 // In C++, we can have a throw-expression, which has 'void' type.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006922 if (C->getRHS()->getType()->isVoidType())
6923 return nullptr;
6924
6925 return EvalVal(C->getRHS(), refVars, ParentDecl);
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006926 }
6927
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006928 // Accesses to members are potential references to data on the stack.
6929 case Stmt::MemberExprClass: {
6930 const MemberExpr *M = cast<MemberExpr>(E);
Anders Carlsson801c5c72007-11-30 19:04:31 +00006931
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006932 // Check for indirect access. We only want direct field accesses.
6933 if (M->isArrow())
6934 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00006935
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006936 // Check whether the member type is itself a reference, in which case
6937 // we're not going to refer to the member, but to what the member refers
6938 // to.
6939 if (M->getMemberDecl()->getType()->isReferenceType())
6940 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00006941
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006942 return EvalVal(M->getBase(), refVars, ParentDecl);
6943 }
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00006944
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006945 case Stmt::MaterializeTemporaryExprClass:
6946 if (const Expr *Result =
6947 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
6948 refVars, ParentDecl))
6949 return Result;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006950 return E;
6951
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006952 default:
6953 // Check that we don't return or take the address of a reference to a
6954 // temporary. This is only useful in C++.
6955 if (!E->isTypeDependent() && E->isRValue())
6956 return E;
6957
6958 // Everything else: we simply don't reason about them.
6959 return nullptr;
6960 }
6961 } while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006962}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006963
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006964void
6965Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
6966 SourceLocation ReturnLoc,
6967 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00006968 const AttrVec *Attrs,
6969 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006970 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
6971
6972 // Check if the return value is null but should not be.
Douglas Gregorb4866e82015-06-19 18:13:19 +00006973 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
6974 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
Benjamin Kramerae852a62014-02-23 14:34:50 +00006975 CheckNonNullExpr(*this, RetValExp))
6976 Diag(ReturnLoc, diag::warn_null_ret)
6977 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00006978
6979 // C++11 [basic.stc.dynamic.allocation]p4:
6980 // If an allocation function declared with a non-throwing
6981 // exception-specification fails to allocate storage, it shall return
6982 // a null pointer. Any other allocation function that fails to allocate
6983 // storage shall indicate failure only by throwing an exception [...]
6984 if (FD) {
6985 OverloadedOperatorKind Op = FD->getOverloadedOperator();
6986 if (Op == OO_New || Op == OO_Array_New) {
6987 const FunctionProtoType *Proto
6988 = FD->getType()->castAs<FunctionProtoType>();
6989 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
6990 CheckNonNullExpr(*this, RetValExp))
6991 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
6992 << FD << getLangOpts().CPlusPlus11;
6993 }
6994 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006995}
6996
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006997//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
6998
6999/// Check for comparisons of floating point operands using != and ==.
7000/// Issue a warning if these are no self-comparisons, as they are not likely
7001/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00007002void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00007003 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
7004 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007005
7006 // Special case: check for x == x (which is OK).
7007 // Do not emit warnings for such cases.
7008 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
7009 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
7010 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00007011 return;
Mike Stump11289f42009-09-09 15:08:12 +00007012
Ted Kremenekeda40e22007-11-29 00:59:04 +00007013 // Special case: check for comparisons against literals that can be exactly
7014 // represented by APFloat. In such cases, do not emit a warning. This
7015 // is a heuristic: often comparison against such literals are used to
7016 // detect if a value in a variable has not changed. This clearly can
7017 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00007018 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
7019 if (FLL->isExact())
7020 return;
7021 } else
7022 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
7023 if (FLR->isExact())
7024 return;
Mike Stump11289f42009-09-09 15:08:12 +00007025
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007026 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00007027 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00007028 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00007029 return;
Mike Stump11289f42009-09-09 15:08:12 +00007030
David Blaikie1f4ff152012-07-16 20:47:22 +00007031 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00007032 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00007033 return;
Mike Stump11289f42009-09-09 15:08:12 +00007034
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007035 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00007036 Diag(Loc, diag::warn_floatingpoint_eq)
7037 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007038}
John McCallca01b222010-01-04 23:21:16 +00007039
John McCall70aa5392010-01-06 05:24:50 +00007040//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
7041//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00007042
John McCall70aa5392010-01-06 05:24:50 +00007043namespace {
John McCallca01b222010-01-04 23:21:16 +00007044
John McCall70aa5392010-01-06 05:24:50 +00007045/// Structure recording the 'active' range of an integer-valued
7046/// expression.
7047struct IntRange {
7048 /// The number of bits active in the int.
7049 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00007050
John McCall70aa5392010-01-06 05:24:50 +00007051 /// True if the int is known not to have negative values.
7052 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00007053
John McCall70aa5392010-01-06 05:24:50 +00007054 IntRange(unsigned Width, bool NonNegative)
7055 : Width(Width), NonNegative(NonNegative)
7056 {}
John McCallca01b222010-01-04 23:21:16 +00007057
John McCall817d4af2010-11-10 23:38:19 +00007058 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00007059 static IntRange forBoolType() {
7060 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00007061 }
7062
John McCall817d4af2010-11-10 23:38:19 +00007063 /// Returns the range of an opaque value of the given integral type.
7064 static IntRange forValueOfType(ASTContext &C, QualType T) {
7065 return forValueOfCanonicalType(C,
7066 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00007067 }
7068
John McCall817d4af2010-11-10 23:38:19 +00007069 /// Returns the range of an opaque value of a canonical integral type.
7070 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00007071 assert(T->isCanonicalUnqualified());
7072
7073 if (const VectorType *VT = dyn_cast<VectorType>(T))
7074 T = VT->getElementType().getTypePtr();
7075 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
7076 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00007077 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
7078 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00007079
David Majnemer6a426652013-06-07 22:07:20 +00007080 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00007081 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00007082 EnumDecl *Enum = ET->getDecl();
7083 if (!Enum->isCompleteDefinition())
7084 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00007085
David Majnemer6a426652013-06-07 22:07:20 +00007086 unsigned NumPositive = Enum->getNumPositiveBits();
7087 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00007088
David Majnemer6a426652013-06-07 22:07:20 +00007089 if (NumNegative == 0)
7090 return IntRange(NumPositive, true/*NonNegative*/);
7091 else
7092 return IntRange(std::max(NumPositive + 1, NumNegative),
7093 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00007094 }
John McCall70aa5392010-01-06 05:24:50 +00007095
7096 const BuiltinType *BT = cast<BuiltinType>(T);
7097 assert(BT->isInteger());
7098
7099 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
7100 }
7101
John McCall817d4af2010-11-10 23:38:19 +00007102 /// Returns the "target" range of a canonical integral type, i.e.
7103 /// the range of values expressible in the type.
7104 ///
7105 /// This matches forValueOfCanonicalType except that enums have the
7106 /// full range of their type, not the range of their enumerators.
7107 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
7108 assert(T->isCanonicalUnqualified());
7109
7110 if (const VectorType *VT = dyn_cast<VectorType>(T))
7111 T = VT->getElementType().getTypePtr();
7112 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
7113 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00007114 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
7115 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00007116 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00007117 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00007118
7119 const BuiltinType *BT = cast<BuiltinType>(T);
7120 assert(BT->isInteger());
7121
7122 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
7123 }
7124
7125 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00007126 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00007127 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00007128 L.NonNegative && R.NonNegative);
7129 }
7130
John McCall817d4af2010-11-10 23:38:19 +00007131 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00007132 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00007133 return IntRange(std::min(L.Width, R.Width),
7134 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00007135 }
7136};
7137
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007138IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00007139 if (value.isSigned() && value.isNegative())
7140 return IntRange(value.getMinSignedBits(), false);
7141
7142 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00007143 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00007144
7145 // isNonNegative() just checks the sign bit without considering
7146 // signedness.
7147 return IntRange(value.getActiveBits(), true);
7148}
7149
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007150IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
7151 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00007152 if (result.isInt())
7153 return GetValueRange(C, result.getInt(), MaxWidth);
7154
7155 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00007156 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
7157 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
7158 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
7159 R = IntRange::join(R, El);
7160 }
John McCall70aa5392010-01-06 05:24:50 +00007161 return R;
7162 }
7163
7164 if (result.isComplexInt()) {
7165 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
7166 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
7167 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00007168 }
7169
7170 // This can happen with lossless casts to intptr_t of "based" lvalues.
7171 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00007172 // FIXME: The only reason we need to pass the type in here is to get
7173 // the sign right on this one case. It would be nice if APValue
7174 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007175 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00007176 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00007177}
John McCall70aa5392010-01-06 05:24:50 +00007178
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007179QualType GetExprType(const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00007180 QualType Ty = E->getType();
7181 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
7182 Ty = AtomicRHS->getValueType();
7183 return Ty;
7184}
7185
John McCall70aa5392010-01-06 05:24:50 +00007186/// Pseudo-evaluate the given integer expression, estimating the
7187/// range of values it might take.
7188///
7189/// \param MaxWidth - the width to which the value will be truncated
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007190IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00007191 E = E->IgnoreParens();
7192
7193 // Try a full evaluation first.
7194 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00007195 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00007196 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00007197
7198 // I think we only want to look through implicit casts here; if the
7199 // user has an explicit widening cast, we should treat the value as
7200 // being of the new, wider type.
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007201 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00007202 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00007203 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
7204
Eli Friedmane6d33952013-07-08 20:20:06 +00007205 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00007206
George Burgess IVdf1ed002016-01-13 01:52:39 +00007207 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
7208 CE->getCastKind() == CK_BooleanToSignedIntegral;
John McCall2ce81ad2010-01-06 22:07:33 +00007209
John McCall70aa5392010-01-06 05:24:50 +00007210 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00007211 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00007212 return OutputTypeRange;
7213
7214 IntRange SubRange
7215 = GetExprRange(C, CE->getSubExpr(),
7216 std::min(MaxWidth, OutputTypeRange.Width));
7217
7218 // Bail out if the subexpr's range is as wide as the cast type.
7219 if (SubRange.Width >= OutputTypeRange.Width)
7220 return OutputTypeRange;
7221
7222 // Otherwise, we take the smaller width, and we're non-negative if
7223 // either the output type or the subexpr is.
7224 return IntRange(SubRange.Width,
7225 SubRange.NonNegative || OutputTypeRange.NonNegative);
7226 }
7227
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007228 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00007229 // If we can fold the condition, just take that operand.
7230 bool CondResult;
7231 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
7232 return GetExprRange(C, CondResult ? CO->getTrueExpr()
7233 : CO->getFalseExpr(),
7234 MaxWidth);
7235
7236 // Otherwise, conservatively merge.
7237 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
7238 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
7239 return IntRange::join(L, R);
7240 }
7241
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007242 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00007243 switch (BO->getOpcode()) {
7244
7245 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00007246 case BO_LAnd:
7247 case BO_LOr:
7248 case BO_LT:
7249 case BO_GT:
7250 case BO_LE:
7251 case BO_GE:
7252 case BO_EQ:
7253 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00007254 return IntRange::forBoolType();
7255
John McCallc3688382011-07-13 06:35:24 +00007256 // The type of the assignments is the type of the LHS, so the RHS
7257 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00007258 case BO_MulAssign:
7259 case BO_DivAssign:
7260 case BO_RemAssign:
7261 case BO_AddAssign:
7262 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00007263 case BO_XorAssign:
7264 case BO_OrAssign:
7265 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00007266 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00007267
John McCallc3688382011-07-13 06:35:24 +00007268 // Simple assignments just pass through the RHS, which will have
7269 // been coerced to the LHS type.
7270 case BO_Assign:
7271 // TODO: bitfields?
7272 return GetExprRange(C, BO->getRHS(), MaxWidth);
7273
John McCall70aa5392010-01-06 05:24:50 +00007274 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00007275 case BO_PtrMemD:
7276 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00007277 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00007278
John McCall2ce81ad2010-01-06 22:07:33 +00007279 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00007280 case BO_And:
7281 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00007282 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
7283 GetExprRange(C, BO->getRHS(), MaxWidth));
7284
John McCall70aa5392010-01-06 05:24:50 +00007285 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00007286 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00007287 // ...except that we want to treat '1 << (blah)' as logically
7288 // positive. It's an important idiom.
7289 if (IntegerLiteral *I
7290 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
7291 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00007292 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00007293 return IntRange(R.Width, /*NonNegative*/ true);
7294 }
7295 }
7296 // fallthrough
7297
John McCalle3027922010-08-25 11:45:40 +00007298 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00007299 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00007300
John McCall2ce81ad2010-01-06 22:07:33 +00007301 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00007302 case BO_Shr:
7303 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00007304 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
7305
7306 // If the shift amount is a positive constant, drop the width by
7307 // that much.
7308 llvm::APSInt shift;
7309 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
7310 shift.isNonNegative()) {
7311 unsigned zext = shift.getZExtValue();
7312 if (zext >= L.Width)
7313 L.Width = (L.NonNegative ? 0 : 1);
7314 else
7315 L.Width -= zext;
7316 }
7317
7318 return L;
7319 }
7320
7321 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00007322 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00007323 return GetExprRange(C, BO->getRHS(), MaxWidth);
7324
John McCall2ce81ad2010-01-06 22:07:33 +00007325 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00007326 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00007327 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00007328 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00007329 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00007330
John McCall51431812011-07-14 22:39:48 +00007331 // The width of a division result is mostly determined by the size
7332 // of the LHS.
7333 case BO_Div: {
7334 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00007335 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00007336 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
7337
7338 // If the divisor is constant, use that.
7339 llvm::APSInt divisor;
7340 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
7341 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
7342 if (log2 >= L.Width)
7343 L.Width = (L.NonNegative ? 0 : 1);
7344 else
7345 L.Width = std::min(L.Width - log2, MaxWidth);
7346 return L;
7347 }
7348
7349 // Otherwise, just use the LHS's width.
7350 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
7351 return IntRange(L.Width, L.NonNegative && R.NonNegative);
7352 }
7353
7354 // The result of a remainder can't be larger than the result of
7355 // either side.
7356 case BO_Rem: {
7357 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00007358 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00007359 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
7360 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
7361
7362 IntRange meet = IntRange::meet(L, R);
7363 meet.Width = std::min(meet.Width, MaxWidth);
7364 return meet;
7365 }
7366
7367 // The default behavior is okay for these.
7368 case BO_Mul:
7369 case BO_Add:
7370 case BO_Xor:
7371 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00007372 break;
7373 }
7374
John McCall51431812011-07-14 22:39:48 +00007375 // The default case is to treat the operation as if it were closed
7376 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00007377 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
7378 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
7379 return IntRange::join(L, R);
7380 }
7381
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007382 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00007383 switch (UO->getOpcode()) {
7384 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00007385 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00007386 return IntRange::forBoolType();
7387
7388 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00007389 case UO_Deref:
7390 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00007391 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00007392
7393 default:
7394 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
7395 }
7396 }
7397
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007398 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
Ted Kremeneka553fbf2013-10-14 18:55:27 +00007399 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
7400
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007401 if (const auto *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00007402 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00007403 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00007404
Eli Friedmane6d33952013-07-08 20:20:06 +00007405 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00007406}
John McCall263a48b2010-01-04 23:31:57 +00007407
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007408IntRange GetExprRange(ASTContext &C, const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00007409 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00007410}
7411
John McCall263a48b2010-01-04 23:31:57 +00007412/// Checks whether the given value, which currently has the given
7413/// source semantics, has the same value when coerced through the
7414/// target semantics.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007415bool IsSameFloatAfterCast(const llvm::APFloat &value,
7416 const llvm::fltSemantics &Src,
7417 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00007418 llvm::APFloat truncated = value;
7419
7420 bool ignored;
7421 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
7422 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
7423
7424 return truncated.bitwiseIsEqual(value);
7425}
7426
7427/// Checks whether the given value, which currently has the given
7428/// source semantics, has the same value when coerced through the
7429/// target semantics.
7430///
7431/// The value might be a vector of floats (or a complex number).
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007432bool IsSameFloatAfterCast(const APValue &value,
7433 const llvm::fltSemantics &Src,
7434 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00007435 if (value.isFloat())
7436 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
7437
7438 if (value.isVector()) {
7439 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
7440 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
7441 return false;
7442 return true;
7443 }
7444
7445 assert(value.isComplexFloat());
7446 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
7447 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
7448}
7449
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007450void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007451
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007452bool IsZero(Sema &S, Expr *E) {
Ted Kremenek6274be42010-09-23 21:43:44 +00007453 // Suppress cases where we are comparing against an enum constant.
7454 if (const DeclRefExpr *DR =
7455 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
7456 if (isa<EnumConstantDecl>(DR->getDecl()))
7457 return false;
7458
7459 // Suppress cases where the '0' value is expanded from a macro.
7460 if (E->getLocStart().isMacroID())
7461 return false;
7462
John McCallcc7e5bf2010-05-06 08:58:33 +00007463 llvm::APSInt Value;
7464 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
7465}
7466
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007467bool HasEnumType(Expr *E) {
John McCall2551c1b2010-10-06 00:25:24 +00007468 // Strip off implicit integral promotions.
7469 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00007470 if (ICE->getCastKind() != CK_IntegralCast &&
7471 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00007472 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00007473 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00007474 }
7475
7476 return E->getType()->isEnumeralType();
7477}
7478
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007479void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00007480 // Disable warning in template instantiations.
7481 if (!S.ActiveTemplateInstantiations.empty())
7482 return;
7483
John McCalle3027922010-08-25 11:45:40 +00007484 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00007485 if (E->isValueDependent())
7486 return;
7487
John McCalle3027922010-08-25 11:45:40 +00007488 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007489 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00007490 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00007491 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00007492 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007493 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00007494 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00007495 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00007496 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007497 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00007498 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00007499 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00007500 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007501 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00007502 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00007503 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
7504 }
7505}
7506
Benjamin Kramer7320b992016-06-15 14:20:56 +00007507void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E, Expr *Constant,
7508 Expr *Other, const llvm::APSInt &Value,
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007509 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00007510 // Disable warning in template instantiations.
7511 if (!S.ActiveTemplateInstantiations.empty())
7512 return;
7513
Richard Trieu0f097742014-04-04 04:13:47 +00007514 // TODO: Investigate using GetExprRange() to get tighter bounds
7515 // on the bit ranges.
7516 QualType OtherT = Other->getType();
David Majnemer7800f1f2015-05-23 01:32:17 +00007517 if (const auto *AT = OtherT->getAs<AtomicType>())
Justin Bogner4f42fc42014-07-21 18:01:53 +00007518 OtherT = AT->getValueType();
Richard Trieu0f097742014-04-04 04:13:47 +00007519 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
7520 unsigned OtherWidth = OtherRange.Width;
7521
7522 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
7523
Richard Trieu560910c2012-11-14 22:50:24 +00007524 // 0 values are handled later by CheckTrivialUnsignedComparison().
Richard Trieu0f097742014-04-04 04:13:47 +00007525 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00007526 return;
7527
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007528 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00007529 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00007530
Richard Trieu0f097742014-04-04 04:13:47 +00007531 // Used for diagnostic printout.
7532 enum {
7533 LiteralConstant = 0,
7534 CXXBoolLiteralTrue,
7535 CXXBoolLiteralFalse
7536 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00007537
Richard Trieu0f097742014-04-04 04:13:47 +00007538 if (!OtherIsBooleanType) {
7539 QualType ConstantT = Constant->getType();
7540 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00007541
Richard Trieu0f097742014-04-04 04:13:47 +00007542 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
7543 return;
7544 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
7545 "comparison with non-integer type");
7546
7547 bool ConstantSigned = ConstantT->isSignedIntegerType();
7548 bool CommonSigned = CommonT->isSignedIntegerType();
7549
7550 bool EqualityOnly = false;
7551
7552 if (CommonSigned) {
7553 // The common type is signed, therefore no signed to unsigned conversion.
7554 if (!OtherRange.NonNegative) {
7555 // Check that the constant is representable in type OtherT.
7556 if (ConstantSigned) {
7557 if (OtherWidth >= Value.getMinSignedBits())
7558 return;
7559 } else { // !ConstantSigned
7560 if (OtherWidth >= Value.getActiveBits() + 1)
7561 return;
7562 }
7563 } else { // !OtherSigned
7564 // Check that the constant is representable in type OtherT.
7565 // Negative values are out of range.
7566 if (ConstantSigned) {
7567 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
7568 return;
7569 } else { // !ConstantSigned
7570 if (OtherWidth >= Value.getActiveBits())
7571 return;
7572 }
Richard Trieu560910c2012-11-14 22:50:24 +00007573 }
Richard Trieu0f097742014-04-04 04:13:47 +00007574 } else { // !CommonSigned
7575 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00007576 if (OtherWidth >= Value.getActiveBits())
7577 return;
Craig Toppercf360162014-06-18 05:13:11 +00007578 } else { // OtherSigned
7579 assert(!ConstantSigned &&
7580 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00007581 // Check to see if the constant is representable in OtherT.
7582 if (OtherWidth > Value.getActiveBits())
7583 return;
7584 // Check to see if the constant is equivalent to a negative value
7585 // cast to CommonT.
7586 if (S.Context.getIntWidth(ConstantT) ==
7587 S.Context.getIntWidth(CommonT) &&
7588 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
7589 return;
7590 // The constant value rests between values that OtherT can represent
7591 // after conversion. Relational comparison still works, but equality
7592 // comparisons will be tautological.
7593 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00007594 }
7595 }
Richard Trieu0f097742014-04-04 04:13:47 +00007596
7597 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
7598
7599 if (op == BO_EQ || op == BO_NE) {
7600 IsTrue = op == BO_NE;
7601 } else if (EqualityOnly) {
7602 return;
7603 } else if (RhsConstant) {
7604 if (op == BO_GT || op == BO_GE)
7605 IsTrue = !PositiveConstant;
7606 else // op == BO_LT || op == BO_LE
7607 IsTrue = PositiveConstant;
7608 } else {
7609 if (op == BO_LT || op == BO_LE)
7610 IsTrue = !PositiveConstant;
7611 else // op == BO_GT || op == BO_GE
7612 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00007613 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00007614 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00007615 // Other isKnownToHaveBooleanValue
7616 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
7617 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
7618 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
7619
7620 static const struct LinkedConditions {
7621 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
7622 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
7623 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
7624 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
7625 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
7626 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
7627
7628 } TruthTable = {
7629 // Constant on LHS. | Constant on RHS. |
7630 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
7631 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
7632 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
7633 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
7634 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
7635 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
7636 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
7637 };
7638
7639 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
7640
7641 enum ConstantValue ConstVal = Zero;
7642 if (Value.isUnsigned() || Value.isNonNegative()) {
7643 if (Value == 0) {
7644 LiteralOrBoolConstant =
7645 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
7646 ConstVal = Zero;
7647 } else if (Value == 1) {
7648 LiteralOrBoolConstant =
7649 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
7650 ConstVal = One;
7651 } else {
7652 LiteralOrBoolConstant = LiteralConstant;
7653 ConstVal = GT_One;
7654 }
7655 } else {
7656 ConstVal = LT_Zero;
7657 }
7658
7659 CompareBoolWithConstantResult CmpRes;
7660
7661 switch (op) {
7662 case BO_LT:
7663 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
7664 break;
7665 case BO_GT:
7666 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
7667 break;
7668 case BO_LE:
7669 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
7670 break;
7671 case BO_GE:
7672 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
7673 break;
7674 case BO_EQ:
7675 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
7676 break;
7677 case BO_NE:
7678 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
7679 break;
7680 default:
7681 CmpRes = Unkwn;
7682 break;
7683 }
7684
7685 if (CmpRes == AFals) {
7686 IsTrue = false;
7687 } else if (CmpRes == ATrue) {
7688 IsTrue = true;
7689 } else {
7690 return;
7691 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007692 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00007693
7694 // If this is a comparison to an enum constant, include that
7695 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00007696 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00007697 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
7698 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
7699
7700 SmallString<64> PrettySourceValue;
7701 llvm::raw_svector_ostream OS(PrettySourceValue);
7702 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00007703 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00007704 else
7705 OS << Value;
7706
Richard Trieu0f097742014-04-04 04:13:47 +00007707 S.DiagRuntimeBehavior(
7708 E->getOperatorLoc(), E,
7709 S.PDiag(diag::warn_out_of_range_compare)
7710 << OS.str() << LiteralOrBoolConstant
7711 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
7712 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007713}
7714
John McCallcc7e5bf2010-05-06 08:58:33 +00007715/// Analyze the operands of the given comparison. Implements the
7716/// fallback case from AnalyzeComparison.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007717void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00007718 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
7719 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00007720}
John McCall263a48b2010-01-04 23:31:57 +00007721
John McCallca01b222010-01-04 23:21:16 +00007722/// \brief Implements -Wsign-compare.
7723///
Richard Trieu82402a02011-09-15 21:56:47 +00007724/// \param E the binary operator to check for warnings
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007725void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007726 // The type the comparison is being performed in.
7727 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00007728
7729 // Only analyze comparison operators where both sides have been converted to
7730 // the same type.
7731 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
7732 return AnalyzeImpConvsInComparison(S, E);
7733
7734 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00007735 if (E->isValueDependent())
7736 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00007737
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007738 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
7739 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007740
7741 bool IsComparisonConstant = false;
7742
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00007743 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007744 // of 'true' or 'false'.
7745 if (T->isIntegralType(S.Context)) {
7746 llvm::APSInt RHSValue;
7747 bool IsRHSIntegralLiteral =
7748 RHS->isIntegerConstantExpr(RHSValue, S.Context);
7749 llvm::APSInt LHSValue;
7750 bool IsLHSIntegralLiteral =
7751 LHS->isIntegerConstantExpr(LHSValue, S.Context);
7752 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
7753 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
7754 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
7755 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
7756 else
7757 IsComparisonConstant =
7758 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00007759 } else if (!T->hasUnsignedIntegerRepresentation())
7760 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007761
John McCallcc7e5bf2010-05-06 08:58:33 +00007762 // We don't do anything special if this isn't an unsigned integral
7763 // comparison: we're only interested in integral comparisons, and
7764 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00007765 //
7766 // We also don't care about value-dependent expressions or expressions
7767 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007768 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00007769 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007770
John McCallcc7e5bf2010-05-06 08:58:33 +00007771 // Check to see if one of the (unmodified) operands is of different
7772 // signedness.
7773 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00007774 if (LHS->getType()->hasSignedIntegerRepresentation()) {
7775 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00007776 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00007777 signedOperand = LHS;
7778 unsignedOperand = RHS;
7779 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
7780 signedOperand = RHS;
7781 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00007782 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00007783 CheckTrivialUnsignedComparison(S, E);
7784 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00007785 }
7786
John McCallcc7e5bf2010-05-06 08:58:33 +00007787 // Otherwise, calculate the effective range of the signed operand.
7788 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00007789
John McCallcc7e5bf2010-05-06 08:58:33 +00007790 // Go ahead and analyze implicit conversions in the operands. Note
7791 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00007792 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
7793 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00007794
John McCallcc7e5bf2010-05-06 08:58:33 +00007795 // If the signed range is non-negative, -Wsign-compare won't fire,
7796 // but we should still check for comparisons which are always true
7797 // or false.
7798 if (signedRange.NonNegative)
7799 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00007800
7801 // For (in)equality comparisons, if the unsigned operand is a
7802 // constant which cannot collide with a overflowed signed operand,
7803 // then reinterpreting the signed operand as unsigned will not
7804 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00007805 if (E->isEqualityOp()) {
7806 unsigned comparisonWidth = S.Context.getIntWidth(T);
7807 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00007808
John McCallcc7e5bf2010-05-06 08:58:33 +00007809 // We should never be unable to prove that the unsigned operand is
7810 // non-negative.
7811 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
7812
7813 if (unsignedRange.Width < comparisonWidth)
7814 return;
7815 }
7816
Douglas Gregorbfb4a212012-05-01 01:53:49 +00007817 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
7818 S.PDiag(diag::warn_mixed_sign_comparison)
7819 << LHS->getType() << RHS->getType()
7820 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00007821}
7822
John McCall1f425642010-11-11 03:21:53 +00007823/// Analyzes an attempt to assign the given value to a bitfield.
7824///
7825/// Returns true if there was something fishy about the attempt.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007826bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
7827 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00007828 assert(Bitfield->isBitField());
7829 if (Bitfield->isInvalidDecl())
7830 return false;
7831
John McCalldeebbcf2010-11-11 05:33:51 +00007832 // White-list bool bitfields.
7833 if (Bitfield->getType()->isBooleanType())
7834 return false;
7835
Douglas Gregor789adec2011-02-04 13:09:01 +00007836 // Ignore value- or type-dependent expressions.
7837 if (Bitfield->getBitWidth()->isValueDependent() ||
7838 Bitfield->getBitWidth()->isTypeDependent() ||
7839 Init->isValueDependent() ||
7840 Init->isTypeDependent())
7841 return false;
7842
John McCall1f425642010-11-11 03:21:53 +00007843 Expr *OriginalInit = Init->IgnoreParenImpCasts();
7844
Richard Smith5fab0c92011-12-28 19:48:30 +00007845 llvm::APSInt Value;
7846 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00007847 return false;
7848
John McCall1f425642010-11-11 03:21:53 +00007849 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00007850 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00007851
Richard Trieu7561ed02016-08-05 02:39:30 +00007852 if (Value.isSigned() && Value.isNegative())
7853 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
7854 if (UO->getOpcode() == UO_Minus)
7855 if (isa<IntegerLiteral>(UO->getSubExpr()))
7856 OriginalWidth = Value.getMinSignedBits();
7857
John McCall1f425642010-11-11 03:21:53 +00007858 if (OriginalWidth <= FieldWidth)
7859 return false;
7860
Eli Friedmanc267a322012-01-26 23:11:39 +00007861 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00007862 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedmanc267a322012-01-26 23:11:39 +00007863 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00007864
Eli Friedmanc267a322012-01-26 23:11:39 +00007865 // Check whether the stored value is equal to the original value.
7866 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00007867 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00007868 return false;
7869
Eli Friedmanc267a322012-01-26 23:11:39 +00007870 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00007871 // therefore don't strictly fit into a signed bitfield of width 1.
7872 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00007873 return false;
7874
John McCall1f425642010-11-11 03:21:53 +00007875 std::string PrettyValue = Value.toString(10);
7876 std::string PrettyTrunc = TruncatedValue.toString(10);
7877
7878 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
7879 << PrettyValue << PrettyTrunc << OriginalInit->getType()
7880 << Init->getSourceRange();
7881
7882 return true;
7883}
7884
John McCalld2a53122010-11-09 23:24:47 +00007885/// Analyze the given simple or compound assignment for warning-worthy
7886/// operations.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007887void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00007888 // Just recurse on the LHS.
7889 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
7890
7891 // We want to recurse on the RHS as normal unless we're assigning to
7892 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00007893 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007894 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00007895 E->getOperatorLoc())) {
7896 // Recurse, ignoring any implicit conversions on the RHS.
7897 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
7898 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00007899 }
7900 }
7901
7902 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
7903}
7904
John McCall263a48b2010-01-04 23:31:57 +00007905/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007906void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
7907 SourceLocation CContext, unsigned diag,
7908 bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00007909 if (pruneControlFlow) {
7910 S.DiagRuntimeBehavior(E->getExprLoc(), E,
7911 S.PDiag(diag)
7912 << SourceType << T << E->getSourceRange()
7913 << SourceRange(CContext));
7914 return;
7915 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00007916 S.Diag(E->getExprLoc(), diag)
7917 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
7918}
7919
Chandler Carruth7f3654f2011-04-05 06:47:57 +00007920/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007921void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
7922 unsigned diag, bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00007923 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00007924}
7925
Richard Trieube234c32016-04-21 21:04:55 +00007926
7927/// Diagnose an implicit cast from a floating point value to an integer value.
7928void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
7929
7930 SourceLocation CContext) {
7931 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
7932 const bool PruneWarnings = !S.ActiveTemplateInstantiations.empty();
7933
7934 Expr *InnerE = E->IgnoreParenImpCasts();
7935 // We also want to warn on, e.g., "int i = -1.234"
7936 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
7937 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
7938 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
7939
7940 const bool IsLiteral =
7941 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
7942
7943 llvm::APFloat Value(0.0);
7944 bool IsConstant =
7945 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
7946 if (!IsConstant) {
Richard Trieu891f0f12016-04-22 22:14:32 +00007947 return DiagnoseImpCast(S, E, T, CContext,
7948 diag::warn_impcast_float_integer, PruneWarnings);
Richard Trieube234c32016-04-21 21:04:55 +00007949 }
7950
Chandler Carruth016ef402011-04-10 08:36:24 +00007951 bool isExact = false;
Richard Trieube234c32016-04-21 21:04:55 +00007952
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00007953 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
7954 T->hasUnsignedIntegerRepresentation());
Richard Trieube234c32016-04-21 21:04:55 +00007955 if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero,
7956 &isExact) == llvm::APFloat::opOK &&
Richard Trieu891f0f12016-04-22 22:14:32 +00007957 isExact) {
Richard Trieube234c32016-04-21 21:04:55 +00007958 if (IsLiteral) return;
7959 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
7960 PruneWarnings);
7961 }
7962
7963 unsigned DiagID = 0;
Richard Trieu891f0f12016-04-22 22:14:32 +00007964 if (IsLiteral) {
Richard Trieube234c32016-04-21 21:04:55 +00007965 // Warn on floating point literal to integer.
7966 DiagID = diag::warn_impcast_literal_float_to_integer;
7967 } else if (IntegerValue == 0) {
7968 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
7969 return DiagnoseImpCast(S, E, T, CContext,
7970 diag::warn_impcast_float_integer, PruneWarnings);
7971 }
7972 // Warn on non-zero to zero conversion.
7973 DiagID = diag::warn_impcast_float_to_integer_zero;
7974 } else {
7975 if (IntegerValue.isUnsigned()) {
7976 if (!IntegerValue.isMaxValue()) {
7977 return DiagnoseImpCast(S, E, T, CContext,
7978 diag::warn_impcast_float_integer, PruneWarnings);
7979 }
7980 } else { // IntegerValue.isSigned()
7981 if (!IntegerValue.isMaxSignedValue() &&
7982 !IntegerValue.isMinSignedValue()) {
7983 return DiagnoseImpCast(S, E, T, CContext,
7984 diag::warn_impcast_float_integer, PruneWarnings);
7985 }
7986 }
7987 // Warn on evaluatable floating point expression to integer conversion.
7988 DiagID = diag::warn_impcast_float_to_integer;
7989 }
Chandler Carruth016ef402011-04-10 08:36:24 +00007990
Eli Friedman07185912013-08-29 23:44:43 +00007991 // FIXME: Force the precision of the source value down so we don't print
7992 // digits which are usually useless (we don't really care here if we
7993 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
7994 // would automatically print the shortest representation, but it's a bit
7995 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00007996 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00007997 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
7998 precision = (precision * 59 + 195) / 196;
7999 Value.toString(PrettySourceValue, precision);
8000
David Blaikie9b88cc02012-05-15 17:18:27 +00008001 SmallString<16> PrettyTargetValue;
Richard Trieube234c32016-04-21 21:04:55 +00008002 if (IsBool)
Aaron Ballmandbc441e2015-12-30 14:26:07 +00008003 PrettyTargetValue = Value.isZero() ? "false" : "true";
David Blaikie7555b6a2012-05-15 16:56:36 +00008004 else
David Blaikie9b88cc02012-05-15 17:18:27 +00008005 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00008006
Richard Trieube234c32016-04-21 21:04:55 +00008007 if (PruneWarnings) {
8008 S.DiagRuntimeBehavior(E->getExprLoc(), E,
8009 S.PDiag(DiagID)
8010 << E->getType() << T.getUnqualifiedType()
8011 << PrettySourceValue << PrettyTargetValue
8012 << E->getSourceRange() << SourceRange(CContext));
8013 } else {
8014 S.Diag(E->getExprLoc(), DiagID)
8015 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
8016 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
8017 }
Chandler Carruth016ef402011-04-10 08:36:24 +00008018}
8019
John McCall18a2c2c2010-11-09 22:22:12 +00008020std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
8021 if (!Range.Width) return "0";
8022
8023 llvm::APSInt ValueInRange = Value;
8024 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00008025 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00008026 return ValueInRange.toString(10);
8027}
8028
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008029bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00008030 if (!isa<ImplicitCastExpr>(Ex))
8031 return false;
8032
8033 Expr *InnerE = Ex->IgnoreParenImpCasts();
8034 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
8035 const Type *Source =
8036 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
8037 if (Target->isDependentType())
8038 return false;
8039
8040 const BuiltinType *FloatCandidateBT =
8041 dyn_cast<BuiltinType>(ToBool ? Source : Target);
8042 const Type *BoolCandidateType = ToBool ? Target : Source;
8043
8044 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
8045 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
8046}
8047
8048void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
8049 SourceLocation CC) {
8050 unsigned NumArgs = TheCall->getNumArgs();
8051 for (unsigned i = 0; i < NumArgs; ++i) {
8052 Expr *CurrA = TheCall->getArg(i);
8053 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
8054 continue;
8055
8056 bool IsSwapped = ((i > 0) &&
8057 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
8058 IsSwapped |= ((i < (NumArgs - 1)) &&
8059 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
8060 if (IsSwapped) {
8061 // Warn on this floating-point to bool conversion.
8062 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
8063 CurrA->getType(), CC,
8064 diag::warn_impcast_floating_point_to_bool);
8065 }
8066 }
8067}
8068
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008069void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) {
Richard Trieu5b993502014-10-15 03:42:06 +00008070 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
8071 E->getExprLoc()))
8072 return;
8073
Richard Trieu09d6b802016-01-08 23:35:06 +00008074 // Don't warn on functions which have return type nullptr_t.
8075 if (isa<CallExpr>(E))
8076 return;
8077
Richard Trieu5b993502014-10-15 03:42:06 +00008078 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
8079 const Expr::NullPointerConstantKind NullKind =
8080 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
8081 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
8082 return;
8083
8084 // Return if target type is a safe conversion.
8085 if (T->isAnyPointerType() || T->isBlockPointerType() ||
8086 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
8087 return;
8088
8089 SourceLocation Loc = E->getSourceRange().getBegin();
8090
Richard Trieu0a5e1662016-02-13 00:58:53 +00008091 // Venture through the macro stacks to get to the source of macro arguments.
8092 // The new location is a better location than the complete location that was
8093 // passed in.
8094 while (S.SourceMgr.isMacroArgExpansion(Loc))
8095 Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc);
8096
8097 while (S.SourceMgr.isMacroArgExpansion(CC))
8098 CC = S.SourceMgr.getImmediateMacroCallerLoc(CC);
8099
Richard Trieu5b993502014-10-15 03:42:06 +00008100 // __null is usually wrapped in a macro. Go up a macro if that is the case.
Richard Trieu0a5e1662016-02-13 00:58:53 +00008101 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
8102 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
8103 Loc, S.SourceMgr, S.getLangOpts());
8104 if (MacroName == "NULL")
8105 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
Richard Trieu5b993502014-10-15 03:42:06 +00008106 }
8107
8108 // Only warn if the null and context location are in the same macro expansion.
8109 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
8110 return;
8111
8112 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
8113 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
8114 << FixItHint::CreateReplacement(Loc,
8115 S.getFixItZeroLiteralForType(T, Loc));
8116}
8117
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008118void checkObjCArrayLiteral(Sema &S, QualType TargetType,
8119 ObjCArrayLiteral *ArrayLiteral);
8120void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
8121 ObjCDictionaryLiteral *DictionaryLiteral);
Douglas Gregor5054cb02015-07-07 03:58:22 +00008122
8123/// Check a single element within a collection literal against the
8124/// target element type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008125void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType,
8126 Expr *Element, unsigned ElementKind) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00008127 // Skip a bitcast to 'id' or qualified 'id'.
8128 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
8129 if (ICE->getCastKind() == CK_BitCast &&
8130 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
8131 Element = ICE->getSubExpr();
8132 }
8133
8134 QualType ElementType = Element->getType();
8135 ExprResult ElementResult(Element);
8136 if (ElementType->getAs<ObjCObjectPointerType>() &&
8137 S.CheckSingleAssignmentConstraints(TargetElementType,
8138 ElementResult,
8139 false, false)
8140 != Sema::Compatible) {
8141 S.Diag(Element->getLocStart(),
8142 diag::warn_objc_collection_literal_element)
8143 << ElementType << ElementKind << TargetElementType
8144 << Element->getSourceRange();
8145 }
8146
8147 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
8148 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
8149 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
8150 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
8151}
8152
8153/// Check an Objective-C array literal being converted to the given
8154/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008155void checkObjCArrayLiteral(Sema &S, QualType TargetType,
8156 ObjCArrayLiteral *ArrayLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00008157 if (!S.NSArrayDecl)
8158 return;
8159
8160 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
8161 if (!TargetObjCPtr)
8162 return;
8163
8164 if (TargetObjCPtr->isUnspecialized() ||
8165 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
8166 != S.NSArrayDecl->getCanonicalDecl())
8167 return;
8168
8169 auto TypeArgs = TargetObjCPtr->getTypeArgs();
8170 if (TypeArgs.size() != 1)
8171 return;
8172
8173 QualType TargetElementType = TypeArgs[0];
8174 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
8175 checkObjCCollectionLiteralElement(S, TargetElementType,
8176 ArrayLiteral->getElement(I),
8177 0);
8178 }
8179}
8180
8181/// Check an Objective-C dictionary literal being converted to the given
8182/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008183void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
8184 ObjCDictionaryLiteral *DictionaryLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00008185 if (!S.NSDictionaryDecl)
8186 return;
8187
8188 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
8189 if (!TargetObjCPtr)
8190 return;
8191
8192 if (TargetObjCPtr->isUnspecialized() ||
8193 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
8194 != S.NSDictionaryDecl->getCanonicalDecl())
8195 return;
8196
8197 auto TypeArgs = TargetObjCPtr->getTypeArgs();
8198 if (TypeArgs.size() != 2)
8199 return;
8200
8201 QualType TargetKeyType = TypeArgs[0];
8202 QualType TargetObjectType = TypeArgs[1];
8203 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
8204 auto Element = DictionaryLiteral->getKeyValueElement(I);
8205 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
8206 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
8207 }
8208}
8209
Richard Trieufc404c72016-02-05 23:02:38 +00008210// Helper function to filter out cases for constant width constant conversion.
8211// Don't warn on char array initialization or for non-decimal values.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008212bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
8213 SourceLocation CC) {
Richard Trieufc404c72016-02-05 23:02:38 +00008214 // If initializing from a constant, and the constant starts with '0',
8215 // then it is a binary, octal, or hexadecimal. Allow these constants
8216 // to fill all the bits, even if there is a sign change.
8217 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
8218 const char FirstLiteralCharacter =
8219 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
8220 if (FirstLiteralCharacter == '0')
8221 return false;
8222 }
8223
8224 // If the CC location points to a '{', and the type is char, then assume
8225 // assume it is an array initialization.
8226 if (CC.isValid() && T->isCharType()) {
8227 const char FirstContextCharacter =
8228 S.getSourceManager().getCharacterData(CC)[0];
8229 if (FirstContextCharacter == '{')
8230 return false;
8231 }
8232
8233 return true;
8234}
8235
John McCallcc7e5bf2010-05-06 08:58:33 +00008236void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00008237 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008238 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00008239
John McCallcc7e5bf2010-05-06 08:58:33 +00008240 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
8241 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
8242 if (Source == Target) return;
8243 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00008244
Chandler Carruthc22845a2011-07-26 05:40:03 +00008245 // If the conversion context location is invalid don't complain. We also
8246 // don't want to emit a warning if the issue occurs from the expansion of
8247 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
8248 // delay this check as long as possible. Once we detect we are in that
8249 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008250 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00008251 return;
8252
Richard Trieu021baa32011-09-23 20:10:00 +00008253 // Diagnose implicit casts to bool.
8254 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
8255 if (isa<StringLiteral>(E))
8256 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00008257 // and expressions, for instance, assert(0 && "error here"), are
8258 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00008259 return DiagnoseImpCast(S, E, T, CC,
8260 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00008261 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
8262 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
8263 // This covers the literal expressions that evaluate to Objective-C
8264 // objects.
8265 return DiagnoseImpCast(S, E, T, CC,
8266 diag::warn_impcast_objective_c_literal_to_bool);
8267 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00008268 if (Source->isPointerType() || Source->canDecayToPointerType()) {
8269 // Warn on pointer to bool conversion that is always true.
8270 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
8271 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00008272 }
Richard Trieu021baa32011-09-23 20:10:00 +00008273 }
John McCall263a48b2010-01-04 23:31:57 +00008274
Douglas Gregor5054cb02015-07-07 03:58:22 +00008275 // Check implicit casts from Objective-C collection literals to specialized
8276 // collection types, e.g., NSArray<NSString *> *.
8277 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
8278 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
8279 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
8280 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
8281
John McCall263a48b2010-01-04 23:31:57 +00008282 // Strip vector types.
8283 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008284 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008285 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008286 return;
John McCallacf0ee52010-10-08 02:01:28 +00008287 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008288 }
Chris Lattneree7286f2011-06-14 04:51:15 +00008289
8290 // If the vector cast is cast between two vectors of the same size, it is
8291 // a bitcast, not a conversion.
8292 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
8293 return;
John McCall263a48b2010-01-04 23:31:57 +00008294
8295 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
8296 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
8297 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00008298 if (auto VecTy = dyn_cast<VectorType>(Target))
8299 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00008300
8301 // Strip complex types.
8302 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008303 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008304 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008305 return;
8306
John McCallacf0ee52010-10-08 02:01:28 +00008307 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008308 }
John McCall263a48b2010-01-04 23:31:57 +00008309
8310 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
8311 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
8312 }
8313
8314 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
8315 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
8316
8317 // If the source is floating point...
8318 if (SourceBT && SourceBT->isFloatingPoint()) {
8319 // ...and the target is floating point...
8320 if (TargetBT && TargetBT->isFloatingPoint()) {
8321 // ...then warn if we're dropping FP rank.
8322
8323 // Builtin FP kinds are ordered by increasing FP rank.
8324 if (SourceBT->getKind() > TargetBT->getKind()) {
8325 // Don't warn about float constants that are precisely
8326 // representable in the target type.
8327 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00008328 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00008329 // Value might be a float, a float vector, or a float complex.
8330 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00008331 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
8332 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00008333 return;
8334 }
8335
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008336 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008337 return;
8338
John McCallacf0ee52010-10-08 02:01:28 +00008339 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
George Burgess IV148e0d32015-10-29 00:28:52 +00008340 }
8341 // ... or possibly if we're increasing rank, too
8342 else if (TargetBT->getKind() > SourceBT->getKind()) {
8343 if (S.SourceMgr.isInSystemMacro(CC))
8344 return;
8345
8346 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
John McCall263a48b2010-01-04 23:31:57 +00008347 }
8348 return;
8349 }
8350
Richard Trieube234c32016-04-21 21:04:55 +00008351 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00008352 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008353 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008354 return;
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00008355
Richard Trieube234c32016-04-21 21:04:55 +00008356 DiagnoseFloatingImpCast(S, E, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00008357 }
John McCall263a48b2010-01-04 23:31:57 +00008358
Richard Smith54894fd2015-12-30 01:06:52 +00008359 // Detect the case where a call result is converted from floating-point to
8360 // to bool, and the final argument to the call is converted from bool, to
8361 // discover this typo:
8362 //
8363 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
8364 //
8365 // FIXME: This is an incredibly special case; is there some more general
8366 // way to detect this class of misplaced-parentheses bug?
8367 if (Target->isBooleanType() && isa<CallExpr>(E)) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00008368 // Check last argument of function call to see if it is an
8369 // implicit cast from a type matching the type the result
8370 // is being cast to.
8371 CallExpr *CEx = cast<CallExpr>(E);
Richard Smith54894fd2015-12-30 01:06:52 +00008372 if (unsigned NumArgs = CEx->getNumArgs()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00008373 Expr *LastA = CEx->getArg(NumArgs - 1);
8374 Expr *InnerE = LastA->IgnoreParenImpCasts();
Richard Smith54894fd2015-12-30 01:06:52 +00008375 if (isa<ImplicitCastExpr>(LastA) &&
8376 InnerE->getType()->isBooleanType()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00008377 // Warn on this floating-point to bool conversion
8378 DiagnoseImpCast(S, E, T, CC,
8379 diag::warn_impcast_floating_point_to_bool);
8380 }
8381 }
8382 }
John McCall263a48b2010-01-04 23:31:57 +00008383 return;
8384 }
8385
Richard Trieu5b993502014-10-15 03:42:06 +00008386 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +00008387
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +00008388 S.DiscardMisalignedMemberAddress(Target, E);
8389
David Blaikie9366d2b2012-06-19 21:19:06 +00008390 if (!Source->isIntegerType() || !Target->isIntegerType())
8391 return;
8392
David Blaikie7555b6a2012-05-15 16:56:36 +00008393 // TODO: remove this early return once the false positives for constant->bool
8394 // in templates, macros, etc, are reduced or removed.
8395 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
8396 return;
8397
John McCallcc7e5bf2010-05-06 08:58:33 +00008398 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00008399 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00008400
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008401 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00008402 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008403 // TODO: this should happen for bitfield stores, too.
8404 llvm::APSInt Value(32);
Richard Trieudcb55572016-01-29 23:51:16 +00008405 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008406 if (S.SourceMgr.isInSystemMacro(CC))
8407 return;
8408
John McCall18a2c2c2010-11-09 22:22:12 +00008409 std::string PrettySourceValue = Value.toString(10);
8410 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008411
Ted Kremenek33ba9952011-10-22 02:37:33 +00008412 S.DiagRuntimeBehavior(E->getExprLoc(), E,
8413 S.PDiag(diag::warn_impcast_integer_precision_constant)
8414 << PrettySourceValue << PrettyTargetValue
8415 << E->getType() << T << E->getSourceRange()
8416 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00008417 return;
8418 }
8419
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008420 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
8421 if (S.SourceMgr.isInSystemMacro(CC))
8422 return;
8423
David Blaikie9455da02012-04-12 22:40:54 +00008424 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00008425 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
8426 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00008427 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00008428 }
8429
Richard Trieudcb55572016-01-29 23:51:16 +00008430 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
8431 SourceRange.NonNegative && Source->isSignedIntegerType()) {
8432 // Warn when doing a signed to signed conversion, warn if the positive
8433 // source value is exactly the width of the target type, which will
8434 // cause a negative value to be stored.
8435
8436 llvm::APSInt Value;
Richard Trieufc404c72016-02-05 23:02:38 +00008437 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
8438 !S.SourceMgr.isInSystemMacro(CC)) {
8439 if (isSameWidthConstantConversion(S, E, T, CC)) {
8440 std::string PrettySourceValue = Value.toString(10);
8441 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Richard Trieudcb55572016-01-29 23:51:16 +00008442
Richard Trieufc404c72016-02-05 23:02:38 +00008443 S.DiagRuntimeBehavior(
8444 E->getExprLoc(), E,
8445 S.PDiag(diag::warn_impcast_integer_precision_constant)
8446 << PrettySourceValue << PrettyTargetValue << E->getType() << T
8447 << E->getSourceRange() << clang::SourceRange(CC));
8448 return;
Richard Trieudcb55572016-01-29 23:51:16 +00008449 }
8450 }
Richard Trieufc404c72016-02-05 23:02:38 +00008451
Richard Trieudcb55572016-01-29 23:51:16 +00008452 // Fall through for non-constants to give a sign conversion warning.
8453 }
8454
John McCallcc7e5bf2010-05-06 08:58:33 +00008455 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
8456 (!TargetRange.NonNegative && SourceRange.NonNegative &&
8457 SourceRange.Width == TargetRange.Width)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008458 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008459 return;
8460
John McCallcc7e5bf2010-05-06 08:58:33 +00008461 unsigned DiagID = diag::warn_impcast_integer_sign;
8462
8463 // Traditionally, gcc has warned about this under -Wsign-compare.
8464 // We also want to warn about it in -Wconversion.
8465 // So if -Wconversion is off, use a completely identical diagnostic
8466 // in the sign-compare group.
8467 // The conditional-checking code will
8468 if (ICContext) {
8469 DiagID = diag::warn_impcast_integer_sign_conditional;
8470 *ICContext = true;
8471 }
8472
John McCallacf0ee52010-10-08 02:01:28 +00008473 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00008474 }
8475
Douglas Gregora78f1932011-02-22 02:45:07 +00008476 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00008477 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
8478 // type, to give us better diagnostics.
8479 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00008480 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00008481 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
8482 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
8483 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
8484 SourceType = S.Context.getTypeDeclType(Enum);
8485 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
8486 }
8487 }
8488
Douglas Gregora78f1932011-02-22 02:45:07 +00008489 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
8490 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00008491 if (SourceEnum->getDecl()->hasNameForLinkage() &&
8492 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008493 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008494 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008495 return;
8496
Douglas Gregor364f7db2011-03-12 00:14:31 +00008497 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00008498 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008499 }
John McCall263a48b2010-01-04 23:31:57 +00008500}
8501
David Blaikie18e9ac72012-05-15 21:57:38 +00008502void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
8503 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00008504
8505void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00008506 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008507 E = E->IgnoreParenImpCasts();
8508
8509 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00008510 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00008511
John McCallacf0ee52010-10-08 02:01:28 +00008512 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008513 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00008514 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00008515}
8516
David Blaikie18e9ac72012-05-15 21:57:38 +00008517void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
8518 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00008519 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00008520
8521 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00008522 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
8523 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00008524
8525 // If -Wconversion would have warned about either of the candidates
8526 // for a signedness conversion to the context type...
8527 if (!Suspicious) return;
8528
8529 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00008530 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00008531 return;
8532
John McCallcc7e5bf2010-05-06 08:58:33 +00008533 // ...then check whether it would have warned about either of the
8534 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00008535 if (E->getType() == T) return;
8536
8537 Suspicious = false;
8538 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
8539 E->getType(), CC, &Suspicious);
8540 if (!Suspicious)
8541 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00008542 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00008543}
8544
Richard Trieu65724892014-11-15 06:37:39 +00008545/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
8546/// Input argument E is a logical expression.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008547void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
Richard Trieu65724892014-11-15 06:37:39 +00008548 if (S.getLangOpts().Bool)
8549 return;
8550 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
8551}
8552
John McCallcc7e5bf2010-05-06 08:58:33 +00008553/// AnalyzeImplicitConversions - Find and report any interesting
8554/// implicit conversions in the given expression. There are a couple
8555/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00008556void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00008557 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00008558 Expr *E = OrigE->IgnoreParenImpCasts();
8559
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00008560 if (E->isTypeDependent() || E->isValueDependent())
8561 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00008562
John McCallcc7e5bf2010-05-06 08:58:33 +00008563 // For conditional operators, we analyze the arguments as if they
8564 // were being fed directly into the output.
8565 if (isa<ConditionalOperator>(E)) {
8566 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00008567 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00008568 return;
8569 }
8570
Hans Wennborgf4ad2322012-08-28 15:44:30 +00008571 // Check implicit argument conversions for function calls.
8572 if (CallExpr *Call = dyn_cast<CallExpr>(E))
8573 CheckImplicitArgumentConversions(S, Call, CC);
8574
John McCallcc7e5bf2010-05-06 08:58:33 +00008575 // Go ahead and check any implicit conversions we might have skipped.
8576 // The non-canonical typecheck is just an optimization;
8577 // CheckImplicitConversion will filter out dead implicit conversions.
8578 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00008579 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008580
8581 // Now continue drilling into this expression.
Richard Smithd7bed4d2015-11-22 02:57:17 +00008582
8583 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
8584 // The bound subexpressions in a PseudoObjectExpr are not reachable
8585 // as transitive children.
8586 // FIXME: Use a more uniform representation for this.
8587 for (auto *SE : POE->semantics())
8588 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
8589 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00008590 }
Richard Smithd7bed4d2015-11-22 02:57:17 +00008591
John McCallcc7e5bf2010-05-06 08:58:33 +00008592 // Skip past explicit casts.
8593 if (isa<ExplicitCastExpr>(E)) {
8594 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00008595 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008596 }
8597
John McCalld2a53122010-11-09 23:24:47 +00008598 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
8599 // Do a somewhat different check with comparison operators.
8600 if (BO->isComparisonOp())
8601 return AnalyzeComparison(S, BO);
8602
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008603 // And with simple assignments.
8604 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00008605 return AnalyzeAssignment(S, BO);
8606 }
John McCallcc7e5bf2010-05-06 08:58:33 +00008607
8608 // These break the otherwise-useful invariant below. Fortunately,
8609 // we don't really need to recurse into them, because any internal
8610 // expressions should have been analyzed already when they were
8611 // built into statements.
8612 if (isa<StmtExpr>(E)) return;
8613
8614 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00008615 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00008616
8617 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00008618 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00008619 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00008620 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Benjamin Kramer642f1732015-07-02 21:03:14 +00008621 for (Stmt *SubStmt : E->children()) {
8622 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00008623 if (!ChildExpr)
8624 continue;
8625
Richard Trieu955231d2014-01-25 01:10:35 +00008626 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00008627 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00008628 // Ignore checking string literals that are in logical and operators.
8629 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00008630 continue;
8631 AnalyzeImplicitConversions(S, ChildExpr, CC);
8632 }
Richard Trieu791b86e2014-11-19 06:08:18 +00008633
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00008634 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +00008635 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
8636 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00008637 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +00008638
8639 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
8640 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00008641 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00008642 }
Richard Trieu791b86e2014-11-19 06:08:18 +00008643
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00008644 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
8645 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +00008646 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008647}
8648
8649} // end anonymous namespace
8650
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00008651static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
8652 unsigned Start, unsigned End) {
8653 bool IllegalParams = false;
8654 for (unsigned I = Start; I <= End; ++I) {
8655 QualType Ty = TheCall->getArg(I)->getType();
8656 // Taking into account implicit conversions,
8657 // allow any integer within 32 bits range
8658 if (!Ty->isIntegerType() ||
8659 S.Context.getTypeSizeInChars(Ty).getQuantity() > 4) {
8660 S.Diag(TheCall->getArg(I)->getLocStart(),
8661 diag::err_opencl_enqueue_kernel_invalid_local_size_type);
8662 IllegalParams = true;
8663 }
8664 // Potentially emit standard warnings for implicit conversions if enabled
8665 // using -Wconversion.
8666 CheckImplicitConversion(S, TheCall->getArg(I), S.Context.UnsignedIntTy,
8667 TheCall->getArg(I)->getLocStart());
8668 }
8669 return IllegalParams;
8670}
8671
Richard Trieuc1888e02014-06-28 23:25:37 +00008672// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
8673// Returns true when emitting a warning about taking the address of a reference.
8674static bool CheckForReference(Sema &SemaRef, const Expr *E,
Benjamin Kramer7320b992016-06-15 14:20:56 +00008675 const PartialDiagnostic &PD) {
Richard Trieuc1888e02014-06-28 23:25:37 +00008676 E = E->IgnoreParenImpCasts();
8677
8678 const FunctionDecl *FD = nullptr;
8679
8680 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
8681 if (!DRE->getDecl()->getType()->isReferenceType())
8682 return false;
8683 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
8684 if (!M->getMemberDecl()->getType()->isReferenceType())
8685 return false;
8686 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +00008687 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +00008688 return false;
8689 FD = Call->getDirectCallee();
8690 } else {
8691 return false;
8692 }
8693
8694 SemaRef.Diag(E->getExprLoc(), PD);
8695
8696 // If possible, point to location of function.
8697 if (FD) {
8698 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
8699 }
8700
8701 return true;
8702}
8703
Richard Trieu4cbff5c2014-08-08 22:41:43 +00008704// Returns true if the SourceLocation is expanded from any macro body.
8705// Returns false if the SourceLocation is invalid, is from not in a macro
8706// expansion, or is from expanded from a top-level macro argument.
8707static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
8708 if (Loc.isInvalid())
8709 return false;
8710
8711 while (Loc.isMacroID()) {
8712 if (SM.isMacroBodyExpansion(Loc))
8713 return true;
8714 Loc = SM.getImmediateMacroCallerLoc(Loc);
8715 }
8716
8717 return false;
8718}
8719
Richard Trieu3bb8b562014-02-26 02:36:06 +00008720/// \brief Diagnose pointers that are always non-null.
8721/// \param E the expression containing the pointer
8722/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
8723/// compared to a null pointer
8724/// \param IsEqual True when the comparison is equal to a null pointer
8725/// \param Range Extra SourceRange to highlight in the diagnostic
8726void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
8727 Expr::NullPointerConstantKind NullKind,
8728 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00008729 if (!E)
8730 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00008731
8732 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +00008733 if (E->getExprLoc().isMacroID()) {
8734 const SourceManager &SM = getSourceManager();
8735 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
8736 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +00008737 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +00008738 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00008739 E = E->IgnoreImpCasts();
8740
8741 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
8742
Richard Trieuf7432752014-06-06 21:39:26 +00008743 if (isa<CXXThisExpr>(E)) {
8744 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
8745 : diag::warn_this_bool_conversion;
8746 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
8747 return;
8748 }
8749
Richard Trieu3bb8b562014-02-26 02:36:06 +00008750 bool IsAddressOf = false;
8751
8752 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
8753 if (UO->getOpcode() != UO_AddrOf)
8754 return;
8755 IsAddressOf = true;
8756 E = UO->getSubExpr();
8757 }
8758
Richard Trieuc1888e02014-06-28 23:25:37 +00008759 if (IsAddressOf) {
8760 unsigned DiagID = IsCompare
8761 ? diag::warn_address_of_reference_null_compare
8762 : diag::warn_address_of_reference_bool_conversion;
8763 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
8764 << IsEqual;
8765 if (CheckForReference(*this, E, PD)) {
8766 return;
8767 }
8768 }
8769
Nick Lewyckybc85ec82016-06-15 05:18:39 +00008770 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
8771 bool IsParam = isa<NonNullAttr>(NonnullAttr);
George Burgess IV850269a2015-12-08 22:02:00 +00008772 std::string Str;
8773 llvm::raw_string_ostream S(Str);
8774 E->printPretty(S, nullptr, getPrintingPolicy());
8775 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
8776 : diag::warn_cast_nonnull_to_bool;
8777 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
8778 << E->getSourceRange() << Range << IsEqual;
Nick Lewyckybc85ec82016-06-15 05:18:39 +00008779 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
George Burgess IV850269a2015-12-08 22:02:00 +00008780 };
8781
8782 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
8783 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
8784 if (auto *Callee = Call->getDirectCallee()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00008785 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
8786 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +00008787 return;
8788 }
8789 }
8790 }
8791
Richard Trieu3bb8b562014-02-26 02:36:06 +00008792 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +00008793 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +00008794 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
8795 D = R->getDecl();
8796 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
8797 D = M->getMemberDecl();
8798 }
8799
8800 // Weak Decls can be null.
8801 if (!D || D->isWeak())
8802 return;
George Burgess IV850269a2015-12-08 22:02:00 +00008803
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008804 // Check for parameter decl with nonnull attribute
George Burgess IV850269a2015-12-08 22:02:00 +00008805 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
8806 if (getCurFunction() &&
8807 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00008808 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
8809 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +00008810 return;
8811 }
8812
8813 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
David Majnemera3debed2016-06-24 05:33:44 +00008814 auto ParamIter = llvm::find(FD->parameters(), PV);
George Burgess IV850269a2015-12-08 22:02:00 +00008815 assert(ParamIter != FD->param_end());
8816 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
8817
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008818 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
8819 if (!NonNull->args_size()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00008820 ComplainAboutNonnullParamOrCall(NonNull);
George Burgess IV850269a2015-12-08 22:02:00 +00008821 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008822 }
George Burgess IV850269a2015-12-08 22:02:00 +00008823
8824 for (unsigned ArgNo : NonNull->args()) {
8825 if (ArgNo == ParamNo) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00008826 ComplainAboutNonnullParamOrCall(NonNull);
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008827 return;
8828 }
George Burgess IV850269a2015-12-08 22:02:00 +00008829 }
8830 }
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008831 }
8832 }
George Burgess IV850269a2015-12-08 22:02:00 +00008833 }
8834
Richard Trieu3bb8b562014-02-26 02:36:06 +00008835 QualType T = D->getType();
8836 const bool IsArray = T->isArrayType();
8837 const bool IsFunction = T->isFunctionType();
8838
Richard Trieuc1888e02014-06-28 23:25:37 +00008839 // Address of function is used to silence the function warning.
8840 if (IsAddressOf && IsFunction) {
8841 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00008842 }
8843
8844 // Found nothing.
8845 if (!IsAddressOf && !IsFunction && !IsArray)
8846 return;
8847
8848 // Pretty print the expression for the diagnostic.
8849 std::string Str;
8850 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +00008851 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +00008852
8853 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
8854 : diag::warn_impcast_pointer_to_bool;
Craig Topperfa1340f2015-12-23 05:44:46 +00008855 enum {
8856 AddressOf,
8857 FunctionPointer,
8858 ArrayPointer
8859 } DiagType;
Richard Trieu3bb8b562014-02-26 02:36:06 +00008860 if (IsAddressOf)
8861 DiagType = AddressOf;
8862 else if (IsFunction)
8863 DiagType = FunctionPointer;
8864 else if (IsArray)
8865 DiagType = ArrayPointer;
8866 else
8867 llvm_unreachable("Could not determine diagnostic.");
8868 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
8869 << Range << IsEqual;
8870
8871 if (!IsFunction)
8872 return;
8873
8874 // Suggest '&' to silence the function warning.
8875 Diag(E->getExprLoc(), diag::note_function_warning_silence)
8876 << FixItHint::CreateInsertion(E->getLocStart(), "&");
8877
8878 // Check to see if '()' fixit should be emitted.
8879 QualType ReturnType;
8880 UnresolvedSet<4> NonTemplateOverloads;
8881 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
8882 if (ReturnType.isNull())
8883 return;
8884
8885 if (IsCompare) {
8886 // There are two cases here. If there is null constant, the only suggest
8887 // for a pointer return type. If the null is 0, then suggest if the return
8888 // type is a pointer or an integer type.
8889 if (!ReturnType->isPointerType()) {
8890 if (NullKind == Expr::NPCK_ZeroExpression ||
8891 NullKind == Expr::NPCK_ZeroLiteral) {
8892 if (!ReturnType->isIntegerType())
8893 return;
8894 } else {
8895 return;
8896 }
8897 }
8898 } else { // !IsCompare
8899 // For function to bool, only suggest if the function pointer has bool
8900 // return type.
8901 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
8902 return;
8903 }
8904 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +00008905 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +00008906}
8907
John McCallcc7e5bf2010-05-06 08:58:33 +00008908/// Diagnoses "dangerous" implicit conversions within the given
8909/// expression (which is a full expression). Implements -Wconversion
8910/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00008911///
8912/// \param CC the "context" location of the implicit conversion, i.e.
8913/// the most location of the syntactic entity requiring the implicit
8914/// conversion
8915void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008916 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00008917 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00008918 return;
8919
8920 // Don't diagnose for value- or type-dependent expressions.
8921 if (E->isTypeDependent() || E->isValueDependent())
8922 return;
8923
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008924 // Check for array bounds violations in cases where the check isn't triggered
8925 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
8926 // ArraySubscriptExpr is on the RHS of a variable initialization.
8927 CheckArrayAccess(E);
8928
John McCallacf0ee52010-10-08 02:01:28 +00008929 // This is not the right CC for (e.g.) a variable initialization.
8930 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008931}
8932
Richard Trieu65724892014-11-15 06:37:39 +00008933/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
8934/// Input argument E is a logical expression.
8935void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
8936 ::CheckBoolLikeConversion(*this, E, CC);
8937}
8938
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008939/// Diagnose when expression is an integer constant expression and its evaluation
8940/// results in integer overflow
8941void Sema::CheckForIntOverflow (Expr *E) {
Akira Hatanakadfe2156f2016-02-10 06:06:06 +00008942 // Use a work list to deal with nested struct initializers.
8943 SmallVector<Expr *, 2> Exprs(1, E);
8944
8945 do {
8946 Expr *E = Exprs.pop_back_val();
8947
8948 if (isa<BinaryOperator>(E->IgnoreParenCasts())) {
8949 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
8950 continue;
8951 }
8952
8953 if (auto InitList = dyn_cast<InitListExpr>(E))
8954 Exprs.append(InitList->inits().begin(), InitList->inits().end());
8955 } while (!Exprs.empty());
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008956}
8957
Richard Smithc406cb72013-01-17 01:17:56 +00008958namespace {
8959/// \brief Visitor for expressions which looks for unsequenced operations on the
8960/// same object.
8961class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00008962 typedef EvaluatedExprVisitor<SequenceChecker> Base;
8963
Richard Smithc406cb72013-01-17 01:17:56 +00008964 /// \brief A tree of sequenced regions within an expression. Two regions are
8965 /// unsequenced if one is an ancestor or a descendent of the other. When we
8966 /// finish processing an expression with sequencing, such as a comma
8967 /// expression, we fold its tree nodes into its parent, since they are
8968 /// unsequenced with respect to nodes we will visit later.
8969 class SequenceTree {
8970 struct Value {
8971 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
8972 unsigned Parent : 31;
Aaron Ballmanaffa1c32016-07-06 18:33:01 +00008973 unsigned Merged : 1;
Richard Smithc406cb72013-01-17 01:17:56 +00008974 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008975 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00008976
8977 public:
8978 /// \brief A region within an expression which may be sequenced with respect
8979 /// to some other region.
8980 class Seq {
8981 explicit Seq(unsigned N) : Index(N) {}
8982 unsigned Index;
8983 friend class SequenceTree;
8984 public:
8985 Seq() : Index(0) {}
8986 };
8987
8988 SequenceTree() { Values.push_back(Value(0)); }
8989 Seq root() const { return Seq(0); }
8990
8991 /// \brief Create a new sequence of operations, which is an unsequenced
8992 /// subset of \p Parent. This sequence of operations is sequenced with
8993 /// respect to other children of \p Parent.
8994 Seq allocate(Seq Parent) {
8995 Values.push_back(Value(Parent.Index));
8996 return Seq(Values.size() - 1);
8997 }
8998
8999 /// \brief Merge a sequence of operations into its parent.
9000 void merge(Seq S) {
9001 Values[S.Index].Merged = true;
9002 }
9003
9004 /// \brief Determine whether two operations are unsequenced. This operation
9005 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
9006 /// should have been merged into its parent as appropriate.
9007 bool isUnsequenced(Seq Cur, Seq Old) {
9008 unsigned C = representative(Cur.Index);
9009 unsigned Target = representative(Old.Index);
9010 while (C >= Target) {
9011 if (C == Target)
9012 return true;
9013 C = Values[C].Parent;
9014 }
9015 return false;
9016 }
9017
9018 private:
9019 /// \brief Pick a representative for a sequence.
9020 unsigned representative(unsigned K) {
9021 if (Values[K].Merged)
9022 // Perform path compression as we go.
9023 return Values[K].Parent = representative(Values[K].Parent);
9024 return K;
9025 }
9026 };
9027
9028 /// An object for which we can track unsequenced uses.
9029 typedef NamedDecl *Object;
9030
9031 /// Different flavors of object usage which we track. We only track the
9032 /// least-sequenced usage of each kind.
9033 enum UsageKind {
9034 /// A read of an object. Multiple unsequenced reads are OK.
9035 UK_Use,
9036 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00009037 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00009038 UK_ModAsValue,
9039 /// A modification of an object which is not sequenced before the value
9040 /// computation of the expression, such as n++.
9041 UK_ModAsSideEffect,
9042
9043 UK_Count = UK_ModAsSideEffect + 1
9044 };
9045
9046 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +00009047 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +00009048 Expr *Use;
9049 SequenceTree::Seq Seq;
9050 };
9051
9052 struct UsageInfo {
9053 UsageInfo() : Diagnosed(false) {}
9054 Usage Uses[UK_Count];
9055 /// Have we issued a diagnostic for this variable already?
9056 bool Diagnosed;
9057 };
9058 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
9059
9060 Sema &SemaRef;
9061 /// Sequenced regions within the expression.
9062 SequenceTree Tree;
9063 /// Declaration modifications and references which we have seen.
9064 UsageInfoMap UsageMap;
9065 /// The region we are currently within.
9066 SequenceTree::Seq Region;
9067 /// Filled in with declarations which were modified as a side-effect
9068 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009069 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00009070 /// Expressions to check later. We defer checking these to reduce
9071 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009072 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00009073
9074 /// RAII object wrapping the visitation of a sequenced subexpression of an
9075 /// expression. At the end of this process, the side-effects of the evaluation
9076 /// become sequenced with respect to the value computation of the result, so
9077 /// we downgrade any UK_ModAsSideEffect within the evaluation to
9078 /// UK_ModAsValue.
9079 struct SequencedSubexpression {
9080 SequencedSubexpression(SequenceChecker &Self)
9081 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
9082 Self.ModAsSideEffect = &ModAsSideEffect;
9083 }
9084 ~SequencedSubexpression() {
David Majnemerf7e36092016-06-23 00:15:04 +00009085 for (auto &M : llvm::reverse(ModAsSideEffect)) {
9086 UsageInfo &U = Self.UsageMap[M.first];
Richard Smithe8efd992014-12-03 01:05:50 +00009087 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
David Majnemerf7e36092016-06-23 00:15:04 +00009088 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
9089 SideEffectUsage = M.second;
Richard Smithc406cb72013-01-17 01:17:56 +00009090 }
9091 Self.ModAsSideEffect = OldModAsSideEffect;
9092 }
9093
9094 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009095 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
9096 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00009097 };
9098
Richard Smith40238f02013-06-20 22:21:56 +00009099 /// RAII object wrapping the visitation of a subexpression which we might
9100 /// choose to evaluate as a constant. If any subexpression is evaluated and
9101 /// found to be non-constant, this allows us to suppress the evaluation of
9102 /// the outer expression.
9103 class EvaluationTracker {
9104 public:
9105 EvaluationTracker(SequenceChecker &Self)
9106 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
9107 Self.EvalTracker = this;
9108 }
9109 ~EvaluationTracker() {
9110 Self.EvalTracker = Prev;
9111 if (Prev)
9112 Prev->EvalOK &= EvalOK;
9113 }
9114
9115 bool evaluate(const Expr *E, bool &Result) {
9116 if (!EvalOK || E->isValueDependent())
9117 return false;
9118 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
9119 return EvalOK;
9120 }
9121
9122 private:
9123 SequenceChecker &Self;
9124 EvaluationTracker *Prev;
9125 bool EvalOK;
9126 } *EvalTracker;
9127
Richard Smithc406cb72013-01-17 01:17:56 +00009128 /// \brief Find the object which is produced by the specified expression,
9129 /// if any.
9130 Object getObject(Expr *E, bool Mod) const {
9131 E = E->IgnoreParenCasts();
9132 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
9133 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
9134 return getObject(UO->getSubExpr(), Mod);
9135 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9136 if (BO->getOpcode() == BO_Comma)
9137 return getObject(BO->getRHS(), Mod);
9138 if (Mod && BO->isAssignmentOp())
9139 return getObject(BO->getLHS(), Mod);
9140 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
9141 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
9142 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
9143 return ME->getMemberDecl();
9144 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9145 // FIXME: If this is a reference, map through to its value.
9146 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00009147 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +00009148 }
9149
9150 /// \brief Note that an object was modified or used by an expression.
9151 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
9152 Usage &U = UI.Uses[UK];
9153 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
9154 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
9155 ModAsSideEffect->push_back(std::make_pair(O, U));
9156 U.Use = Ref;
9157 U.Seq = Region;
9158 }
9159 }
9160 /// \brief Check whether a modification or use conflicts with a prior usage.
9161 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
9162 bool IsModMod) {
9163 if (UI.Diagnosed)
9164 return;
9165
9166 const Usage &U = UI.Uses[OtherKind];
9167 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
9168 return;
9169
9170 Expr *Mod = U.Use;
9171 Expr *ModOrUse = Ref;
9172 if (OtherKind == UK_Use)
9173 std::swap(Mod, ModOrUse);
9174
9175 SemaRef.Diag(Mod->getExprLoc(),
9176 IsModMod ? diag::warn_unsequenced_mod_mod
9177 : diag::warn_unsequenced_mod_use)
9178 << O << SourceRange(ModOrUse->getExprLoc());
9179 UI.Diagnosed = true;
9180 }
9181
9182 void notePreUse(Object O, Expr *Use) {
9183 UsageInfo &U = UsageMap[O];
9184 // Uses conflict with other modifications.
9185 checkUsage(O, U, Use, UK_ModAsValue, false);
9186 }
9187 void notePostUse(Object O, Expr *Use) {
9188 UsageInfo &U = UsageMap[O];
9189 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
9190 addUsage(U, O, Use, UK_Use);
9191 }
9192
9193 void notePreMod(Object O, Expr *Mod) {
9194 UsageInfo &U = UsageMap[O];
9195 // Modifications conflict with other modifications and with uses.
9196 checkUsage(O, U, Mod, UK_ModAsValue, true);
9197 checkUsage(O, U, Mod, UK_Use, false);
9198 }
9199 void notePostMod(Object O, Expr *Use, UsageKind UK) {
9200 UsageInfo &U = UsageMap[O];
9201 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
9202 addUsage(U, O, Use, UK);
9203 }
9204
9205public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009206 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +00009207 : Base(S.Context), SemaRef(S), Region(Tree.root()),
9208 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +00009209 Visit(E);
9210 }
9211
9212 void VisitStmt(Stmt *S) {
9213 // Skip all statements which aren't expressions for now.
9214 }
9215
9216 void VisitExpr(Expr *E) {
9217 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00009218 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00009219 }
9220
9221 void VisitCastExpr(CastExpr *E) {
9222 Object O = Object();
9223 if (E->getCastKind() == CK_LValueToRValue)
9224 O = getObject(E->getSubExpr(), false);
9225
9226 if (O)
9227 notePreUse(O, E);
9228 VisitExpr(E);
9229 if (O)
9230 notePostUse(O, E);
9231 }
9232
9233 void VisitBinComma(BinaryOperator *BO) {
9234 // C++11 [expr.comma]p1:
9235 // Every value computation and side effect associated with the left
9236 // expression is sequenced before every value computation and side
9237 // effect associated with the right expression.
9238 SequenceTree::Seq LHS = Tree.allocate(Region);
9239 SequenceTree::Seq RHS = Tree.allocate(Region);
9240 SequenceTree::Seq OldRegion = Region;
9241
9242 {
9243 SequencedSubexpression SeqLHS(*this);
9244 Region = LHS;
9245 Visit(BO->getLHS());
9246 }
9247
9248 Region = RHS;
9249 Visit(BO->getRHS());
9250
9251 Region = OldRegion;
9252
9253 // Forget that LHS and RHS are sequenced. They are both unsequenced
9254 // with respect to other stuff.
9255 Tree.merge(LHS);
9256 Tree.merge(RHS);
9257 }
9258
9259 void VisitBinAssign(BinaryOperator *BO) {
9260 // The modification is sequenced after the value computation of the LHS
9261 // and RHS, so check it before inspecting the operands and update the
9262 // map afterwards.
9263 Object O = getObject(BO->getLHS(), true);
9264 if (!O)
9265 return VisitExpr(BO);
9266
9267 notePreMod(O, BO);
9268
9269 // C++11 [expr.ass]p7:
9270 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
9271 // only once.
9272 //
9273 // Therefore, for a compound assignment operator, O is considered used
9274 // everywhere except within the evaluation of E1 itself.
9275 if (isa<CompoundAssignOperator>(BO))
9276 notePreUse(O, BO);
9277
9278 Visit(BO->getLHS());
9279
9280 if (isa<CompoundAssignOperator>(BO))
9281 notePostUse(O, BO);
9282
9283 Visit(BO->getRHS());
9284
Richard Smith83e37bee2013-06-26 23:16:51 +00009285 // C++11 [expr.ass]p1:
9286 // the assignment is sequenced [...] before the value computation of the
9287 // assignment expression.
9288 // C11 6.5.16/3 has no such rule.
9289 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
9290 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00009291 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009292
Richard Smithc406cb72013-01-17 01:17:56 +00009293 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
9294 VisitBinAssign(CAO);
9295 }
9296
9297 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
9298 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
9299 void VisitUnaryPreIncDec(UnaryOperator *UO) {
9300 Object O = getObject(UO->getSubExpr(), true);
9301 if (!O)
9302 return VisitExpr(UO);
9303
9304 notePreMod(O, UO);
9305 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +00009306 // C++11 [expr.pre.incr]p1:
9307 // the expression ++x is equivalent to x+=1
9308 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
9309 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00009310 }
9311
9312 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
9313 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
9314 void VisitUnaryPostIncDec(UnaryOperator *UO) {
9315 Object O = getObject(UO->getSubExpr(), true);
9316 if (!O)
9317 return VisitExpr(UO);
9318
9319 notePreMod(O, UO);
9320 Visit(UO->getSubExpr());
9321 notePostMod(O, UO, UK_ModAsSideEffect);
9322 }
9323
9324 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
9325 void VisitBinLOr(BinaryOperator *BO) {
9326 // The side-effects of the LHS of an '&&' are sequenced before the
9327 // value computation of the RHS, and hence before the value computation
9328 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
9329 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +00009330 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00009331 {
9332 SequencedSubexpression Sequenced(*this);
9333 Visit(BO->getLHS());
9334 }
9335
9336 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00009337 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00009338 if (!Result)
9339 Visit(BO->getRHS());
9340 } else {
9341 // Check for unsequenced operations in the RHS, treating it as an
9342 // entirely separate evaluation.
9343 //
9344 // FIXME: If there are operations in the RHS which are unsequenced
9345 // with respect to operations outside the RHS, and those operations
9346 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +00009347 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00009348 }
Richard Smithc406cb72013-01-17 01:17:56 +00009349 }
9350 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +00009351 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00009352 {
9353 SequencedSubexpression Sequenced(*this);
9354 Visit(BO->getLHS());
9355 }
9356
9357 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00009358 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00009359 if (Result)
9360 Visit(BO->getRHS());
9361 } else {
Richard Smithd33f5202013-01-17 23:18:09 +00009362 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00009363 }
Richard Smithc406cb72013-01-17 01:17:56 +00009364 }
9365
9366 // Only visit the condition, unless we can be sure which subexpression will
9367 // be chosen.
9368 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +00009369 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +00009370 {
9371 SequencedSubexpression Sequenced(*this);
9372 Visit(CO->getCond());
9373 }
Richard Smithc406cb72013-01-17 01:17:56 +00009374
9375 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00009376 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +00009377 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00009378 else {
Richard Smithd33f5202013-01-17 23:18:09 +00009379 WorkList.push_back(CO->getTrueExpr());
9380 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00009381 }
Richard Smithc406cb72013-01-17 01:17:56 +00009382 }
9383
Richard Smithe3dbfe02013-06-30 10:40:20 +00009384 void VisitCallExpr(CallExpr *CE) {
9385 // C++11 [intro.execution]p15:
9386 // When calling a function [...], every value computation and side effect
9387 // associated with any argument expression, or with the postfix expression
9388 // designating the called function, is sequenced before execution of every
9389 // expression or statement in the body of the function [and thus before
9390 // the value computation of its result].
9391 SequencedSubexpression Sequenced(*this);
9392 Base::VisitCallExpr(CE);
9393
9394 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
9395 }
9396
Richard Smithc406cb72013-01-17 01:17:56 +00009397 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +00009398 // This is a call, so all subexpressions are sequenced before the result.
9399 SequencedSubexpression Sequenced(*this);
9400
Richard Smithc406cb72013-01-17 01:17:56 +00009401 if (!CCE->isListInitialization())
9402 return VisitExpr(CCE);
9403
9404 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009405 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00009406 SequenceTree::Seq Parent = Region;
9407 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
9408 E = CCE->arg_end();
9409 I != E; ++I) {
9410 Region = Tree.allocate(Parent);
9411 Elts.push_back(Region);
9412 Visit(*I);
9413 }
9414
9415 // Forget that the initializers are sequenced.
9416 Region = Parent;
9417 for (unsigned I = 0; I < Elts.size(); ++I)
9418 Tree.merge(Elts[I]);
9419 }
9420
9421 void VisitInitListExpr(InitListExpr *ILE) {
9422 if (!SemaRef.getLangOpts().CPlusPlus11)
9423 return VisitExpr(ILE);
9424
9425 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009426 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00009427 SequenceTree::Seq Parent = Region;
9428 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
9429 Expr *E = ILE->getInit(I);
9430 if (!E) continue;
9431 Region = Tree.allocate(Parent);
9432 Elts.push_back(Region);
9433 Visit(E);
9434 }
9435
9436 // Forget that the initializers are sequenced.
9437 Region = Parent;
9438 for (unsigned I = 0; I < Elts.size(); ++I)
9439 Tree.merge(Elts[I]);
9440 }
9441};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009442} // end anonymous namespace
Richard Smithc406cb72013-01-17 01:17:56 +00009443
9444void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009445 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +00009446 WorkList.push_back(E);
9447 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00009448 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +00009449 SequenceChecker(*this, Item, WorkList);
9450 }
Richard Smithc406cb72013-01-17 01:17:56 +00009451}
9452
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009453void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
9454 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +00009455 CheckImplicitConversions(E, CheckLoc);
Richard Trieu71d74d42016-08-05 21:02:34 +00009456 if (!E->isInstantiationDependent())
9457 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009458 if (!IsConstexpr && !E->isValueDependent())
9459 CheckForIntOverflow(E);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +00009460 DiagnoseMisalignedMembers();
Richard Smithc406cb72013-01-17 01:17:56 +00009461}
9462
John McCall1f425642010-11-11 03:21:53 +00009463void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
9464 FieldDecl *BitField,
9465 Expr *Init) {
9466 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
9467}
9468
David Majnemer61a5bbf2015-04-07 22:08:51 +00009469static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
9470 SourceLocation Loc) {
9471 if (!PType->isVariablyModifiedType())
9472 return;
9473 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
9474 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
9475 return;
9476 }
David Majnemerdf8f73f2015-04-09 19:53:25 +00009477 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
9478 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
9479 return;
9480 }
David Majnemer61a5bbf2015-04-07 22:08:51 +00009481 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
9482 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
9483 return;
9484 }
9485
9486 const ArrayType *AT = S.Context.getAsArrayType(PType);
9487 if (!AT)
9488 return;
9489
9490 if (AT->getSizeModifier() != ArrayType::Star) {
9491 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
9492 return;
9493 }
9494
9495 S.Diag(Loc, diag::err_array_star_in_function_definition);
9496}
9497
Mike Stump0c2ec772010-01-21 03:59:47 +00009498/// CheckParmsForFunctionDef - Check that the parameters of the given
9499/// function are appropriate for the definition of a function. This
9500/// takes care of any checks that cannot be performed on the
9501/// declaration itself, e.g., that the types of each of the function
9502/// parameters are complete.
David Majnemer59f77922016-06-24 04:05:48 +00009503bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
Douglas Gregorb524d902010-11-01 18:37:59 +00009504 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +00009505 bool HasInvalidParm = false;
David Majnemer59f77922016-06-24 04:05:48 +00009506 for (ParmVarDecl *Param : Parameters) {
Mike Stump0c2ec772010-01-21 03:59:47 +00009507 // C99 6.7.5.3p4: the parameters in a parameter type list in a
9508 // function declarator that is part of a function definition of
9509 // that function shall not have incomplete type.
9510 //
9511 // This is also C++ [dcl.fct]p6.
9512 if (!Param->isInvalidDecl() &&
9513 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00009514 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +00009515 Param->setInvalidDecl();
9516 HasInvalidParm = true;
9517 }
9518
9519 // C99 6.9.1p5: If the declarator includes a parameter type list, the
9520 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +00009521 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +00009522 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +00009523 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00009524 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +00009525 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +00009526
9527 // C99 6.7.5.3p12:
9528 // If the function declarator is not part of a definition of that
9529 // function, parameters may have incomplete type and may use the [*]
9530 // notation in their sequences of declarator specifiers to specify
9531 // variable length array types.
9532 QualType PType = Param->getOriginalType();
David Majnemer61a5bbf2015-04-07 22:08:51 +00009533 // FIXME: This diagnostic should point the '[*]' if source-location
9534 // information is added for it.
9535 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00009536
9537 // MSVC destroys objects passed by value in the callee. Therefore a
9538 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00009539 // object's destructor. However, we don't perform any direct access check
9540 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +00009541 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
9542 .getCXXABI()
9543 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +00009544 if (!Param->isInvalidDecl()) {
9545 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
9546 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
9547 if (!ClassDecl->isInvalidDecl() &&
9548 !ClassDecl->hasIrrelevantDestructor() &&
9549 !ClassDecl->isDependentContext()) {
9550 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
9551 MarkFunctionReferenced(Param->getLocation(), Destructor);
9552 DiagnoseUseOfDecl(Destructor, Param->getLocation());
9553 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00009554 }
9555 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00009556 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009557
9558 // Parameters with the pass_object_size attribute only need to be marked
9559 // constant at function definitions. Because we lack information about
9560 // whether we're on a declaration or definition when we're instantiating the
9561 // attribute, we need to check for constness here.
9562 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
9563 if (!Param->getType().isConstQualified())
9564 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
9565 << Attr->getSpelling() << 1;
Mike Stump0c2ec772010-01-21 03:59:47 +00009566 }
9567
9568 return HasInvalidParm;
9569}
John McCall2b5c1b22010-08-12 21:44:57 +00009570
9571/// CheckCastAlign - Implements -Wcast-align, which warns when a
9572/// pointer cast increases the alignment requirements.
9573void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
9574 // This is actually a lot of work to potentially be doing on every
9575 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009576 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +00009577 return;
9578
9579 // Ignore dependent types.
9580 if (T->isDependentType() || Op->getType()->isDependentType())
9581 return;
9582
9583 // Require that the destination be a pointer type.
9584 const PointerType *DestPtr = T->getAs<PointerType>();
9585 if (!DestPtr) return;
9586
9587 // If the destination has alignment 1, we're done.
9588 QualType DestPointee = DestPtr->getPointeeType();
9589 if (DestPointee->isIncompleteType()) return;
9590 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
9591 if (DestAlign.isOne()) return;
9592
9593 // Require that the source be a pointer type.
9594 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
9595 if (!SrcPtr) return;
9596 QualType SrcPointee = SrcPtr->getPointeeType();
9597
9598 // Whitelist casts from cv void*. We already implicitly
9599 // whitelisted casts to cv void*, since they have alignment 1.
9600 // Also whitelist casts involving incomplete types, which implicitly
9601 // includes 'void'.
9602 if (SrcPointee->isIncompleteType()) return;
9603
9604 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
9605 if (SrcAlign >= DestAlign) return;
9606
9607 Diag(TRange.getBegin(), diag::warn_cast_align)
9608 << Op->getType() << T
9609 << static_cast<unsigned>(SrcAlign.getQuantity())
9610 << static_cast<unsigned>(DestAlign.getQuantity())
9611 << TRange << Op->getSourceRange();
9612}
9613
Chandler Carruth28389f02011-08-05 09:10:50 +00009614/// \brief Check whether this array fits the idiom of a size-one tail padded
9615/// array member of a struct.
9616///
9617/// We avoid emitting out-of-bounds access warnings for such arrays as they are
9618/// commonly used to emulate flexible arrays in C89 code.
Benjamin Kramer7320b992016-06-15 14:20:56 +00009619static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
Chandler Carruth28389f02011-08-05 09:10:50 +00009620 const NamedDecl *ND) {
9621 if (Size != 1 || !ND) return false;
9622
9623 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
9624 if (!FD) return false;
9625
9626 // Don't consider sizes resulting from macro expansions or template argument
9627 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +00009628
9629 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00009630 while (TInfo) {
9631 TypeLoc TL = TInfo->getTypeLoc();
9632 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +00009633 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
9634 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00009635 TInfo = TDL->getTypeSourceInfo();
9636 continue;
9637 }
David Blaikie6adc78e2013-02-18 22:06:02 +00009638 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
9639 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +00009640 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
9641 return false;
9642 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +00009643 break;
Sean Callanan06a48a62012-05-04 18:22:53 +00009644 }
Chandler Carruth28389f02011-08-05 09:10:50 +00009645
9646 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +00009647 if (!RD) return false;
9648 if (RD->isUnion()) return false;
9649 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
9650 if (!CRD->isStandardLayout()) return false;
9651 }
Chandler Carruth28389f02011-08-05 09:10:50 +00009652
Benjamin Kramer8c543672011-08-06 03:04:42 +00009653 // See if this is the last field decl in the record.
9654 const Decl *D = FD;
9655 while ((D = D->getNextDeclInContext()))
9656 if (isa<FieldDecl>(D))
9657 return false;
9658 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +00009659}
9660
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009661void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009662 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +00009663 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +00009664 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009665 if (IndexExpr->isValueDependent())
9666 return;
9667
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00009668 const Type *EffectiveType =
9669 BaseExpr->getType()->getPointeeOrArrayElementType();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009670 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009671 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009672 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009673 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +00009674 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +00009675
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009676 llvm::APSInt index;
Richard Smith0c6124b2015-12-03 01:36:22 +00009677 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
Ted Kremenek64699be2011-02-16 01:57:07 +00009678 return;
Richard Smith13f67182011-12-16 19:31:14 +00009679 if (IndexNegated)
9680 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +00009681
Craig Topperc3ec1492014-05-26 06:22:03 +00009682 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +00009683 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
9684 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +00009685 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +00009686 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +00009687
Ted Kremeneke4b316c2011-02-23 23:06:04 +00009688 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00009689 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +00009690 if (!size.isStrictlyPositive())
9691 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009692
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00009693 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
Nico Weber7c299802011-09-17 22:59:41 +00009694 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009695 // Make sure we're comparing apples to apples when comparing index to size
9696 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
9697 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +00009698 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +00009699 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009700 if (ptrarith_typesize != array_typesize) {
9701 // There's a cast to a different size type involved
9702 uint64_t ratio = array_typesize / ptrarith_typesize;
9703 // TODO: Be smarter about handling cases where array_typesize is not a
9704 // multiple of ptrarith_typesize
9705 if (ptrarith_typesize * ratio == array_typesize)
9706 size *= llvm::APInt(size.getBitWidth(), ratio);
9707 }
9708 }
9709
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009710 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00009711 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00009712 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00009713 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00009714
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009715 // For array subscripting the index must be less than size, but for pointer
9716 // arithmetic also allow the index (offset) to be equal to size since
9717 // computing the next address after the end of the array is legal and
9718 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +00009719 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +00009720 return;
9721
9722 // Also don't warn for arrays of size 1 which are members of some
9723 // structure. These are often used to approximate flexible arrays in C89
9724 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009725 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +00009726 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009727
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009728 // Suppress the warning if the subscript expression (as identified by the
9729 // ']' location) and the index expression are both from macro expansions
9730 // within a system header.
9731 if (ASE) {
9732 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
9733 ASE->getRBracketLoc());
9734 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
9735 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
9736 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +00009737 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009738 return;
9739 }
9740 }
9741
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009742 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009743 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009744 DiagID = diag::warn_array_index_exceeds_bounds;
9745
9746 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
9747 PDiag(DiagID) << index.toString(10, true)
9748 << size.toString(10, true)
9749 << (unsigned)size.getLimitedValue(~0U)
9750 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009751 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009752 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009753 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009754 DiagID = diag::warn_ptr_arith_precedes_bounds;
9755 if (index.isNegative()) index = -index;
9756 }
9757
9758 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
9759 PDiag(DiagID) << index.toString(10, true)
9760 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +00009761 }
Chandler Carruth1af88f12011-02-17 21:10:52 +00009762
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +00009763 if (!ND) {
9764 // Try harder to find a NamedDecl to point at in the note.
9765 while (const ArraySubscriptExpr *ASE =
9766 dyn_cast<ArraySubscriptExpr>(BaseExpr))
9767 BaseExpr = ASE->getBase()->IgnoreParenCasts();
9768 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
9769 ND = dyn_cast<NamedDecl>(DRE->getDecl());
9770 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
9771 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
9772 }
9773
Chandler Carruth1af88f12011-02-17 21:10:52 +00009774 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009775 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
9776 PDiag(diag::note_array_index_out_of_bounds)
9777 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +00009778}
9779
Ted Kremenekdf26df72011-03-01 18:41:00 +00009780void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009781 int AllowOnePastEnd = 0;
9782 while (expr) {
9783 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +00009784 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009785 case Stmt::ArraySubscriptExprClass: {
9786 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009787 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009788 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +00009789 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009790 }
Alexey Bataev1a3320e2015-08-25 14:24:04 +00009791 case Stmt::OMPArraySectionExprClass: {
9792 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
9793 if (ASE->getLowerBound())
9794 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
9795 /*ASE=*/nullptr, AllowOnePastEnd > 0);
9796 return;
9797 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009798 case Stmt::UnaryOperatorClass: {
9799 // Only unwrap the * and & unary operators
9800 const UnaryOperator *UO = cast<UnaryOperator>(expr);
9801 expr = UO->getSubExpr();
9802 switch (UO->getOpcode()) {
9803 case UO_AddrOf:
9804 AllowOnePastEnd++;
9805 break;
9806 case UO_Deref:
9807 AllowOnePastEnd--;
9808 break;
9809 default:
9810 return;
9811 }
9812 break;
9813 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00009814 case Stmt::ConditionalOperatorClass: {
9815 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
9816 if (const Expr *lhs = cond->getLHS())
9817 CheckArrayAccess(lhs);
9818 if (const Expr *rhs = cond->getRHS())
9819 CheckArrayAccess(rhs);
9820 return;
9821 }
9822 default:
9823 return;
9824 }
Peter Collingbourne91147592011-04-15 00:35:48 +00009825 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00009826}
John McCall31168b02011-06-15 23:02:42 +00009827
9828//===--- CHECK: Objective-C retain cycles ----------------------------------//
9829
9830namespace {
9831 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +00009832 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +00009833 VarDecl *Variable;
9834 SourceRange Range;
9835 SourceLocation Loc;
9836 bool Indirect;
9837
9838 void setLocsFrom(Expr *e) {
9839 Loc = e->getExprLoc();
9840 Range = e->getSourceRange();
9841 }
9842 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009843} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +00009844
9845/// Consider whether capturing the given variable can possibly lead to
9846/// a retain cycle.
9847static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00009848 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +00009849 // lifetime. In MRR, it's captured strongly if the variable is
9850 // __block and has an appropriate type.
9851 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
9852 return false;
9853
9854 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00009855 if (ref)
9856 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +00009857 return true;
9858}
9859
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009860static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +00009861 while (true) {
9862 e = e->IgnoreParens();
9863 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
9864 switch (cast->getCastKind()) {
9865 case CK_BitCast:
9866 case CK_LValueBitCast:
9867 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00009868 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +00009869 e = cast->getSubExpr();
9870 continue;
9871
John McCall31168b02011-06-15 23:02:42 +00009872 default:
9873 return false;
9874 }
9875 }
9876
9877 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
9878 ObjCIvarDecl *ivar = ref->getDecl();
9879 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
9880 return false;
9881
9882 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009883 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +00009884 return false;
9885
9886 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
9887 owner.Indirect = true;
9888 return true;
9889 }
9890
9891 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
9892 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
9893 if (!var) return false;
9894 return considerVariable(var, ref, owner);
9895 }
9896
John McCall31168b02011-06-15 23:02:42 +00009897 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
9898 if (member->isArrow()) return false;
9899
9900 // Don't count this as an indirect ownership.
9901 e = member->getBase();
9902 continue;
9903 }
9904
John McCallfe96e0b2011-11-06 09:01:30 +00009905 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
9906 // Only pay attention to pseudo-objects on property references.
9907 ObjCPropertyRefExpr *pre
9908 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
9909 ->IgnoreParens());
9910 if (!pre) return false;
9911 if (pre->isImplicitProperty()) return false;
9912 ObjCPropertyDecl *property = pre->getExplicitProperty();
9913 if (!property->isRetaining() &&
9914 !(property->getPropertyIvarDecl() &&
9915 property->getPropertyIvarDecl()->getType()
9916 .getObjCLifetime() == Qualifiers::OCL_Strong))
9917 return false;
9918
9919 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009920 if (pre->isSuperReceiver()) {
9921 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
9922 if (!owner.Variable)
9923 return false;
9924 owner.Loc = pre->getLocation();
9925 owner.Range = pre->getSourceRange();
9926 return true;
9927 }
John McCallfe96e0b2011-11-06 09:01:30 +00009928 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
9929 ->getSourceExpr());
9930 continue;
9931 }
9932
John McCall31168b02011-06-15 23:02:42 +00009933 // Array ivars?
9934
9935 return false;
9936 }
9937}
9938
9939namespace {
9940 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
9941 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
9942 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00009943 Context(Context), Variable(variable), Capturer(nullptr),
9944 VarWillBeReased(false) {}
9945 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +00009946 VarDecl *Variable;
9947 Expr *Capturer;
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00009948 bool VarWillBeReased;
John McCall31168b02011-06-15 23:02:42 +00009949
9950 void VisitDeclRefExpr(DeclRefExpr *ref) {
9951 if (ref->getDecl() == Variable && !Capturer)
9952 Capturer = ref;
9953 }
9954
John McCall31168b02011-06-15 23:02:42 +00009955 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
9956 if (Capturer) return;
9957 Visit(ref->getBase());
9958 if (Capturer && ref->isFreeIvar())
9959 Capturer = ref;
9960 }
9961
9962 void VisitBlockExpr(BlockExpr *block) {
9963 // Look inside nested blocks
9964 if (block->getBlockDecl()->capturesVariable(Variable))
9965 Visit(block->getBlockDecl()->getBody());
9966 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +00009967
9968 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
9969 if (Capturer) return;
9970 if (OVE->getSourceExpr())
9971 Visit(OVE->getSourceExpr());
9972 }
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00009973 void VisitBinaryOperator(BinaryOperator *BinOp) {
9974 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
9975 return;
9976 Expr *LHS = BinOp->getLHS();
9977 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
9978 if (DRE->getDecl() != Variable)
9979 return;
9980 if (Expr *RHS = BinOp->getRHS()) {
9981 RHS = RHS->IgnoreParenCasts();
9982 llvm::APSInt Value;
9983 VarWillBeReased =
9984 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
9985 }
9986 }
9987 }
John McCall31168b02011-06-15 23:02:42 +00009988 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009989} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +00009990
9991/// Check whether the given argument is a block which captures a
9992/// variable.
9993static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
9994 assert(owner.Variable && owner.Loc.isValid());
9995
9996 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +00009997
9998 // Look through [^{...} copy] and Block_copy(^{...}).
9999 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
10000 Selector Cmd = ME->getSelector();
10001 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
10002 e = ME->getInstanceReceiver();
10003 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +000010004 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +000010005 e = e->IgnoreParenCasts();
10006 }
10007 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
10008 if (CE->getNumArgs() == 1) {
10009 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +000010010 if (Fn) {
10011 const IdentifierInfo *FnI = Fn->getIdentifier();
10012 if (FnI && FnI->isStr("_Block_copy")) {
10013 e = CE->getArg(0)->IgnoreParenCasts();
10014 }
10015 }
Jordan Rose67e887c2012-09-17 17:54:30 +000010016 }
10017 }
10018
John McCall31168b02011-06-15 23:02:42 +000010019 BlockExpr *block = dyn_cast<BlockExpr>(e);
10020 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +000010021 return nullptr;
John McCall31168b02011-06-15 23:02:42 +000010022
10023 FindCaptureVisitor visitor(S.Context, owner.Variable);
10024 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000010025 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +000010026}
10027
10028static void diagnoseRetainCycle(Sema &S, Expr *capturer,
10029 RetainCycleOwner &owner) {
10030 assert(capturer);
10031 assert(owner.Variable && owner.Loc.isValid());
10032
10033 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
10034 << owner.Variable << capturer->getSourceRange();
10035 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
10036 << owner.Indirect << owner.Range;
10037}
10038
10039/// Check for a keyword selector that starts with the word 'add' or
10040/// 'set'.
10041static bool isSetterLikeSelector(Selector sel) {
10042 if (sel.isUnarySelector()) return false;
10043
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010044 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +000010045 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +000010046 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +000010047 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +000010048 else if (str.startswith("add")) {
10049 // Specially whitelist 'addOperationWithBlock:'.
10050 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
10051 return false;
10052 str = str.substr(3);
10053 }
John McCall31168b02011-06-15 23:02:42 +000010054 else
10055 return false;
10056
10057 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +000010058 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +000010059}
10060
Benjamin Kramer3a743452015-03-09 15:03:32 +000010061static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
10062 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000010063 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
10064 Message->getReceiverInterface(),
10065 NSAPI::ClassId_NSMutableArray);
10066 if (!IsMutableArray) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010067 return None;
10068 }
10069
10070 Selector Sel = Message->getSelector();
10071
10072 Optional<NSAPI::NSArrayMethodKind> MKOpt =
10073 S.NSAPIObj->getNSArrayMethodKind(Sel);
10074 if (!MKOpt) {
10075 return None;
10076 }
10077
10078 NSAPI::NSArrayMethodKind MK = *MKOpt;
10079
10080 switch (MK) {
10081 case NSAPI::NSMutableArr_addObject:
10082 case NSAPI::NSMutableArr_insertObjectAtIndex:
10083 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
10084 return 0;
10085 case NSAPI::NSMutableArr_replaceObjectAtIndex:
10086 return 1;
10087
10088 default:
10089 return None;
10090 }
10091
10092 return None;
10093}
10094
10095static
10096Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
10097 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000010098 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
10099 Message->getReceiverInterface(),
10100 NSAPI::ClassId_NSMutableDictionary);
10101 if (!IsMutableDictionary) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010102 return None;
10103 }
10104
10105 Selector Sel = Message->getSelector();
10106
10107 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
10108 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
10109 if (!MKOpt) {
10110 return None;
10111 }
10112
10113 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
10114
10115 switch (MK) {
10116 case NSAPI::NSMutableDict_setObjectForKey:
10117 case NSAPI::NSMutableDict_setValueForKey:
10118 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
10119 return 0;
10120
10121 default:
10122 return None;
10123 }
10124
10125 return None;
10126}
10127
10128static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000010129 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
10130 Message->getReceiverInterface(),
10131 NSAPI::ClassId_NSMutableSet);
Alex Denisove1d882c2015-03-04 17:55:52 +000010132
Alex Denisov5dfac812015-08-06 04:51:14 +000010133 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
10134 Message->getReceiverInterface(),
10135 NSAPI::ClassId_NSMutableOrderedSet);
10136 if (!IsMutableSet && !IsMutableOrderedSet) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010137 return None;
10138 }
10139
10140 Selector Sel = Message->getSelector();
10141
10142 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
10143 if (!MKOpt) {
10144 return None;
10145 }
10146
10147 NSAPI::NSSetMethodKind MK = *MKOpt;
10148
10149 switch (MK) {
10150 case NSAPI::NSMutableSet_addObject:
10151 case NSAPI::NSOrderedSet_setObjectAtIndex:
10152 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
10153 case NSAPI::NSOrderedSet_insertObjectAtIndex:
10154 return 0;
10155 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
10156 return 1;
10157 }
10158
10159 return None;
10160}
10161
10162void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
10163 if (!Message->isInstanceMessage()) {
10164 return;
10165 }
10166
10167 Optional<int> ArgOpt;
10168
10169 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
10170 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
10171 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
10172 return;
10173 }
10174
10175 int ArgIndex = *ArgOpt;
10176
Alex Denisove1d882c2015-03-04 17:55:52 +000010177 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
10178 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
10179 Arg = OE->getSourceExpr()->IgnoreImpCasts();
10180 }
10181
Alex Denisov5dfac812015-08-06 04:51:14 +000010182 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010183 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
Alex Denisov5dfac812015-08-06 04:51:14 +000010184 if (ArgRE->isObjCSelfExpr()) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010185 Diag(Message->getSourceRange().getBegin(),
10186 diag::warn_objc_circular_container)
Alex Denisov5dfac812015-08-06 04:51:14 +000010187 << ArgRE->getDecl()->getName() << StringRef("super");
Alex Denisove1d882c2015-03-04 17:55:52 +000010188 }
10189 }
Alex Denisov5dfac812015-08-06 04:51:14 +000010190 } else {
10191 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
10192
10193 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
10194 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
10195 }
10196
10197 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
10198 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
10199 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
10200 ValueDecl *Decl = ReceiverRE->getDecl();
10201 Diag(Message->getSourceRange().getBegin(),
10202 diag::warn_objc_circular_container)
10203 << Decl->getName() << Decl->getName();
10204 if (!ArgRE->isObjCSelfExpr()) {
10205 Diag(Decl->getLocation(),
10206 diag::note_objc_circular_container_declared_here)
10207 << Decl->getName();
10208 }
10209 }
10210 }
10211 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
10212 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
10213 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
10214 ObjCIvarDecl *Decl = IvarRE->getDecl();
10215 Diag(Message->getSourceRange().getBegin(),
10216 diag::warn_objc_circular_container)
10217 << Decl->getName() << Decl->getName();
10218 Diag(Decl->getLocation(),
10219 diag::note_objc_circular_container_declared_here)
10220 << Decl->getName();
10221 }
Alex Denisove1d882c2015-03-04 17:55:52 +000010222 }
10223 }
10224 }
Alex Denisove1d882c2015-03-04 17:55:52 +000010225}
10226
John McCall31168b02011-06-15 23:02:42 +000010227/// Check a message send to see if it's likely to cause a retain cycle.
10228void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
10229 // Only check instance methods whose selector looks like a setter.
10230 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
10231 return;
10232
10233 // Try to find a variable that the receiver is strongly owned by.
10234 RetainCycleOwner owner;
10235 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010236 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +000010237 return;
10238 } else {
10239 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
10240 owner.Variable = getCurMethodDecl()->getSelfDecl();
10241 owner.Loc = msg->getSuperLoc();
10242 owner.Range = msg->getSuperLoc();
10243 }
10244
10245 // Check whether the receiver is captured by any of the arguments.
10246 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
10247 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
10248 return diagnoseRetainCycle(*this, capturer, owner);
10249}
10250
10251/// Check a property assign to see if it's likely to cause a retain cycle.
10252void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
10253 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010254 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +000010255 return;
10256
10257 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
10258 diagnoseRetainCycle(*this, capturer, owner);
10259}
10260
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000010261void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
10262 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +000010263 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000010264 return;
10265
10266 // Because we don't have an expression for the variable, we have to set the
10267 // location explicitly here.
10268 Owner.Loc = Var->getLocation();
10269 Owner.Range = Var->getSourceRange();
10270
10271 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
10272 diagnoseRetainCycle(*this, Capturer, Owner);
10273}
10274
Ted Kremenek9304da92012-12-21 08:04:28 +000010275static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
10276 Expr *RHS, bool isProperty) {
10277 // Check if RHS is an Objective-C object literal, which also can get
10278 // immediately zapped in a weak reference. Note that we explicitly
10279 // allow ObjCStringLiterals, since those are designed to never really die.
10280 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000010281
Ted Kremenek64873352012-12-21 22:46:35 +000010282 // This enum needs to match with the 'select' in
10283 // warn_objc_arc_literal_assign (off-by-1).
10284 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
10285 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
10286 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000010287
10288 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +000010289 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +000010290 << (isProperty ? 0 : 1)
10291 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000010292
10293 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +000010294}
10295
Ted Kremenekc1f014a2012-12-21 19:45:30 +000010296static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
10297 Qualifiers::ObjCLifetime LT,
10298 Expr *RHS, bool isProperty) {
10299 // Strip off any implicit cast added to get to the one ARC-specific.
10300 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
10301 if (cast->getCastKind() == CK_ARCConsumeObject) {
10302 S.Diag(Loc, diag::warn_arc_retained_assign)
10303 << (LT == Qualifiers::OCL_ExplicitNone)
10304 << (isProperty ? 0 : 1)
10305 << RHS->getSourceRange();
10306 return true;
10307 }
10308 RHS = cast->getSubExpr();
10309 }
10310
10311 if (LT == Qualifiers::OCL_Weak &&
10312 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
10313 return true;
10314
10315 return false;
10316}
10317
Ted Kremenekb36234d2012-12-21 08:04:20 +000010318bool Sema::checkUnsafeAssigns(SourceLocation Loc,
10319 QualType LHS, Expr *RHS) {
10320 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
10321
10322 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
10323 return false;
10324
10325 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
10326 return true;
10327
10328 return false;
10329}
10330
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010331void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
10332 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000010333 QualType LHSType;
10334 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +000010335 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000010336 ObjCPropertyRefExpr *PRE
10337 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
10338 if (PRE && !PRE->isImplicitProperty()) {
10339 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
10340 if (PD)
10341 LHSType = PD->getType();
10342 }
10343
10344 if (LHSType.isNull())
10345 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +000010346
10347 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
10348
10349 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000010350 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +000010351 getCurFunction()->markSafeWeakUse(LHS);
10352 }
10353
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010354 if (checkUnsafeAssigns(Loc, LHSType, RHS))
10355 return;
Jordan Rose657b5f42012-09-28 22:21:35 +000010356
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010357 // FIXME. Check for other life times.
10358 if (LT != Qualifiers::OCL_None)
10359 return;
10360
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000010361 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010362 if (PRE->isImplicitProperty())
10363 return;
10364 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
10365 if (!PD)
10366 return;
10367
Bill Wendling44426052012-12-20 19:22:21 +000010368 unsigned Attributes = PD->getPropertyAttributes();
10369 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000010370 // when 'assign' attribute was not explicitly specified
10371 // by user, ignore it and rely on property type itself
10372 // for lifetime info.
10373 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
10374 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
10375 LHSType->isObjCRetainableType())
10376 return;
10377
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010378 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +000010379 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010380 Diag(Loc, diag::warn_arc_retained_property_assign)
10381 << RHS->getSourceRange();
10382 return;
10383 }
10384 RHS = cast->getSubExpr();
10385 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000010386 }
Bill Wendling44426052012-12-20 19:22:21 +000010387 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +000010388 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
10389 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +000010390 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010391 }
10392}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010393
10394//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
10395
10396namespace {
10397bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
10398 SourceLocation StmtLoc,
10399 const NullStmt *Body) {
10400 // Do not warn if the body is a macro that expands to nothing, e.g:
10401 //
10402 // #define CALL(x)
10403 // if (condition)
10404 // CALL(0);
10405 //
10406 if (Body->hasLeadingEmptyMacro())
10407 return false;
10408
10409 // Get line numbers of statement and body.
10410 bool StmtLineInvalid;
Dmitri Gribenkoad80af82015-03-15 01:08:23 +000010411 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010412 &StmtLineInvalid);
10413 if (StmtLineInvalid)
10414 return false;
10415
10416 bool BodyLineInvalid;
10417 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
10418 &BodyLineInvalid);
10419 if (BodyLineInvalid)
10420 return false;
10421
10422 // Warn if null statement and body are on the same line.
10423 if (StmtLine != BodyLine)
10424 return false;
10425
10426 return true;
10427}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010428} // end anonymous namespace
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010429
10430void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
10431 const Stmt *Body,
10432 unsigned DiagID) {
10433 // Since this is a syntactic check, don't emit diagnostic for template
10434 // instantiations, this just adds noise.
10435 if (CurrentInstantiationScope)
10436 return;
10437
10438 // The body should be a null statement.
10439 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
10440 if (!NBody)
10441 return;
10442
10443 // Do the usual checks.
10444 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
10445 return;
10446
10447 Diag(NBody->getSemiLoc(), DiagID);
10448 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
10449}
10450
10451void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
10452 const Stmt *PossibleBody) {
10453 assert(!CurrentInstantiationScope); // Ensured by caller
10454
10455 SourceLocation StmtLoc;
10456 const Stmt *Body;
10457 unsigned DiagID;
10458 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
10459 StmtLoc = FS->getRParenLoc();
10460 Body = FS->getBody();
10461 DiagID = diag::warn_empty_for_body;
10462 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
10463 StmtLoc = WS->getCond()->getSourceRange().getEnd();
10464 Body = WS->getBody();
10465 DiagID = diag::warn_empty_while_body;
10466 } else
10467 return; // Neither `for' nor `while'.
10468
10469 // The body should be a null statement.
10470 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
10471 if (!NBody)
10472 return;
10473
10474 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000010475 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010476 return;
10477
10478 // Do the usual checks.
10479 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
10480 return;
10481
10482 // `for(...);' and `while(...);' are popular idioms, so in order to keep
10483 // noise level low, emit diagnostics only if for/while is followed by a
10484 // CompoundStmt, e.g.:
10485 // for (int i = 0; i < n; i++);
10486 // {
10487 // a(i);
10488 // }
10489 // or if for/while is followed by a statement with more indentation
10490 // than for/while itself:
10491 // for (int i = 0; i < n; i++);
10492 // a(i);
10493 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
10494 if (!ProbableTypo) {
10495 bool BodyColInvalid;
10496 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
10497 PossibleBody->getLocStart(),
10498 &BodyColInvalid);
10499 if (BodyColInvalid)
10500 return;
10501
10502 bool StmtColInvalid;
10503 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
10504 S->getLocStart(),
10505 &StmtColInvalid);
10506 if (StmtColInvalid)
10507 return;
10508
10509 if (BodyCol > StmtCol)
10510 ProbableTypo = true;
10511 }
10512
10513 if (ProbableTypo) {
10514 Diag(NBody->getSemiLoc(), DiagID);
10515 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
10516 }
10517}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010518
Richard Trieu36d0b2b2015-01-13 02:32:02 +000010519//===--- CHECK: Warn on self move with std::move. -------------------------===//
10520
10521/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
10522void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
10523 SourceLocation OpLoc) {
Richard Trieu36d0b2b2015-01-13 02:32:02 +000010524 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
10525 return;
10526
10527 if (!ActiveTemplateInstantiations.empty())
10528 return;
10529
10530 // Strip parens and casts away.
10531 LHSExpr = LHSExpr->IgnoreParenImpCasts();
10532 RHSExpr = RHSExpr->IgnoreParenImpCasts();
10533
10534 // Check for a call expression
10535 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
10536 if (!CE || CE->getNumArgs() != 1)
10537 return;
10538
10539 // Check for a call to std::move
10540 const FunctionDecl *FD = CE->getDirectCallee();
10541 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
10542 !FD->getIdentifier()->isStr("move"))
10543 return;
10544
10545 // Get argument from std::move
10546 RHSExpr = CE->getArg(0);
10547
10548 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
10549 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
10550
10551 // Two DeclRefExpr's, check that the decls are the same.
10552 if (LHSDeclRef && RHSDeclRef) {
10553 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
10554 return;
10555 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
10556 RHSDeclRef->getDecl()->getCanonicalDecl())
10557 return;
10558
10559 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
10560 << LHSExpr->getSourceRange()
10561 << RHSExpr->getSourceRange();
10562 return;
10563 }
10564
10565 // Member variables require a different approach to check for self moves.
10566 // MemberExpr's are the same if every nested MemberExpr refers to the same
10567 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
10568 // the base Expr's are CXXThisExpr's.
10569 const Expr *LHSBase = LHSExpr;
10570 const Expr *RHSBase = RHSExpr;
10571 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
10572 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
10573 if (!LHSME || !RHSME)
10574 return;
10575
10576 while (LHSME && RHSME) {
10577 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
10578 RHSME->getMemberDecl()->getCanonicalDecl())
10579 return;
10580
10581 LHSBase = LHSME->getBase();
10582 RHSBase = RHSME->getBase();
10583 LHSME = dyn_cast<MemberExpr>(LHSBase);
10584 RHSME = dyn_cast<MemberExpr>(RHSBase);
10585 }
10586
10587 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
10588 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
10589 if (LHSDeclRef && RHSDeclRef) {
10590 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
10591 return;
10592 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
10593 RHSDeclRef->getDecl()->getCanonicalDecl())
10594 return;
10595
10596 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
10597 << LHSExpr->getSourceRange()
10598 << RHSExpr->getSourceRange();
10599 return;
10600 }
10601
10602 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
10603 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
10604 << LHSExpr->getSourceRange()
10605 << RHSExpr->getSourceRange();
10606}
10607
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010608//===--- Layout compatibility ----------------------------------------------//
10609
10610namespace {
10611
10612bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
10613
10614/// \brief Check if two enumeration types are layout-compatible.
10615bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
10616 // C++11 [dcl.enum] p8:
10617 // Two enumeration types are layout-compatible if they have the same
10618 // underlying type.
10619 return ED1->isComplete() && ED2->isComplete() &&
10620 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
10621}
10622
10623/// \brief Check if two fields are layout-compatible.
10624bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
10625 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
10626 return false;
10627
10628 if (Field1->isBitField() != Field2->isBitField())
10629 return false;
10630
10631 if (Field1->isBitField()) {
10632 // Make sure that the bit-fields are the same length.
10633 unsigned Bits1 = Field1->getBitWidthValue(C);
10634 unsigned Bits2 = Field2->getBitWidthValue(C);
10635
10636 if (Bits1 != Bits2)
10637 return false;
10638 }
10639
10640 return true;
10641}
10642
10643/// \brief Check if two standard-layout structs are layout-compatible.
10644/// (C++11 [class.mem] p17)
10645bool isLayoutCompatibleStruct(ASTContext &C,
10646 RecordDecl *RD1,
10647 RecordDecl *RD2) {
10648 // If both records are C++ classes, check that base classes match.
10649 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
10650 // If one of records is a CXXRecordDecl we are in C++ mode,
10651 // thus the other one is a CXXRecordDecl, too.
10652 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
10653 // Check number of base classes.
10654 if (D1CXX->getNumBases() != D2CXX->getNumBases())
10655 return false;
10656
10657 // Check the base classes.
10658 for (CXXRecordDecl::base_class_const_iterator
10659 Base1 = D1CXX->bases_begin(),
10660 BaseEnd1 = D1CXX->bases_end(),
10661 Base2 = D2CXX->bases_begin();
10662 Base1 != BaseEnd1;
10663 ++Base1, ++Base2) {
10664 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
10665 return false;
10666 }
10667 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
10668 // If only RD2 is a C++ class, it should have zero base classes.
10669 if (D2CXX->getNumBases() > 0)
10670 return false;
10671 }
10672
10673 // Check the fields.
10674 RecordDecl::field_iterator Field2 = RD2->field_begin(),
10675 Field2End = RD2->field_end(),
10676 Field1 = RD1->field_begin(),
10677 Field1End = RD1->field_end();
10678 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
10679 if (!isLayoutCompatible(C, *Field1, *Field2))
10680 return false;
10681 }
10682 if (Field1 != Field1End || Field2 != Field2End)
10683 return false;
10684
10685 return true;
10686}
10687
10688/// \brief Check if two standard-layout unions are layout-compatible.
10689/// (C++11 [class.mem] p18)
10690bool isLayoutCompatibleUnion(ASTContext &C,
10691 RecordDecl *RD1,
10692 RecordDecl *RD2) {
10693 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010694 for (auto *Field2 : RD2->fields())
10695 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010696
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010697 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010698 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
10699 I = UnmatchedFields.begin(),
10700 E = UnmatchedFields.end();
10701
10702 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010703 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010704 bool Result = UnmatchedFields.erase(*I);
10705 (void) Result;
10706 assert(Result);
10707 break;
10708 }
10709 }
10710 if (I == E)
10711 return false;
10712 }
10713
10714 return UnmatchedFields.empty();
10715}
10716
10717bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
10718 if (RD1->isUnion() != RD2->isUnion())
10719 return false;
10720
10721 if (RD1->isUnion())
10722 return isLayoutCompatibleUnion(C, RD1, RD2);
10723 else
10724 return isLayoutCompatibleStruct(C, RD1, RD2);
10725}
10726
10727/// \brief Check if two types are layout-compatible in C++11 sense.
10728bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
10729 if (T1.isNull() || T2.isNull())
10730 return false;
10731
10732 // C++11 [basic.types] p11:
10733 // If two types T1 and T2 are the same type, then T1 and T2 are
10734 // layout-compatible types.
10735 if (C.hasSameType(T1, T2))
10736 return true;
10737
10738 T1 = T1.getCanonicalType().getUnqualifiedType();
10739 T2 = T2.getCanonicalType().getUnqualifiedType();
10740
10741 const Type::TypeClass TC1 = T1->getTypeClass();
10742 const Type::TypeClass TC2 = T2->getTypeClass();
10743
10744 if (TC1 != TC2)
10745 return false;
10746
10747 if (TC1 == Type::Enum) {
10748 return isLayoutCompatible(C,
10749 cast<EnumType>(T1)->getDecl(),
10750 cast<EnumType>(T2)->getDecl());
10751 } else if (TC1 == Type::Record) {
10752 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
10753 return false;
10754
10755 return isLayoutCompatible(C,
10756 cast<RecordType>(T1)->getDecl(),
10757 cast<RecordType>(T2)->getDecl());
10758 }
10759
10760 return false;
10761}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010762} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010763
10764//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
10765
10766namespace {
10767/// \brief Given a type tag expression find the type tag itself.
10768///
10769/// \param TypeExpr Type tag expression, as it appears in user's code.
10770///
10771/// \param VD Declaration of an identifier that appears in a type tag.
10772///
10773/// \param MagicValue Type tag magic value.
10774bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
10775 const ValueDecl **VD, uint64_t *MagicValue) {
10776 while(true) {
10777 if (!TypeExpr)
10778 return false;
10779
10780 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
10781
10782 switch (TypeExpr->getStmtClass()) {
10783 case Stmt::UnaryOperatorClass: {
10784 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
10785 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
10786 TypeExpr = UO->getSubExpr();
10787 continue;
10788 }
10789 return false;
10790 }
10791
10792 case Stmt::DeclRefExprClass: {
10793 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
10794 *VD = DRE->getDecl();
10795 return true;
10796 }
10797
10798 case Stmt::IntegerLiteralClass: {
10799 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
10800 llvm::APInt MagicValueAPInt = IL->getValue();
10801 if (MagicValueAPInt.getActiveBits() <= 64) {
10802 *MagicValue = MagicValueAPInt.getZExtValue();
10803 return true;
10804 } else
10805 return false;
10806 }
10807
10808 case Stmt::BinaryConditionalOperatorClass:
10809 case Stmt::ConditionalOperatorClass: {
10810 const AbstractConditionalOperator *ACO =
10811 cast<AbstractConditionalOperator>(TypeExpr);
10812 bool Result;
10813 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
10814 if (Result)
10815 TypeExpr = ACO->getTrueExpr();
10816 else
10817 TypeExpr = ACO->getFalseExpr();
10818 continue;
10819 }
10820 return false;
10821 }
10822
10823 case Stmt::BinaryOperatorClass: {
10824 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
10825 if (BO->getOpcode() == BO_Comma) {
10826 TypeExpr = BO->getRHS();
10827 continue;
10828 }
10829 return false;
10830 }
10831
10832 default:
10833 return false;
10834 }
10835 }
10836}
10837
10838/// \brief Retrieve the C type corresponding to type tag TypeExpr.
10839///
10840/// \param TypeExpr Expression that specifies a type tag.
10841///
10842/// \param MagicValues Registered magic values.
10843///
10844/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
10845/// kind.
10846///
10847/// \param TypeInfo Information about the corresponding C type.
10848///
10849/// \returns true if the corresponding C type was found.
10850bool GetMatchingCType(
10851 const IdentifierInfo *ArgumentKind,
10852 const Expr *TypeExpr, const ASTContext &Ctx,
10853 const llvm::DenseMap<Sema::TypeTagMagicValue,
10854 Sema::TypeTagData> *MagicValues,
10855 bool &FoundWrongKind,
10856 Sema::TypeTagData &TypeInfo) {
10857 FoundWrongKind = false;
10858
10859 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +000010860 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010861
10862 uint64_t MagicValue;
10863
10864 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
10865 return false;
10866
10867 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +000010868 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010869 if (I->getArgumentKind() != ArgumentKind) {
10870 FoundWrongKind = true;
10871 return false;
10872 }
10873 TypeInfo.Type = I->getMatchingCType();
10874 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
10875 TypeInfo.MustBeNull = I->getMustBeNull();
10876 return true;
10877 }
10878 return false;
10879 }
10880
10881 if (!MagicValues)
10882 return false;
10883
10884 llvm::DenseMap<Sema::TypeTagMagicValue,
10885 Sema::TypeTagData>::const_iterator I =
10886 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
10887 if (I == MagicValues->end())
10888 return false;
10889
10890 TypeInfo = I->second;
10891 return true;
10892}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010893} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010894
10895void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
10896 uint64_t MagicValue, QualType Type,
10897 bool LayoutCompatible,
10898 bool MustBeNull) {
10899 if (!TypeTagForDatatypeMagicValues)
10900 TypeTagForDatatypeMagicValues.reset(
10901 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
10902
10903 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
10904 (*TypeTagForDatatypeMagicValues)[Magic] =
10905 TypeTagData(Type, LayoutCompatible, MustBeNull);
10906}
10907
10908namespace {
10909bool IsSameCharType(QualType T1, QualType T2) {
10910 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
10911 if (!BT1)
10912 return false;
10913
10914 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
10915 if (!BT2)
10916 return false;
10917
10918 BuiltinType::Kind T1Kind = BT1->getKind();
10919 BuiltinType::Kind T2Kind = BT2->getKind();
10920
10921 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
10922 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
10923 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
10924 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
10925}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010926} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010927
10928void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
10929 const Expr * const *ExprArgs) {
10930 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
10931 bool IsPointerAttr = Attr->getIsPointer();
10932
10933 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
10934 bool FoundWrongKind;
10935 TypeTagData TypeInfo;
10936 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
10937 TypeTagForDatatypeMagicValues.get(),
10938 FoundWrongKind, TypeInfo)) {
10939 if (FoundWrongKind)
10940 Diag(TypeTagExpr->getExprLoc(),
10941 diag::warn_type_tag_for_datatype_wrong_kind)
10942 << TypeTagExpr->getSourceRange();
10943 return;
10944 }
10945
10946 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
10947 if (IsPointerAttr) {
10948 // Skip implicit cast of pointer to `void *' (as a function argument).
10949 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +000010950 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +000010951 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010952 ArgumentExpr = ICE->getSubExpr();
10953 }
10954 QualType ArgumentType = ArgumentExpr->getType();
10955
10956 // Passing a `void*' pointer shouldn't trigger a warning.
10957 if (IsPointerAttr && ArgumentType->isVoidPointerType())
10958 return;
10959
10960 if (TypeInfo.MustBeNull) {
10961 // Type tag with matching void type requires a null pointer.
10962 if (!ArgumentExpr->isNullPointerConstant(Context,
10963 Expr::NPC_ValueDependentIsNotNull)) {
10964 Diag(ArgumentExpr->getExprLoc(),
10965 diag::warn_type_safety_null_pointer_required)
10966 << ArgumentKind->getName()
10967 << ArgumentExpr->getSourceRange()
10968 << TypeTagExpr->getSourceRange();
10969 }
10970 return;
10971 }
10972
10973 QualType RequiredType = TypeInfo.Type;
10974 if (IsPointerAttr)
10975 RequiredType = Context.getPointerType(RequiredType);
10976
10977 bool mismatch = false;
10978 if (!TypeInfo.LayoutCompatible) {
10979 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
10980
10981 // C++11 [basic.fundamental] p1:
10982 // Plain char, signed char, and unsigned char are three distinct types.
10983 //
10984 // But we treat plain `char' as equivalent to `signed char' or `unsigned
10985 // char' depending on the current char signedness mode.
10986 if (mismatch)
10987 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
10988 RequiredType->getPointeeType())) ||
10989 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
10990 mismatch = false;
10991 } else
10992 if (IsPointerAttr)
10993 mismatch = !isLayoutCompatible(Context,
10994 ArgumentType->getPointeeType(),
10995 RequiredType->getPointeeType());
10996 else
10997 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
10998
10999 if (mismatch)
11000 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +000011001 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011002 << TypeInfo.LayoutCompatible << RequiredType
11003 << ArgumentExpr->getSourceRange()
11004 << TypeTagExpr->getSourceRange();
11005}
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011006
11007void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
11008 CharUnits Alignment) {
11009 MisalignedMembers.emplace_back(E, RD, MD, Alignment);
11010}
11011
11012void Sema::DiagnoseMisalignedMembers() {
11013 for (MisalignedMember &m : MisalignedMembers) {
11014 Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member)
11015 << m.MD << m.RD << m.E->getSourceRange();
11016 }
11017 MisalignedMembers.clear();
11018}
11019
11020void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
11021 if (!T->isPointerType())
11022 return;
11023 if (isa<UnaryOperator>(E) &&
11024 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
11025 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
11026 if (isa<MemberExpr>(Op)) {
11027 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
11028 MisalignedMember(Op));
11029 if (MA != MisalignedMembers.end() &&
11030 Context.getTypeAlignInChars(T->getPointeeType()) <= MA->Alignment)
11031 MisalignedMembers.erase(MA);
11032 }
11033 }
11034}
11035
11036void Sema::RefersToMemberWithReducedAlignment(
11037 Expr *E,
11038 std::function<void(Expr *, RecordDecl *, ValueDecl *, CharUnits)> Action) {
11039 const auto *ME = dyn_cast<MemberExpr>(E);
11040 while (ME && isa<FieldDecl>(ME->getMemberDecl())) {
11041 QualType BaseType = ME->getBase()->getType();
11042 if (ME->isArrow())
11043 BaseType = BaseType->getPointeeType();
11044 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
11045
11046 ValueDecl *MD = ME->getMemberDecl();
11047 bool ByteAligned = Context.getTypeAlignInChars(MD->getType()).isOne();
11048 if (ByteAligned) // Attribute packed does not have any effect.
11049 break;
11050
11051 if (!ByteAligned &&
11052 (RD->hasAttr<PackedAttr>() || (MD->hasAttr<PackedAttr>()))) {
11053 CharUnits Alignment = std::min(Context.getTypeAlignInChars(MD->getType()),
11054 Context.getTypeAlignInChars(BaseType));
11055 // Notify that this expression designates a member with reduced alignment
11056 Action(E, RD, MD, Alignment);
11057 break;
11058 }
11059 ME = dyn_cast<MemberExpr>(ME->getBase());
11060 }
11061}
11062
11063void Sema::CheckAddressOfPackedMember(Expr *rhs) {
11064 using namespace std::placeholders;
11065 RefersToMemberWithReducedAlignment(
11066 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
11067 _2, _3, _4));
11068}
11069