blob: deb3860da15c492e5f04db205a7676ff43978c13 [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() ||
Aaron Ballmana4f597f2016-09-15 18:07:51 +00003243 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
3244 // Promotable integers are UB, but enumerations need a bit of
3245 // extra checking to see what their promotable type actually is.
3246 if (!Type->isPromotableIntegerType())
3247 return false;
3248 if (!Type->isEnumeralType())
3249 return true;
3250 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3251 return !(ED &&
3252 Context.typesAreCompatible(ED->getPromotionType(), Type));
3253 }()) {
Aaron Ballman1de59c52016-04-24 13:30:21 +00003254 unsigned Reason = 0;
3255 if (Type->isReferenceType()) Reason = 1;
3256 else if (IsCRegister) Reason = 2;
3257 Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
Nico Weber9eea7642013-05-24 23:31:57 +00003258 Diag(ParamLoc, diag::note_parameter_type) << Type;
3259 }
3260
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00003261 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00003262 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00003263}
Chris Lattner43be2e62007-12-19 23:59:04 +00003264
Charles Davisc7d5c942015-09-17 20:55:33 +00003265/// Check the arguments to '__builtin_va_start' for validity, and that
3266/// it was called from a function of the native ABI.
3267/// Emit an error and return true on failure; return false on success.
3268bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
3269 // On x86-64 Unix, don't allow this in Win64 ABI functions.
3270 // On x64 Windows, don't allow this in System V ABI functions.
3271 // (Yes, that means there's no corresponding way to support variadic
3272 // System V ABI functions on Windows.)
3273 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64) {
3274 unsigned OS = Context.getTargetInfo().getTriple().getOS();
3275 clang::CallingConv CC = CC_C;
3276 if (const FunctionDecl *FD = getCurFunctionDecl())
3277 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3278 if ((OS == llvm::Triple::Win32 && CC == CC_X86_64SysV) ||
3279 (OS != llvm::Triple::Win32 && CC == CC_X86_64Win64))
3280 return Diag(TheCall->getCallee()->getLocStart(),
3281 diag::err_va_start_used_in_wrong_abi_function)
3282 << (OS != llvm::Triple::Win32);
3283 }
3284 return SemaBuiltinVAStartImpl(TheCall);
3285}
3286
3287/// Check the arguments to '__builtin_ms_va_start' for validity, and that
3288/// it was called from a Win64 ABI function.
3289/// Emit an error and return true on failure; return false on success.
3290bool Sema::SemaBuiltinMSVAStart(CallExpr *TheCall) {
3291 // This only makes sense for x86-64.
3292 const llvm::Triple &TT = Context.getTargetInfo().getTriple();
3293 Expr *Callee = TheCall->getCallee();
3294 if (TT.getArch() != llvm::Triple::x86_64)
3295 return Diag(Callee->getLocStart(), diag::err_x86_builtin_32_bit_tgt);
3296 // Don't allow this in System V ABI functions.
3297 clang::CallingConv CC = CC_C;
3298 if (const FunctionDecl *FD = getCurFunctionDecl())
3299 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3300 if (CC == CC_X86_64SysV ||
3301 (TT.getOS() != llvm::Triple::Win32 && CC != CC_X86_64Win64))
3302 return Diag(Callee->getLocStart(),
3303 diag::err_ms_va_start_used_in_sysv_function);
3304 return SemaBuiltinVAStartImpl(TheCall);
3305}
3306
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00003307bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
3308 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
3309 // const char *named_addr);
3310
3311 Expr *Func = Call->getCallee();
3312
3313 if (Call->getNumArgs() < 3)
3314 return Diag(Call->getLocEnd(),
3315 diag::err_typecheck_call_too_few_args_at_least)
3316 << 0 /*function call*/ << 3 << Call->getNumArgs();
3317
3318 // Determine whether the current function is variadic or not.
3319 bool IsVariadic;
3320 if (BlockScopeInfo *CurBlock = getCurBlock())
3321 IsVariadic = CurBlock->TheDecl->isVariadic();
3322 else if (FunctionDecl *FD = getCurFunctionDecl())
3323 IsVariadic = FD->isVariadic();
3324 else if (ObjCMethodDecl *MD = getCurMethodDecl())
3325 IsVariadic = MD->isVariadic();
3326 else
3327 llvm_unreachable("unexpected statement type");
3328
3329 if (!IsVariadic) {
3330 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
3331 return true;
3332 }
3333
3334 // Type-check the first argument normally.
3335 if (checkBuiltinArgument(*this, Call, 0))
3336 return true;
3337
Benjamin Kramere0ca6e12015-03-01 18:09:50 +00003338 const struct {
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00003339 unsigned ArgNo;
3340 QualType Type;
3341 } ArgumentTypes[] = {
3342 { 1, Context.getPointerType(Context.CharTy.withConst()) },
3343 { 2, Context.getSizeType() },
3344 };
3345
3346 for (const auto &AT : ArgumentTypes) {
3347 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
3348 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
3349 continue;
3350 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
3351 << Arg->getType() << AT.Type << 1 /* different class */
3352 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
3353 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
3354 }
3355
3356 return false;
3357}
3358
Chris Lattner2da14fb2007-12-20 00:26:33 +00003359/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
3360/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00003361bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
3362 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00003363 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00003364 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00003365 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00003366 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003367 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003368 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00003369 << SourceRange(TheCall->getArg(2)->getLocStart(),
3370 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00003371
John Wiegley01296292011-04-08 18:41:53 +00003372 ExprResult OrigArg0 = TheCall->getArg(0);
3373 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00003374
Chris Lattner2da14fb2007-12-20 00:26:33 +00003375 // Do standard promotions between the two arguments, returning their common
3376 // type.
Chris Lattner08464942007-12-28 05:29:59 +00003377 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00003378 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
3379 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00003380
3381 // Make sure any conversions are pushed back into the call; this is
3382 // type safe since unordered compare builtins are declared as "_Bool
3383 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00003384 TheCall->setArg(0, OrigArg0.get());
3385 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00003386
John Wiegley01296292011-04-08 18:41:53 +00003387 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00003388 return false;
3389
Chris Lattner2da14fb2007-12-20 00:26:33 +00003390 // If the common type isn't a real floating type, then the arguments were
3391 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00003392 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00003393 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003394 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00003395 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
3396 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00003397
Chris Lattner2da14fb2007-12-20 00:26:33 +00003398 return false;
3399}
3400
Benjamin Kramer634fc102010-02-15 22:42:31 +00003401/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
3402/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00003403/// to check everything. We expect the last argument to be a floating point
3404/// value.
3405bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
3406 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00003407 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00003408 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00003409 if (TheCall->getNumArgs() > NumArgs)
3410 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00003411 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003412 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00003413 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00003414 (*(TheCall->arg_end()-1))->getLocEnd());
3415
Benjamin Kramer64aae502010-02-16 10:07:31 +00003416 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00003417
Eli Friedman7e4faac2009-08-31 20:06:00 +00003418 if (OrigArg->isTypeDependent())
3419 return false;
3420
Chris Lattner68784ef2010-05-06 05:50:07 +00003421 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00003422 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00003423 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00003424 diag::err_typecheck_call_invalid_unary_fp)
3425 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00003426
Chris Lattner68784ef2010-05-06 05:50:07 +00003427 // If this is an implicit conversion from float -> double, remove it.
3428 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
3429 Expr *CastArg = Cast->getSubExpr();
3430 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
3431 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
3432 "promotion from float to double is the only expected cast here");
Craig Topperc3ec1492014-05-26 06:22:03 +00003433 Cast->setSubExpr(nullptr);
Chris Lattner68784ef2010-05-06 05:50:07 +00003434 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner68784ef2010-05-06 05:50:07 +00003435 }
3436 }
3437
Eli Friedman7e4faac2009-08-31 20:06:00 +00003438 return false;
3439}
3440
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003441/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
3442// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00003443ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00003444 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003445 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00003446 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00003447 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3448 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003449
Nate Begemana0110022010-06-08 00:16:34 +00003450 // Determine which of the following types of shufflevector we're checking:
3451 // 1) unary, vector mask: (lhs, mask)
Craig Topperb3174a82016-05-18 04:11:25 +00003452 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
Nate Begemana0110022010-06-08 00:16:34 +00003453 QualType resType = TheCall->getArg(0)->getType();
3454 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00003455
Douglas Gregorc25f7662009-05-19 22:10:17 +00003456 if (!TheCall->getArg(0)->isTypeDependent() &&
3457 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00003458 QualType LHSType = TheCall->getArg(0)->getType();
3459 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00003460
Craig Topperbaca3892013-07-29 06:47:04 +00003461 if (!LHSType->isVectorType() || !RHSType->isVectorType())
3462 return ExprError(Diag(TheCall->getLocStart(),
3463 diag::err_shufflevector_non_vector)
3464 << SourceRange(TheCall->getArg(0)->getLocStart(),
3465 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00003466
Nate Begemana0110022010-06-08 00:16:34 +00003467 numElements = LHSType->getAs<VectorType>()->getNumElements();
3468 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00003469
Nate Begemana0110022010-06-08 00:16:34 +00003470 // Check to see if we have a call with 2 vector arguments, the unary shuffle
3471 // with mask. If so, verify that RHS is an integer vector type with the
3472 // same number of elts as lhs.
3473 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00003474 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00003475 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00003476 return ExprError(Diag(TheCall->getLocStart(),
3477 diag::err_shufflevector_incompatible_vector)
3478 << SourceRange(TheCall->getArg(1)->getLocStart(),
3479 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00003480 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00003481 return ExprError(Diag(TheCall->getLocStart(),
3482 diag::err_shufflevector_incompatible_vector)
3483 << SourceRange(TheCall->getArg(0)->getLocStart(),
3484 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00003485 } else if (numElements != numResElements) {
3486 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00003487 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00003488 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00003489 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003490 }
3491
3492 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00003493 if (TheCall->getArg(i)->isTypeDependent() ||
3494 TheCall->getArg(i)->isValueDependent())
3495 continue;
3496
Nate Begemana0110022010-06-08 00:16:34 +00003497 llvm::APSInt Result(32);
3498 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
3499 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00003500 diag::err_shufflevector_nonconstant_argument)
3501 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003502
Craig Topper50ad5b72013-08-03 17:40:38 +00003503 // Allow -1 which will be translated to undef in the IR.
3504 if (Result.isSigned() && Result.isAllOnesValue())
3505 continue;
3506
Chris Lattner7ab824e2008-08-10 02:05:13 +00003507 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003508 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00003509 diag::err_shufflevector_argument_too_large)
3510 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003511 }
3512
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003513 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003514
Chris Lattner7ab824e2008-08-10 02:05:13 +00003515 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003516 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00003517 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003518 }
3519
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003520 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
3521 TheCall->getCallee()->getLocStart(),
3522 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003523}
Chris Lattner43be2e62007-12-19 23:59:04 +00003524
Hal Finkelc4d7c822013-09-18 03:29:45 +00003525/// SemaConvertVectorExpr - Handle __builtin_convertvector
3526ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
3527 SourceLocation BuiltinLoc,
3528 SourceLocation RParenLoc) {
3529 ExprValueKind VK = VK_RValue;
3530 ExprObjectKind OK = OK_Ordinary;
3531 QualType DstTy = TInfo->getType();
3532 QualType SrcTy = E->getType();
3533
3534 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
3535 return ExprError(Diag(BuiltinLoc,
3536 diag::err_convertvector_non_vector)
3537 << E->getSourceRange());
3538 if (!DstTy->isVectorType() && !DstTy->isDependentType())
3539 return ExprError(Diag(BuiltinLoc,
3540 diag::err_convertvector_non_vector_type));
3541
3542 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
3543 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
3544 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
3545 if (SrcElts != DstElts)
3546 return ExprError(Diag(BuiltinLoc,
3547 diag::err_convertvector_incompatible_vector)
3548 << E->getSourceRange());
3549 }
3550
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003551 return new (Context)
3552 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00003553}
3554
Daniel Dunbarb7257262008-07-21 22:59:13 +00003555/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
3556// This is declared to take (const void*, ...) and can take two
3557// optional constant int args.
3558bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00003559 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00003560
Chris Lattner3b054132008-11-19 05:08:23 +00003561 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003562 return Diag(TheCall->getLocEnd(),
3563 diag::err_typecheck_call_too_many_args_at_most)
3564 << 0 /*function call*/ << 3 << NumArgs
3565 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00003566
3567 // Argument 0 is checked for us and the remaining arguments must be
3568 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00003569 for (unsigned i = 1; i != NumArgs; ++i)
3570 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00003571 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003572
Warren Hunt20e4a5d2014-02-21 23:08:53 +00003573 return false;
3574}
3575
Hal Finkelf0417332014-07-17 14:25:55 +00003576/// SemaBuiltinAssume - Handle __assume (MS Extension).
3577// __assume does not evaluate its arguments, and should warn if its argument
3578// has side effects.
3579bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
3580 Expr *Arg = TheCall->getArg(0);
3581 if (Arg->isInstantiationDependent()) return false;
3582
3583 if (Arg->HasSideEffects(Context))
David Majnemer51236642015-02-26 00:57:33 +00003584 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00003585 << Arg->getSourceRange()
3586 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
3587
3588 return false;
3589}
3590
3591/// Handle __builtin_assume_aligned. This is declared
3592/// as (const void*, size_t, ...) and can take one optional constant int arg.
3593bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
3594 unsigned NumArgs = TheCall->getNumArgs();
3595
3596 if (NumArgs > 3)
3597 return Diag(TheCall->getLocEnd(),
3598 diag::err_typecheck_call_too_many_args_at_most)
3599 << 0 /*function call*/ << 3 << NumArgs
3600 << TheCall->getSourceRange();
3601
3602 // The alignment must be a constant integer.
3603 Expr *Arg = TheCall->getArg(1);
3604
3605 // We can't check the value of a dependent argument.
3606 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
3607 llvm::APSInt Result;
3608 if (SemaBuiltinConstantArg(TheCall, 1, Result))
3609 return true;
3610
3611 if (!Result.isPowerOf2())
3612 return Diag(TheCall->getLocStart(),
3613 diag::err_alignment_not_power_of_two)
3614 << Arg->getSourceRange();
3615 }
3616
3617 if (NumArgs > 2) {
3618 ExprResult Arg(TheCall->getArg(2));
3619 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3620 Context.getSizeType(), false);
3621 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3622 if (Arg.isInvalid()) return true;
3623 TheCall->setArg(2, Arg.get());
3624 }
Hal Finkelf0417332014-07-17 14:25:55 +00003625
3626 return false;
3627}
3628
Eric Christopher8d0c6212010-04-17 02:26:23 +00003629/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
3630/// TheCall is a constant expression.
3631bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
3632 llvm::APSInt &Result) {
3633 Expr *Arg = TheCall->getArg(ArgNum);
3634 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3635 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3636
3637 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
3638
3639 if (!Arg->isIntegerConstantExpr(Result, Context))
3640 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00003641 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00003642
Chris Lattnerd545ad12009-09-23 06:06:36 +00003643 return false;
3644}
3645
Richard Sandiford28940af2014-04-16 08:47:51 +00003646/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
3647/// TheCall is a constant expression in the range [Low, High].
3648bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
3649 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00003650 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00003651
3652 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00003653 Expr *Arg = TheCall->getArg(ArgNum);
3654 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00003655 return false;
3656
Eric Christopher8d0c6212010-04-17 02:26:23 +00003657 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00003658 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00003659 return true;
3660
Richard Sandiford28940af2014-04-16 08:47:51 +00003661 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00003662 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00003663 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00003664
3665 return false;
3666}
3667
Luke Cheeseman59b2d832015-06-15 17:51:01 +00003668/// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
3669/// TheCall is an ARM/AArch64 special register string literal.
3670bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
3671 int ArgNum, unsigned ExpectedFieldNum,
3672 bool AllowName) {
3673 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
3674 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
3675 BuiltinID == ARM::BI__builtin_arm_rsr ||
3676 BuiltinID == ARM::BI__builtin_arm_rsrp ||
3677 BuiltinID == ARM::BI__builtin_arm_wsr ||
3678 BuiltinID == ARM::BI__builtin_arm_wsrp;
3679 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
3680 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
3681 BuiltinID == AArch64::BI__builtin_arm_rsr ||
3682 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
3683 BuiltinID == AArch64::BI__builtin_arm_wsr ||
3684 BuiltinID == AArch64::BI__builtin_arm_wsrp;
3685 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
3686
3687 // We can't check the value of a dependent argument.
3688 Expr *Arg = TheCall->getArg(ArgNum);
3689 if (Arg->isTypeDependent() || Arg->isValueDependent())
3690 return false;
3691
3692 // Check if the argument is a string literal.
3693 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3694 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
3695 << Arg->getSourceRange();
3696
3697 // Check the type of special register given.
3698 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3699 SmallVector<StringRef, 6> Fields;
3700 Reg.split(Fields, ":");
3701
3702 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
3703 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
3704 << Arg->getSourceRange();
3705
3706 // If the string is the name of a register then we cannot check that it is
3707 // valid here but if the string is of one the forms described in ACLE then we
3708 // can check that the supplied fields are integers and within the valid
3709 // ranges.
3710 if (Fields.size() > 1) {
3711 bool FiveFields = Fields.size() == 5;
3712
3713 bool ValidString = true;
3714 if (IsARMBuiltin) {
3715 ValidString &= Fields[0].startswith_lower("cp") ||
3716 Fields[0].startswith_lower("p");
3717 if (ValidString)
3718 Fields[0] =
3719 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
3720
3721 ValidString &= Fields[2].startswith_lower("c");
3722 if (ValidString)
3723 Fields[2] = Fields[2].drop_front(1);
3724
3725 if (FiveFields) {
3726 ValidString &= Fields[3].startswith_lower("c");
3727 if (ValidString)
3728 Fields[3] = Fields[3].drop_front(1);
3729 }
3730 }
3731
3732 SmallVector<int, 5> Ranges;
3733 if (FiveFields)
3734 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 7, 15, 15});
3735 else
3736 Ranges.append({15, 7, 15});
3737
3738 for (unsigned i=0; i<Fields.size(); ++i) {
3739 int IntField;
3740 ValidString &= !Fields[i].getAsInteger(10, IntField);
3741 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
3742 }
3743
3744 if (!ValidString)
3745 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
3746 << Arg->getSourceRange();
3747
3748 } else if (IsAArch64Builtin && Fields.size() == 1) {
3749 // If the register name is one of those that appear in the condition below
3750 // and the special register builtin being used is one of the write builtins,
3751 // then we require that the argument provided for writing to the register
3752 // is an integer constant expression. This is because it will be lowered to
3753 // an MSR (immediate) instruction, so we need to know the immediate at
3754 // compile time.
3755 if (TheCall->getNumArgs() != 2)
3756 return false;
3757
3758 std::string RegLower = Reg.lower();
3759 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
3760 RegLower != "pan" && RegLower != "uao")
3761 return false;
3762
3763 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
3764 }
3765
3766 return false;
3767}
3768
Eli Friedmanc97d0142009-05-03 06:04:26 +00003769/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Joerg Sonnenberger27173282015-03-11 23:46:32 +00003770/// This checks that the target supports __builtin_longjmp and
3771/// that val is a constant 1.
Eli Friedmaneed8ad22009-05-03 04:46:36 +00003772bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Joerg Sonnenberger27173282015-03-11 23:46:32 +00003773 if (!Context.getTargetInfo().hasSjLjLowering())
3774 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
3775 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
3776
Eli Friedmaneed8ad22009-05-03 04:46:36 +00003777 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00003778 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00003779
Eric Christopher8d0c6212010-04-17 02:26:23 +00003780 // TODO: This is less than ideal. Overload this to take a value.
3781 if (SemaBuiltinConstantArg(TheCall, 1, Result))
3782 return true;
3783
3784 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00003785 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
3786 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
3787
3788 return false;
3789}
3790
Joerg Sonnenberger27173282015-03-11 23:46:32 +00003791/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
3792/// This checks that the target supports __builtin_setjmp.
3793bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
3794 if (!Context.getTargetInfo().hasSjLjLowering())
3795 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
3796 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
3797 return false;
3798}
3799
Richard Smithd7293d72013-08-05 18:49:43 +00003800namespace {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003801class UncoveredArgHandler {
3802 enum { Unknown = -1, AllCovered = -2 };
3803 signed FirstUncoveredArg;
3804 SmallVector<const Expr *, 4> DiagnosticExprs;
3805
3806public:
3807 UncoveredArgHandler() : FirstUncoveredArg(Unknown) { }
3808
3809 bool hasUncoveredArg() const {
3810 return (FirstUncoveredArg >= 0);
3811 }
3812
3813 unsigned getUncoveredArg() const {
3814 assert(hasUncoveredArg() && "no uncovered argument");
3815 return FirstUncoveredArg;
3816 }
3817
3818 void setAllCovered() {
3819 // A string has been found with all arguments covered, so clear out
3820 // the diagnostics.
3821 DiagnosticExprs.clear();
3822 FirstUncoveredArg = AllCovered;
3823 }
3824
3825 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
3826 assert(NewFirstUncoveredArg >= 0 && "Outside range");
3827
3828 // Don't update if a previous string covers all arguments.
3829 if (FirstUncoveredArg == AllCovered)
3830 return;
3831
3832 // UncoveredArgHandler tracks the highest uncovered argument index
3833 // and with it all the strings that match this index.
3834 if (NewFirstUncoveredArg == FirstUncoveredArg)
3835 DiagnosticExprs.push_back(StrExpr);
3836 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
3837 DiagnosticExprs.clear();
3838 DiagnosticExprs.push_back(StrExpr);
3839 FirstUncoveredArg = NewFirstUncoveredArg;
3840 }
3841 }
3842
3843 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
3844};
3845
Richard Smithd7293d72013-08-05 18:49:43 +00003846enum StringLiteralCheckType {
3847 SLCT_NotALiteral,
3848 SLCT_UncheckedLiteral,
3849 SLCT_CheckedLiteral
3850};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00003851} // end anonymous namespace
Richard Smithd7293d72013-08-05 18:49:43 +00003852
Stephen Hines648c3692016-09-16 01:07:04 +00003853static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
3854 BinaryOperatorKind BinOpKind,
3855 bool AddendIsRight) {
3856 unsigned BitWidth = Offset.getBitWidth();
3857 unsigned AddendBitWidth = Addend.getBitWidth();
3858 // There might be negative interim results.
3859 if (Addend.isUnsigned()) {
3860 Addend = Addend.zext(++AddendBitWidth);
3861 Addend.setIsSigned(true);
3862 }
3863 // Adjust the bit width of the APSInts.
3864 if (AddendBitWidth > BitWidth) {
3865 Offset = Offset.sext(AddendBitWidth);
3866 BitWidth = AddendBitWidth;
3867 } else if (BitWidth > AddendBitWidth) {
3868 Addend = Addend.sext(BitWidth);
3869 }
3870
3871 bool Ov = false;
3872 llvm::APSInt ResOffset = Offset;
3873 if (BinOpKind == BO_Add)
3874 ResOffset = Offset.sadd_ov(Addend, Ov);
3875 else {
3876 assert(AddendIsRight && BinOpKind == BO_Sub &&
3877 "operator must be add or sub with addend on the right");
3878 ResOffset = Offset.ssub_ov(Addend, Ov);
3879 }
3880
3881 // We add an offset to a pointer here so we should support an offset as big as
3882 // possible.
3883 if (Ov) {
3884 assert(BitWidth <= UINT_MAX / 2 && "index (intermediate) result too big");
3885 Offset.sext(2 * BitWidth);
3886 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
3887 return;
3888 }
3889
3890 Offset = ResOffset;
3891}
3892
3893namespace {
3894// This is a wrapper class around StringLiteral to support offsetted string
3895// literals as format strings. It takes the offset into account when returning
3896// the string and its length or the source locations to display notes correctly.
3897class FormatStringLiteral {
3898 const StringLiteral *FExpr;
3899 int64_t Offset;
3900
3901 public:
3902 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
3903 : FExpr(fexpr), Offset(Offset) {}
3904
3905 StringRef getString() const {
3906 return FExpr->getString().drop_front(Offset);
3907 }
3908
3909 unsigned getByteLength() const {
3910 return FExpr->getByteLength() - getCharByteWidth() * Offset;
3911 }
3912 unsigned getLength() const { return FExpr->getLength() - Offset; }
3913 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
3914
3915 StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
3916
3917 QualType getType() const { return FExpr->getType(); }
3918
3919 bool isAscii() const { return FExpr->isAscii(); }
3920 bool isWide() const { return FExpr->isWide(); }
3921 bool isUTF8() const { return FExpr->isUTF8(); }
3922 bool isUTF16() const { return FExpr->isUTF16(); }
3923 bool isUTF32() const { return FExpr->isUTF32(); }
3924 bool isPascal() const { return FExpr->isPascal(); }
3925
3926 SourceLocation getLocationOfByte(
3927 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
3928 const TargetInfo &Target, unsigned *StartToken = nullptr,
3929 unsigned *StartTokenByteOffset = nullptr) const {
3930 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
3931 StartToken, StartTokenByteOffset);
3932 }
3933
3934 SourceLocation getLocStart() const LLVM_READONLY {
3935 return FExpr->getLocStart().getLocWithOffset(Offset);
3936 }
3937 SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); }
3938};
3939} // end anonymous namespace
3940
3941static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00003942 const Expr *OrigFormatExpr,
3943 ArrayRef<const Expr *> Args,
3944 bool HasVAListArg, unsigned format_idx,
3945 unsigned firstDataArg,
3946 Sema::FormatStringType Type,
3947 bool inFunctionCall,
3948 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003949 llvm::SmallBitVector &CheckedVarArgs,
3950 UncoveredArgHandler &UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00003951
Richard Smith55ce3522012-06-25 20:30:08 +00003952// Determine if an expression is a string literal or constant string.
3953// If this function returns false on the arguments to a function expecting a
3954// format string, we will usually need to emit a warning.
3955// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00003956static StringLiteralCheckType
3957checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
3958 bool HasVAListArg, unsigned format_idx,
3959 unsigned firstDataArg, Sema::FormatStringType Type,
3960 Sema::VariadicCallType CallType, bool InFunctionCall,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003961 llvm::SmallBitVector &CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00003962 UncoveredArgHandler &UncoveredArg,
3963 llvm::APSInt Offset) {
Ted Kremenek808829352010-09-09 03:51:39 +00003964 tryAgain:
Stephen Hines648c3692016-09-16 01:07:04 +00003965 assert(Offset.isSigned() && "invalid offset");
3966
Douglas Gregorc25f7662009-05-19 22:10:17 +00003967 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00003968 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003969
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003970 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00003971
Richard Smithd7293d72013-08-05 18:49:43 +00003972 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00003973 // Technically -Wformat-nonliteral does not warn about this case.
3974 // The behavior of printf and friends in this case is implementation
3975 // dependent. Ideally if the format string cannot be null then
3976 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00003977 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00003978
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003979 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00003980 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003981 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00003982 // The expression is a literal if both sub-expressions were, and it was
3983 // completely checked only if both sub-expressions were checked.
3984 const AbstractConditionalOperator *C =
3985 cast<AbstractConditionalOperator>(E);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003986
3987 // Determine whether it is necessary to check both sub-expressions, for
3988 // example, because the condition expression is a constant that can be
3989 // evaluated at compile time.
3990 bool CheckLeft = true, CheckRight = true;
3991
3992 bool Cond;
3993 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
3994 if (Cond)
3995 CheckRight = false;
3996 else
3997 CheckLeft = false;
3998 }
3999
Stephen Hines648c3692016-09-16 01:07:04 +00004000 // We need to maintain the offsets for the right and the left hand side
4001 // separately to check if every possible indexed expression is a valid
4002 // string literal. They might have different offsets for different string
4003 // literals in the end.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004004 StringLiteralCheckType Left;
4005 if (!CheckLeft)
4006 Left = SLCT_UncheckedLiteral;
4007 else {
4008 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
4009 HasVAListArg, format_idx, firstDataArg,
4010 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00004011 CheckedVarArgs, UncoveredArg, Offset);
4012 if (Left == SLCT_NotALiteral || !CheckRight) {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004013 return Left;
Stephen Hines648c3692016-09-16 01:07:04 +00004014 }
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004015 }
4016
Richard Smith55ce3522012-06-25 20:30:08 +00004017 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00004018 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004019 HasVAListArg, format_idx, firstDataArg,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004020 Type, CallType, InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00004021 UncoveredArg, Offset);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004022
4023 return (CheckLeft && Left < Right) ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004024 }
4025
4026 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00004027 E = cast<ImplicitCastExpr>(E)->getSubExpr();
4028 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004029 }
4030
John McCallc07a0c72011-02-17 10:25:35 +00004031 case Stmt::OpaqueValueExprClass:
4032 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
4033 E = src;
4034 goto tryAgain;
4035 }
Richard Smith55ce3522012-06-25 20:30:08 +00004036 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00004037
Ted Kremeneka8890832011-02-24 23:03:04 +00004038 case Stmt::PredefinedExprClass:
4039 // While __func__, etc., are technically not string literals, they
4040 // cannot contain format specifiers and thus are not a security
4041 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00004042 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00004043
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004044 case Stmt::DeclRefExprClass: {
4045 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004046
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004047 // As an exception, do not flag errors for variables binding to
4048 // const string literals.
4049 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
4050 bool isConstant = false;
4051 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004052
Richard Smithd7293d72013-08-05 18:49:43 +00004053 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
4054 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00004055 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00004056 isConstant = T.isConstant(S.Context) &&
4057 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00004058 } else if (T->isObjCObjectPointerType()) {
4059 // In ObjC, there is usually no "const ObjectPointer" type,
4060 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00004061 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004062 }
Mike Stump11289f42009-09-09 15:08:12 +00004063
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004064 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00004065 if (const Expr *Init = VD->getAnyInitializer()) {
4066 // Look through initializers like const char c[] = { "foo" }
4067 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4068 if (InitList->isStringLiteralInit())
4069 Init = InitList->getInit(0)->IgnoreParenImpCasts();
4070 }
Richard Smithd7293d72013-08-05 18:49:43 +00004071 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004072 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004073 firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00004074 /*InFunctionCall*/ false, CheckedVarArgs,
4075 UncoveredArg, Offset);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00004076 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004077 }
Mike Stump11289f42009-09-09 15:08:12 +00004078
Anders Carlssonb012ca92009-06-28 19:55:58 +00004079 // For vprintf* functions (i.e., HasVAListArg==true), we add a
4080 // special check to see if the format string is a function parameter
4081 // of the function calling the printf function. If the function
4082 // has an attribute indicating it is a printf-like function, then we
4083 // should suppress warnings concerning non-literals being used in a call
4084 // to a vprintf function. For example:
4085 //
4086 // void
4087 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
4088 // va_list ap;
4089 // va_start(ap, fmt);
4090 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
4091 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00004092 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004093 if (HasVAListArg) {
4094 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
4095 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
4096 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00004097 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004098 // adjust for implicit parameter
4099 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4100 if (MD->isInstance())
4101 ++PVIndex;
4102 // We also check if the formats are compatible.
4103 // We can't pass a 'scanf' string to a 'printf' function.
4104 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00004105 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00004106 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004107 }
4108 }
4109 }
4110 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004111 }
Mike Stump11289f42009-09-09 15:08:12 +00004112
Richard Smith55ce3522012-06-25 20:30:08 +00004113 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004114 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004115
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00004116 case Stmt::CallExprClass:
4117 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00004118 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00004119 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
4120 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
4121 unsigned ArgIndex = FA->getFormatIdx();
4122 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4123 if (MD->isInstance())
4124 --ArgIndex;
4125 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00004126
Richard Smithd7293d72013-08-05 18:49:43 +00004127 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004128 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00004129 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00004130 CheckedVarArgs, UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004131 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4132 unsigned BuiltinID = FD->getBuiltinID();
4133 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
4134 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
4135 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00004136 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004137 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004138 firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004139 InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00004140 UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004141 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00004142 }
4143 }
Mike Stump11289f42009-09-09 15:08:12 +00004144
Richard Smith55ce3522012-06-25 20:30:08 +00004145 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00004146 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004147 case Stmt::ObjCStringLiteralClass:
4148 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00004149 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004150
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004151 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004152 StrE = ObjCFExpr->getString();
4153 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004154 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004155
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004156 if (StrE) {
Stephen Hines648c3692016-09-16 01:07:04 +00004157 if (Offset.isNegative() || Offset > StrE->getLength()) {
4158 // TODO: It would be better to have an explicit warning for out of
4159 // bounds literals.
4160 return SLCT_NotALiteral;
4161 }
4162 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
4163 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004164 firstDataArg, Type, InFunctionCall, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004165 CheckedVarArgs, UncoveredArg);
Richard Smith55ce3522012-06-25 20:30:08 +00004166 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004167 }
Mike Stump11289f42009-09-09 15:08:12 +00004168
Richard Smith55ce3522012-06-25 20:30:08 +00004169 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004170 }
Stephen Hines648c3692016-09-16 01:07:04 +00004171 case Stmt::BinaryOperatorClass: {
4172 llvm::APSInt LResult;
4173 llvm::APSInt RResult;
4174
4175 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
4176
4177 // A string literal + an int offset is still a string literal.
4178 if (BinOp->isAdditiveOp()) {
4179 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
4180 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
4181
4182 if (LIsInt != RIsInt) {
4183 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
4184
4185 if (LIsInt) {
4186 if (BinOpKind == BO_Add) {
4187 sumOffsets(Offset, LResult, BinOpKind, RIsInt);
4188 E = BinOp->getRHS();
4189 goto tryAgain;
4190 }
4191 } else {
4192 sumOffsets(Offset, RResult, BinOpKind, RIsInt);
4193 E = BinOp->getLHS();
4194 goto tryAgain;
4195 }
4196 }
4197
4198 return SLCT_NotALiteral;
4199 }
4200 }
4201 case Stmt::UnaryOperatorClass: {
4202 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
4203 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
4204 if (UnaOp->getOpcode() == clang::UO_AddrOf && ASE) {
4205 llvm::APSInt IndexResult;
4206 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
4207 sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true);
4208 E = ASE->getBase();
4209 goto tryAgain;
4210 }
4211 }
4212
4213 return SLCT_NotALiteral;
4214 }
Mike Stump11289f42009-09-09 15:08:12 +00004215
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004216 default:
Richard Smith55ce3522012-06-25 20:30:08 +00004217 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004218 }
4219}
4220
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004221Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00004222 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004223 .Case("scanf", FST_Scanf)
4224 .Cases("printf", "printf0", FST_Printf)
4225 .Cases("NSString", "CFString", FST_NSString)
4226 .Case("strftime", FST_Strftime)
4227 .Case("strfmon", FST_Strfmon)
4228 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
Dimitry Andric6b5ed342015-02-19 22:32:33 +00004229 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00004230 .Case("os_trace", FST_OSTrace)
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004231 .Default(FST_Unknown);
4232}
4233
Jordan Rose3e0ec582012-07-19 18:10:23 +00004234/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00004235/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00004236/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004237bool Sema::CheckFormatArguments(const FormatAttr *Format,
4238 ArrayRef<const Expr *> Args,
4239 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004240 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00004241 SourceLocation Loc, SourceRange Range,
4242 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00004243 FormatStringInfo FSI;
4244 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004245 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00004246 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00004247 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00004248 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004249}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00004250
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004251bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004252 bool HasVAListArg, unsigned format_idx,
4253 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004254 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00004255 SourceLocation Loc, SourceRange Range,
4256 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00004257 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004258 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004259 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00004260 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00004261 }
Mike Stump11289f42009-09-09 15:08:12 +00004262
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004263 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00004264
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004265 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00004266 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00004267 // Dynamically generated format strings are difficult to
4268 // automatically vet at compile time. Requiring that format strings
4269 // are string literals: (1) permits the checking of format strings by
4270 // the compiler and thereby (2) can practically remove the source of
4271 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00004272
Mike Stump11289f42009-09-09 15:08:12 +00004273 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00004274 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00004275 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00004276 // the same format string checking logic for both ObjC and C strings.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004277 UncoveredArgHandler UncoveredArg;
Richard Smith55ce3522012-06-25 20:30:08 +00004278 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00004279 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
4280 format_idx, firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00004281 /*IsFunctionCall*/ true, CheckedVarArgs,
4282 UncoveredArg,
4283 /*no string offset*/ llvm::APSInt(64, false) = 0);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004284
4285 // Generate a diagnostic where an uncovered argument is detected.
4286 if (UncoveredArg.hasUncoveredArg()) {
4287 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
4288 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
4289 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
4290 }
4291
Richard Smith55ce3522012-06-25 20:30:08 +00004292 if (CT != SLCT_NotALiteral)
4293 // Literal format string found, check done!
4294 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00004295
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00004296 // Strftime is particular as it always uses a single 'time' argument,
4297 // so it is safe to pass a non-literal string.
4298 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00004299 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00004300
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00004301 // Do not emit diag when the string param is a macro expansion and the
4302 // format is either NSString or CFString. This is a hack to prevent
4303 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
4304 // which are usually used in place of NS and CF string literals.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004305 SourceLocation FormatLoc = Args[format_idx]->getLocStart();
4306 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
Richard Smith55ce3522012-06-25 20:30:08 +00004307 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00004308
Chris Lattnercc5d1c22009-04-29 04:59:47 +00004309 // If there are no arguments specified, warn with -Wformat-security, otherwise
4310 // warn only with -Wformat-nonliteral.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004311 if (Args.size() == firstDataArg) {
Bob Wilson57819fc2016-03-15 20:56:38 +00004312 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
4313 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004314 switch (Type) {
4315 default:
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004316 break;
4317 case FST_Kprintf:
4318 case FST_FreeBSDKPrintf:
4319 case FST_Printf:
Bob Wilson57819fc2016-03-15 20:56:38 +00004320 Diag(FormatLoc, diag::note_format_security_fixit)
4321 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004322 break;
4323 case FST_NSString:
Bob Wilson57819fc2016-03-15 20:56:38 +00004324 Diag(FormatLoc, diag::note_format_security_fixit)
4325 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004326 break;
4327 }
4328 } else {
4329 Diag(FormatLoc, diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00004330 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004331 }
Richard Smith55ce3522012-06-25 20:30:08 +00004332 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004333}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00004334
Ted Kremenekab278de2010-01-28 23:39:18 +00004335namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00004336class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
4337protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00004338 Sema &S;
Stephen Hines648c3692016-09-16 01:07:04 +00004339 const FormatStringLiteral *FExpr;
Ted Kremenekab278de2010-01-28 23:39:18 +00004340 const Expr *OrigFormatExpr;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00004341 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00004342 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00004343 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00004344 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004345 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00004346 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00004347 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00004348 bool usesPositionalArgs;
4349 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00004350 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00004351 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00004352 llvm::SmallBitVector &CheckedVarArgs;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004353 UncoveredArgHandler &UncoveredArg;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004354
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004355public:
Stephen Hines648c3692016-09-16 01:07:04 +00004356 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
Ted Kremenek4d745dd2010-03-25 03:59:12 +00004357 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004358 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004359 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004360 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00004361 Sema::VariadicCallType callType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004362 llvm::SmallBitVector &CheckedVarArgs,
4363 UncoveredArgHandler &UncoveredArg)
Ted Kremenekab278de2010-01-28 23:39:18 +00004364 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004365 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
4366 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004367 Args(Args), FormatIdx(formatIdx),
Richard Trieu03cf7b72011-10-28 00:41:25 +00004368 usesPositionalArgs(false), atFirstArg(true),
Richard Smithd7293d72013-08-05 18:49:43 +00004369 inFunctionCall(inFunctionCall), CallType(callType),
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004370 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
Richard Smithd7293d72013-08-05 18:49:43 +00004371 CoveredArgs.resize(numDataArgs);
4372 CoveredArgs.reset();
4373 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004374
Ted Kremenek019d2242010-01-29 01:50:07 +00004375 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004376
Ted Kremenek02087932010-07-16 02:11:22 +00004377 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004378 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004379
Jordan Rose92303592012-09-08 04:00:03 +00004380 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00004381 const analyze_format_string::FormatSpecifier &FS,
4382 const analyze_format_string::ConversionSpecifier &CS,
4383 const char *startSpecifier, unsigned specifierLen,
4384 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00004385
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004386 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00004387 const analyze_format_string::FormatSpecifier &FS,
4388 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004389
4390 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00004391 const analyze_format_string::ConversionSpecifier &CS,
4392 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004393
Craig Toppere14c0f82014-03-12 04:55:44 +00004394 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00004395
Craig Toppere14c0f82014-03-12 04:55:44 +00004396 void HandleInvalidPosition(const char *startSpecifier,
4397 unsigned specifierLen,
4398 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00004399
Craig Toppere14c0f82014-03-12 04:55:44 +00004400 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00004401
Craig Toppere14c0f82014-03-12 04:55:44 +00004402 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004403
Richard Trieu03cf7b72011-10-28 00:41:25 +00004404 template <typename Range>
Benjamin Kramer7320b992016-06-15 14:20:56 +00004405 static void
4406 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
4407 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
4408 bool IsStringLocation, Range StringRange,
4409 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00004410
Ted Kremenek02087932010-07-16 02:11:22 +00004411protected:
Ted Kremenekce815422010-07-19 21:25:57 +00004412 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
4413 const char *startSpec,
4414 unsigned specifierLen,
4415 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00004416
4417 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
4418 const char *startSpec,
4419 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00004420
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004421 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00004422 CharSourceRange getSpecifierRange(const char *startSpecifier,
4423 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00004424 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004425
Ted Kremenek5739de72010-01-29 01:06:55 +00004426 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004427
4428 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
4429 const analyze_format_string::ConversionSpecifier &CS,
4430 const char *startSpecifier, unsigned specifierLen,
4431 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00004432
4433 template <typename Range>
4434 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
4435 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00004436 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00004437};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004438} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00004439
Ted Kremenek02087932010-07-16 02:11:22 +00004440SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00004441 return OrigFormatExpr->getSourceRange();
4442}
4443
Ted Kremenek02087932010-07-16 02:11:22 +00004444CharSourceRange CheckFormatHandler::
4445getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00004446 SourceLocation Start = getLocationOfByte(startSpecifier);
4447 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
4448
4449 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00004450 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00004451
4452 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004453}
4454
Ted Kremenek02087932010-07-16 02:11:22 +00004455SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Stephen Hines648c3692016-09-16 01:07:04 +00004456 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
4457 S.getLangOpts(), S.Context.getTargetInfo());
Ted Kremenekab278de2010-01-28 23:39:18 +00004458}
4459
Ted Kremenek02087932010-07-16 02:11:22 +00004460void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
4461 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00004462 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
4463 getLocationOfByte(startSpecifier),
4464 /*IsStringLocation*/true,
4465 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00004466}
4467
Jordan Rose92303592012-09-08 04:00:03 +00004468void CheckFormatHandler::HandleInvalidLengthModifier(
4469 const analyze_format_string::FormatSpecifier &FS,
4470 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00004471 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00004472 using namespace analyze_format_string;
4473
4474 const LengthModifier &LM = FS.getLengthModifier();
4475 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
4476
4477 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00004478 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00004479 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00004480 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00004481 getLocationOfByte(LM.getStart()),
4482 /*IsStringLocation*/true,
4483 getSpecifierRange(startSpecifier, specifierLen));
4484
4485 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
4486 << FixedLM->toString()
4487 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
4488
4489 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00004490 FixItHint Hint;
4491 if (DiagID == diag::warn_format_nonsensical_length)
4492 Hint = FixItHint::CreateRemoval(LMRange);
4493
4494 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00004495 getLocationOfByte(LM.getStart()),
4496 /*IsStringLocation*/true,
4497 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00004498 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00004499 }
4500}
4501
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004502void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00004503 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004504 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00004505 using namespace analyze_format_string;
4506
4507 const LengthModifier &LM = FS.getLengthModifier();
4508 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
4509
4510 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00004511 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00004512 if (FixedLM) {
4513 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4514 << LM.toString() << 0,
4515 getLocationOfByte(LM.getStart()),
4516 /*IsStringLocation*/true,
4517 getSpecifierRange(startSpecifier, specifierLen));
4518
4519 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
4520 << FixedLM->toString()
4521 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
4522
4523 } else {
4524 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4525 << LM.toString() << 0,
4526 getLocationOfByte(LM.getStart()),
4527 /*IsStringLocation*/true,
4528 getSpecifierRange(startSpecifier, specifierLen));
4529 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004530}
4531
4532void CheckFormatHandler::HandleNonStandardConversionSpecifier(
4533 const analyze_format_string::ConversionSpecifier &CS,
4534 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00004535 using namespace analyze_format_string;
4536
4537 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00004538 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00004539 if (FixedCS) {
4540 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4541 << CS.toString() << /*conversion specifier*/1,
4542 getLocationOfByte(CS.getStart()),
4543 /*IsStringLocation*/true,
4544 getSpecifierRange(startSpecifier, specifierLen));
4545
4546 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
4547 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
4548 << FixedCS->toString()
4549 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
4550 } else {
4551 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4552 << CS.toString() << /*conversion specifier*/1,
4553 getLocationOfByte(CS.getStart()),
4554 /*IsStringLocation*/true,
4555 getSpecifierRange(startSpecifier, specifierLen));
4556 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004557}
4558
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00004559void CheckFormatHandler::HandlePosition(const char *startPos,
4560 unsigned posLen) {
4561 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
4562 getLocationOfByte(startPos),
4563 /*IsStringLocation*/true,
4564 getSpecifierRange(startPos, posLen));
4565}
4566
Ted Kremenekd1668192010-02-27 01:41:03 +00004567void
Ted Kremenek02087932010-07-16 02:11:22 +00004568CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
4569 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004570 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
4571 << (unsigned) p,
4572 getLocationOfByte(startPos), /*IsStringLocation*/true,
4573 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00004574}
4575
Ted Kremenek02087932010-07-16 02:11:22 +00004576void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00004577 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004578 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
4579 getLocationOfByte(startPos),
4580 /*IsStringLocation*/true,
4581 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00004582}
4583
Ted Kremenek02087932010-07-16 02:11:22 +00004584void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004585 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00004586 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00004587 EmitFormatDiagnostic(
4588 S.PDiag(diag::warn_printf_format_string_contains_null_char),
4589 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
4590 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00004591 }
Ted Kremenek02087932010-07-16 02:11:22 +00004592}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004593
Jordan Rose58bbe422012-07-19 18:10:08 +00004594// Note that this may return NULL if there was an error parsing or building
4595// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00004596const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004597 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00004598}
4599
4600void CheckFormatHandler::DoneProcessing() {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004601 // Does the number of data arguments exceed the number of
4602 // format conversions in the format string?
Ted Kremenek02087932010-07-16 02:11:22 +00004603 if (!HasVAListArg) {
4604 // Find any arguments that weren't covered.
4605 CoveredArgs.flip();
4606 signed notCoveredArg = CoveredArgs.find_first();
4607 if (notCoveredArg >= 0) {
4608 assert((unsigned)notCoveredArg < NumDataArgs);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004609 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
4610 } else {
4611 UncoveredArg.setAllCovered();
Ted Kremenek02087932010-07-16 02:11:22 +00004612 }
4613 }
4614}
4615
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004616void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
4617 const Expr *ArgExpr) {
4618 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
4619 "Invalid state");
4620
4621 if (!ArgExpr)
4622 return;
4623
4624 SourceLocation Loc = ArgExpr->getLocStart();
4625
4626 if (S.getSourceManager().isInSystemMacro(Loc))
4627 return;
4628
4629 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
4630 for (auto E : DiagnosticExprs)
4631 PDiag << E->getSourceRange();
4632
4633 CheckFormatHandler::EmitFormatDiagnostic(
4634 S, IsFunctionCall, DiagnosticExprs[0],
4635 PDiag, Loc, /*IsStringLocation*/false,
4636 DiagnosticExprs[0]->getSourceRange());
4637}
4638
Ted Kremenekce815422010-07-19 21:25:57 +00004639bool
4640CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
4641 SourceLocation Loc,
4642 const char *startSpec,
4643 unsigned specifierLen,
4644 const char *csStart,
4645 unsigned csLen) {
Ted Kremenekce815422010-07-19 21:25:57 +00004646 bool keepGoing = true;
4647 if (argIndex < NumDataArgs) {
4648 // Consider the argument coverered, even though the specifier doesn't
4649 // make sense.
4650 CoveredArgs.set(argIndex);
4651 }
4652 else {
4653 // If argIndex exceeds the number of data arguments we
4654 // don't issue a warning because that is just a cascade of warnings (and
4655 // they may have intended '%%' anyway). We don't want to continue processing
4656 // the format string after this point, however, as we will like just get
4657 // gibberish when trying to match arguments.
4658 keepGoing = false;
4659 }
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00004660
4661 StringRef Specifier(csStart, csLen);
4662
4663 // If the specifier in non-printable, it could be the first byte of a UTF-8
4664 // sequence. In that case, print the UTF-8 code point. If not, print the byte
4665 // hex value.
4666 std::string CodePointStr;
4667 if (!llvm::sys::locale::isPrint(*csStart)) {
4668 UTF32 CodePoint;
4669 const UTF8 **B = reinterpret_cast<const UTF8 **>(&csStart);
4670 const UTF8 *E =
4671 reinterpret_cast<const UTF8 *>(csStart + csLen);
4672 ConversionResult Result =
4673 llvm::convertUTF8Sequence(B, E, &CodePoint, strictConversion);
4674
4675 if (Result != conversionOK) {
4676 unsigned char FirstChar = *csStart;
4677 CodePoint = (UTF32)FirstChar;
4678 }
4679
4680 llvm::raw_string_ostream OS(CodePointStr);
4681 if (CodePoint < 256)
4682 OS << "\\x" << llvm::format("%02x", CodePoint);
4683 else if (CodePoint <= 0xFFFF)
4684 OS << "\\u" << llvm::format("%04x", CodePoint);
4685 else
4686 OS << "\\U" << llvm::format("%08x", CodePoint);
4687 OS.flush();
4688 Specifier = CodePointStr;
4689 }
4690
4691 EmitFormatDiagnostic(
4692 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
4693 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
4694
Ted Kremenekce815422010-07-19 21:25:57 +00004695 return keepGoing;
4696}
4697
Richard Trieu03cf7b72011-10-28 00:41:25 +00004698void
4699CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
4700 const char *startSpec,
4701 unsigned specifierLen) {
4702 EmitFormatDiagnostic(
4703 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
4704 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
4705}
4706
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004707bool
4708CheckFormatHandler::CheckNumArgs(
4709 const analyze_format_string::FormatSpecifier &FS,
4710 const analyze_format_string::ConversionSpecifier &CS,
4711 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
4712
4713 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004714 PartialDiagnostic PDiag = FS.usesPositionalArg()
4715 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
4716 << (argIndex+1) << NumDataArgs)
4717 : S.PDiag(diag::warn_printf_insufficient_data_args);
4718 EmitFormatDiagnostic(
4719 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
4720 getSpecifierRange(startSpecifier, specifierLen));
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004721
4722 // Since more arguments than conversion tokens are given, by extension
4723 // all arguments are covered, so mark this as so.
4724 UncoveredArg.setAllCovered();
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004725 return false;
4726 }
4727 return true;
4728}
4729
Richard Trieu03cf7b72011-10-28 00:41:25 +00004730template<typename Range>
4731void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
4732 SourceLocation Loc,
4733 bool IsStringLocation,
4734 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00004735 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004736 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00004737 Loc, IsStringLocation, StringRange, FixIt);
4738}
4739
4740/// \brief If the format string is not within the funcion call, emit a note
4741/// so that the function call and string are in diagnostic messages.
4742///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00004743/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00004744/// call and only one diagnostic message will be produced. Otherwise, an
4745/// extra note will be emitted pointing to location of the format string.
4746///
4747/// \param ArgumentExpr the expression that is passed as the format string
4748/// argument in the function call. Used for getting locations when two
4749/// diagnostics are emitted.
4750///
4751/// \param PDiag the callee should already have provided any strings for the
4752/// diagnostic message. This function only adds locations and fixits
4753/// to diagnostics.
4754///
4755/// \param Loc primary location for diagnostic. If two diagnostics are
4756/// required, one will be at Loc and a new SourceLocation will be created for
4757/// the other one.
4758///
4759/// \param IsStringLocation if true, Loc points to the format string should be
4760/// used for the note. Otherwise, Loc points to the argument list and will
4761/// be used with PDiag.
4762///
4763/// \param StringRange some or all of the string to highlight. This is
4764/// templated so it can accept either a CharSourceRange or a SourceRange.
4765///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00004766/// \param FixIt optional fix it hint for the format string.
Benjamin Kramer7320b992016-06-15 14:20:56 +00004767template <typename Range>
4768void CheckFormatHandler::EmitFormatDiagnostic(
4769 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
4770 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
4771 Range StringRange, ArrayRef<FixItHint> FixIt) {
Jordan Roseaee34382012-09-05 22:56:26 +00004772 if (InFunctionCall) {
4773 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
4774 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00004775 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00004776 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004777 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
4778 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00004779
4780 const Sema::SemaDiagnosticBuilder &Note =
4781 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
4782 diag::note_format_string_defined);
4783
4784 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00004785 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00004786 }
4787}
4788
Ted Kremenek02087932010-07-16 02:11:22 +00004789//===--- CHECK: Printf format string checking ------------------------------===//
4790
4791namespace {
4792class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004793 bool ObjCContext;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004794
Ted Kremenek02087932010-07-16 02:11:22 +00004795public:
Stephen Hines648c3692016-09-16 01:07:04 +00004796 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
Ted Kremenek02087932010-07-16 02:11:22 +00004797 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004798 unsigned numDataArgs, bool isObjC,
Ted Kremenek02087932010-07-16 02:11:22 +00004799 const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004800 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004801 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00004802 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004803 llvm::SmallBitVector &CheckedVarArgs,
4804 UncoveredArgHandler &UncoveredArg)
Richard Smithd7293d72013-08-05 18:49:43 +00004805 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
4806 numDataArgs, beg, hasVAListArg, Args,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004807 formatIdx, inFunctionCall, CallType, CheckedVarArgs,
4808 UncoveredArg),
Richard Smithd7293d72013-08-05 18:49:43 +00004809 ObjCContext(isObjC)
Jordan Rose3e0ec582012-07-19 18:10:23 +00004810 {}
4811
Ted Kremenek02087932010-07-16 02:11:22 +00004812 bool HandleInvalidPrintfConversionSpecifier(
4813 const analyze_printf::PrintfSpecifier &FS,
4814 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004815 unsigned specifierLen) override;
4816
Ted Kremenek02087932010-07-16 02:11:22 +00004817 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
4818 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004819 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00004820 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
4821 const char *StartSpecifier,
4822 unsigned SpecifierLen,
4823 const Expr *E);
4824
Ted Kremenek02087932010-07-16 02:11:22 +00004825 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
4826 const char *startSpecifier, unsigned specifierLen);
4827 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
4828 const analyze_printf::OptionalAmount &Amt,
4829 unsigned type,
4830 const char *startSpecifier, unsigned specifierLen);
4831 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
4832 const analyze_printf::OptionalFlag &flag,
4833 const char *startSpecifier, unsigned specifierLen);
4834 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
4835 const analyze_printf::OptionalFlag &ignoredFlag,
4836 const analyze_printf::OptionalFlag &flag,
4837 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004838 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00004839 const Expr *E);
Ted Kremenek2b417712015-07-02 05:39:16 +00004840
4841 void HandleEmptyObjCModifierFlag(const char *startFlag,
4842 unsigned flagLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00004843
Ted Kremenek2b417712015-07-02 05:39:16 +00004844 void HandleInvalidObjCModifierFlag(const char *startFlag,
4845 unsigned flagLen) override;
4846
4847 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
4848 const char *flagsEnd,
4849 const char *conversionPosition)
4850 override;
4851};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004852} // end anonymous namespace
Ted Kremenek02087932010-07-16 02:11:22 +00004853
4854bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
4855 const analyze_printf::PrintfSpecifier &FS,
4856 const char *startSpecifier,
4857 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004858 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00004859 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00004860
Ted Kremenekce815422010-07-19 21:25:57 +00004861 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
4862 getLocationOfByte(CS.getStart()),
4863 startSpecifier, specifierLen,
4864 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00004865}
4866
Ted Kremenek02087932010-07-16 02:11:22 +00004867bool CheckPrintfHandler::HandleAmount(
4868 const analyze_format_string::OptionalAmount &Amt,
4869 unsigned k, const char *startSpecifier,
4870 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00004871 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00004872 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00004873 unsigned argIndex = Amt.getArgIndex();
4874 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004875 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
4876 << k,
4877 getLocationOfByte(Amt.getStart()),
4878 /*IsStringLocation*/true,
4879 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00004880 // Don't do any more checking. We will just emit
4881 // spurious errors.
4882 return false;
4883 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004884
Ted Kremenek5739de72010-01-29 01:06:55 +00004885 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00004886 // Although not in conformance with C99, we also allow the argument to be
4887 // an 'unsigned int' as that is a reasonably safe case. GCC also
4888 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00004889 CoveredArgs.set(argIndex);
4890 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00004891 if (!Arg)
4892 return false;
4893
Ted Kremenek5739de72010-01-29 01:06:55 +00004894 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004895
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004896 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
4897 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004898
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004899 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004900 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004901 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00004902 << T << Arg->getSourceRange(),
4903 getLocationOfByte(Amt.getStart()),
4904 /*IsStringLocation*/true,
4905 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00004906 // Don't do any more checking. We will just emit
4907 // spurious errors.
4908 return false;
4909 }
4910 }
4911 }
4912 return true;
4913}
Ted Kremenek5739de72010-01-29 01:06:55 +00004914
Tom Careb49ec692010-06-17 19:00:27 +00004915void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00004916 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00004917 const analyze_printf::OptionalAmount &Amt,
4918 unsigned type,
4919 const char *startSpecifier,
4920 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004921 const analyze_printf::PrintfConversionSpecifier &CS =
4922 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00004923
Richard Trieu03cf7b72011-10-28 00:41:25 +00004924 FixItHint fixit =
4925 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
4926 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
4927 Amt.getConstantLength()))
4928 : FixItHint();
4929
4930 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
4931 << type << CS.toString(),
4932 getLocationOfByte(Amt.getStart()),
4933 /*IsStringLocation*/true,
4934 getSpecifierRange(startSpecifier, specifierLen),
4935 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00004936}
4937
Ted Kremenek02087932010-07-16 02:11:22 +00004938void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00004939 const analyze_printf::OptionalFlag &flag,
4940 const char *startSpecifier,
4941 unsigned specifierLen) {
4942 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004943 const analyze_printf::PrintfConversionSpecifier &CS =
4944 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00004945 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
4946 << flag.toString() << CS.toString(),
4947 getLocationOfByte(flag.getPosition()),
4948 /*IsStringLocation*/true,
4949 getSpecifierRange(startSpecifier, specifierLen),
4950 FixItHint::CreateRemoval(
4951 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00004952}
4953
4954void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00004955 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00004956 const analyze_printf::OptionalFlag &ignoredFlag,
4957 const analyze_printf::OptionalFlag &flag,
4958 const char *startSpecifier,
4959 unsigned specifierLen) {
4960 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00004961 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
4962 << ignoredFlag.toString() << flag.toString(),
4963 getLocationOfByte(ignoredFlag.getPosition()),
4964 /*IsStringLocation*/true,
4965 getSpecifierRange(startSpecifier, specifierLen),
4966 FixItHint::CreateRemoval(
4967 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00004968}
4969
Ted Kremenek2b417712015-07-02 05:39:16 +00004970// void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
4971// bool IsStringLocation, Range StringRange,
4972// ArrayRef<FixItHint> Fixit = None);
4973
4974void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
4975 unsigned flagLen) {
4976 // Warn about an empty flag.
4977 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
4978 getLocationOfByte(startFlag),
4979 /*IsStringLocation*/true,
4980 getSpecifierRange(startFlag, flagLen));
4981}
4982
4983void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
4984 unsigned flagLen) {
4985 // Warn about an invalid flag.
4986 auto Range = getSpecifierRange(startFlag, flagLen);
4987 StringRef flag(startFlag, flagLen);
4988 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
4989 getLocationOfByte(startFlag),
4990 /*IsStringLocation*/true,
4991 Range, FixItHint::CreateRemoval(Range));
4992}
4993
4994void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
4995 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
4996 // Warn about using '[...]' without a '@' conversion.
4997 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
4998 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
4999 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
5000 getLocationOfByte(conversionPosition),
5001 /*IsStringLocation*/true,
5002 Range, FixItHint::CreateRemoval(Range));
5003}
5004
Richard Smith55ce3522012-06-25 20:30:08 +00005005// Determines if the specified is a C++ class or struct containing
5006// a member with the specified name and kind (e.g. a CXXMethodDecl named
5007// "c_str()").
5008template<typename MemberKind>
5009static llvm::SmallPtrSet<MemberKind*, 1>
5010CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
5011 const RecordType *RT = Ty->getAs<RecordType>();
5012 llvm::SmallPtrSet<MemberKind*, 1> Results;
5013
5014 if (!RT)
5015 return Results;
5016 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00005017 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00005018 return Results;
5019
Alp Tokerb6cc5922014-05-03 03:45:55 +00005020 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00005021 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00005022 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00005023
5024 // We just need to include all members of the right kind turned up by the
5025 // filter, at this point.
5026 if (S.LookupQualifiedName(R, RT->getDecl()))
5027 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
5028 NamedDecl *decl = (*I)->getUnderlyingDecl();
5029 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
5030 Results.insert(FK);
5031 }
5032 return Results;
5033}
5034
Richard Smith2868a732014-02-28 01:36:39 +00005035/// Check if we could call '.c_str()' on an object.
5036///
5037/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
5038/// allow the call, or if it would be ambiguous).
5039bool Sema::hasCStrMethod(const Expr *E) {
5040 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5041 MethodSet Results =
5042 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
5043 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5044 MI != ME; ++MI)
5045 if ((*MI)->getMinRequiredArguments() == 0)
5046 return true;
5047 return false;
5048}
5049
Richard Smith55ce3522012-06-25 20:30:08 +00005050// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005051// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00005052// Returns true when a c_str() conversion method is found.
5053bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00005054 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00005055 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5056
5057 MethodSet Results =
5058 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
5059
5060 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5061 MI != ME; ++MI) {
5062 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00005063 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00005064 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00005065 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00005066 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00005067 S.Diag(E->getLocStart(), diag::note_printf_c_str)
5068 << "c_str()"
5069 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
5070 return true;
5071 }
5072 }
5073
5074 return false;
5075}
5076
Ted Kremenekab278de2010-01-28 23:39:18 +00005077bool
Ted Kremenek02087932010-07-16 02:11:22 +00005078CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00005079 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00005080 const char *startSpecifier,
5081 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005082 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00005083 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005084 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00005085
Ted Kremenek6cd69422010-07-19 22:01:06 +00005086 if (FS.consumesDataArgument()) {
5087 if (atFirstArg) {
5088 atFirstArg = false;
5089 usesPositionalArgs = FS.usesPositionalArg();
5090 }
5091 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005092 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
5093 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00005094 return false;
5095 }
Ted Kremenek5739de72010-01-29 01:06:55 +00005096 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005097
Ted Kremenekd1668192010-02-27 01:41:03 +00005098 // First check if the field width, precision, and conversion specifier
5099 // have matching data arguments.
5100 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
5101 startSpecifier, specifierLen)) {
5102 return false;
5103 }
5104
5105 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
5106 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00005107 return false;
5108 }
5109
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005110 if (!CS.consumesDataArgument()) {
5111 // FIXME: Technically specifying a precision or field width here
5112 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00005113 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005114 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005115
Ted Kremenek4a49d982010-02-26 19:18:41 +00005116 // Consume the argument.
5117 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00005118 if (argIndex < NumDataArgs) {
5119 // The check to see if the argIndex is valid will come later.
5120 // We set the bit here because we may exit early from this
5121 // function if we encounter some other error.
5122 CoveredArgs.set(argIndex);
5123 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00005124
Dimitry Andric6b5ed342015-02-19 22:32:33 +00005125 // FreeBSD kernel extensions.
5126 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
5127 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
5128 // We need at least two arguments.
5129 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
5130 return false;
5131
5132 // Claim the second argument.
5133 CoveredArgs.set(argIndex + 1);
5134
5135 // Type check the first argument (int for %b, pointer for %D)
5136 const Expr *Ex = getDataArg(argIndex);
5137 const analyze_printf::ArgType &AT =
5138 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
5139 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
5140 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
5141 EmitFormatDiagnostic(
5142 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5143 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
5144 << false << Ex->getSourceRange(),
5145 Ex->getLocStart(), /*IsStringLocation*/false,
5146 getSpecifierRange(startSpecifier, specifierLen));
5147
5148 // Type check the second argument (char * for both %b and %D)
5149 Ex = getDataArg(argIndex + 1);
5150 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
5151 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
5152 EmitFormatDiagnostic(
5153 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5154 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
5155 << false << Ex->getSourceRange(),
5156 Ex->getLocStart(), /*IsStringLocation*/false,
5157 getSpecifierRange(startSpecifier, specifierLen));
5158
5159 return true;
5160 }
5161
Ted Kremenek4a49d982010-02-26 19:18:41 +00005162 // Check for using an Objective-C specific conversion specifier
5163 // in a non-ObjC literal.
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005164 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00005165 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5166 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00005167 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005168
Tom Careb49ec692010-06-17 19:00:27 +00005169 // Check for invalid use of field width
5170 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00005171 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00005172 startSpecifier, specifierLen);
5173 }
5174
5175 // Check for invalid use of precision
5176 if (!FS.hasValidPrecision()) {
5177 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
5178 startSpecifier, specifierLen);
5179 }
5180
5181 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00005182 if (!FS.hasValidThousandsGroupingPrefix())
5183 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00005184 if (!FS.hasValidLeadingZeros())
5185 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
5186 if (!FS.hasValidPlusPrefix())
5187 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00005188 if (!FS.hasValidSpacePrefix())
5189 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00005190 if (!FS.hasValidAlternativeForm())
5191 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
5192 if (!FS.hasValidLeftJustified())
5193 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
5194
5195 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00005196 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
5197 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
5198 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00005199 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
5200 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
5201 startSpecifier, specifierLen);
5202
5203 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00005204 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00005205 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5206 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00005207 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00005208 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00005209 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00005210 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5211 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00005212
Jordan Rose92303592012-09-08 04:00:03 +00005213 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
5214 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
5215
Ted Kremenek9fcd8302010-01-29 01:43:31 +00005216 // The remaining checks depend on the data arguments.
5217 if (HasVAListArg)
5218 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005219
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005220 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00005221 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005222
Jordan Rose58bbe422012-07-19 18:10:08 +00005223 const Expr *Arg = getDataArg(argIndex);
5224 if (!Arg)
5225 return true;
5226
5227 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00005228}
5229
Jordan Roseaee34382012-09-05 22:56:26 +00005230static bool requiresParensToAddCast(const Expr *E) {
5231 // FIXME: We should have a general way to reason about operator
5232 // precedence and whether parens are actually needed here.
5233 // Take care of a few common cases where they aren't.
5234 const Expr *Inside = E->IgnoreImpCasts();
5235 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
5236 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
5237
5238 switch (Inside->getStmtClass()) {
5239 case Stmt::ArraySubscriptExprClass:
5240 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005241 case Stmt::CharacterLiteralClass:
5242 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005243 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005244 case Stmt::FloatingLiteralClass:
5245 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005246 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005247 case Stmt::ObjCArrayLiteralClass:
5248 case Stmt::ObjCBoolLiteralExprClass:
5249 case Stmt::ObjCBoxedExprClass:
5250 case Stmt::ObjCDictionaryLiteralClass:
5251 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005252 case Stmt::ObjCIvarRefExprClass:
5253 case Stmt::ObjCMessageExprClass:
5254 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005255 case Stmt::ObjCStringLiteralClass:
5256 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005257 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005258 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005259 case Stmt::UnaryOperatorClass:
5260 return false;
5261 default:
5262 return true;
5263 }
5264}
5265
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005266static std::pair<QualType, StringRef>
5267shouldNotPrintDirectly(const ASTContext &Context,
5268 QualType IntendedTy,
5269 const Expr *E) {
5270 // Use a 'while' to peel off layers of typedefs.
5271 QualType TyTy = IntendedTy;
5272 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
5273 StringRef Name = UserTy->getDecl()->getName();
5274 QualType CastTy = llvm::StringSwitch<QualType>(Name)
5275 .Case("NSInteger", Context.LongTy)
5276 .Case("NSUInteger", Context.UnsignedLongTy)
5277 .Case("SInt32", Context.IntTy)
5278 .Case("UInt32", Context.UnsignedIntTy)
5279 .Default(QualType());
5280
5281 if (!CastTy.isNull())
5282 return std::make_pair(CastTy, Name);
5283
5284 TyTy = UserTy->desugar();
5285 }
5286
5287 // Strip parens if necessary.
5288 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
5289 return shouldNotPrintDirectly(Context,
5290 PE->getSubExpr()->getType(),
5291 PE->getSubExpr());
5292
5293 // If this is a conditional expression, then its result type is constructed
5294 // via usual arithmetic conversions and thus there might be no necessary
5295 // typedef sugar there. Recurse to operands to check for NSInteger &
5296 // Co. usage condition.
5297 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
5298 QualType TrueTy, FalseTy;
5299 StringRef TrueName, FalseName;
5300
5301 std::tie(TrueTy, TrueName) =
5302 shouldNotPrintDirectly(Context,
5303 CO->getTrueExpr()->getType(),
5304 CO->getTrueExpr());
5305 std::tie(FalseTy, FalseName) =
5306 shouldNotPrintDirectly(Context,
5307 CO->getFalseExpr()->getType(),
5308 CO->getFalseExpr());
5309
5310 if (TrueTy == FalseTy)
5311 return std::make_pair(TrueTy, TrueName);
5312 else if (TrueTy.isNull())
5313 return std::make_pair(FalseTy, FalseName);
5314 else if (FalseTy.isNull())
5315 return std::make_pair(TrueTy, TrueName);
5316 }
5317
5318 return std::make_pair(QualType(), StringRef());
5319}
5320
Richard Smith55ce3522012-06-25 20:30:08 +00005321bool
5322CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5323 const char *StartSpecifier,
5324 unsigned SpecifierLen,
5325 const Expr *E) {
5326 using namespace analyze_format_string;
5327 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005328 // Now type check the data expression that matches the
5329 // format specifier.
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005330 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
5331 ObjCContext);
Jordan Rose22b74712012-09-05 22:56:19 +00005332 if (!AT.isValid())
5333 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00005334
Jordan Rose598ec092012-12-05 18:44:40 +00005335 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00005336 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
5337 ExprTy = TET->getUnderlyingExpr()->getType();
5338 }
5339
Seth Cantrellb4802962015-03-04 03:12:10 +00005340 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
5341
5342 if (match == analyze_printf::ArgType::Match) {
Jordan Rose22b74712012-09-05 22:56:19 +00005343 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00005344 }
Jordan Rose98709982012-06-04 22:48:57 +00005345
Jordan Rose22b74712012-09-05 22:56:19 +00005346 // Look through argument promotions for our error message's reported type.
5347 // This includes the integral and floating promotions, but excludes array
5348 // and function pointer decay; seeing that an argument intended to be a
5349 // string has type 'char [6]' is probably more confusing than 'char *'.
5350 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5351 if (ICE->getCastKind() == CK_IntegralCast ||
5352 ICE->getCastKind() == CK_FloatingCast) {
5353 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00005354 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00005355
5356 // Check if we didn't match because of an implicit cast from a 'char'
5357 // or 'short' to an 'int'. This is done because printf is a varargs
5358 // function.
5359 if (ICE->getType() == S.Context.IntTy ||
5360 ICE->getType() == S.Context.UnsignedIntTy) {
5361 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00005362 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00005363 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00005364 }
Jordan Rose98709982012-06-04 22:48:57 +00005365 }
Jordan Rose598ec092012-12-05 18:44:40 +00005366 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
5367 // Special case for 'a', which has type 'int' in C.
5368 // Note, however, that we do /not/ want to treat multibyte constants like
5369 // 'MooV' as characters! This form is deprecated but still exists.
5370 if (ExprTy == S.Context.IntTy)
5371 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
5372 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00005373 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005374
Jordan Rosebc53ed12014-05-31 04:12:14 +00005375 // Look through enums to their underlying type.
5376 bool IsEnum = false;
5377 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
5378 ExprTy = EnumTy->getDecl()->getIntegerType();
5379 IsEnum = true;
5380 }
5381
Jordan Rose0e5badd2012-12-05 18:44:49 +00005382 // %C in an Objective-C context prints a unichar, not a wchar_t.
5383 // If the argument is an integer of some kind, believe the %C and suggest
5384 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00005385 QualType IntendedTy = ExprTy;
Jordan Rose0e5badd2012-12-05 18:44:49 +00005386 if (ObjCContext &&
5387 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
5388 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
5389 !ExprTy->isCharType()) {
5390 // 'unichar' is defined as a typedef of unsigned short, but we should
5391 // prefer using the typedef if it is visible.
5392 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00005393
5394 // While we are here, check if the value is an IntegerLiteral that happens
5395 // to be within the valid range.
5396 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
5397 const llvm::APInt &V = IL->getValue();
5398 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
5399 return true;
5400 }
5401
Jordan Rose0e5badd2012-12-05 18:44:49 +00005402 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
5403 Sema::LookupOrdinaryName);
5404 if (S.LookupName(Result, S.getCurScope())) {
5405 NamedDecl *ND = Result.getFoundDecl();
5406 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
5407 if (TD->getUnderlyingType() == IntendedTy)
5408 IntendedTy = S.Context.getTypedefType(TD);
5409 }
5410 }
5411 }
5412
5413 // Special-case some of Darwin's platform-independence types by suggesting
5414 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005415 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00005416 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005417 QualType CastTy;
5418 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
5419 if (!CastTy.isNull()) {
5420 IntendedTy = CastTy;
5421 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00005422 }
5423 }
5424
Jordan Rose22b74712012-09-05 22:56:19 +00005425 // We may be able to offer a FixItHint if it is a supported type.
5426 PrintfSpecifier fixedFS = FS;
Jordan Roseaee34382012-09-05 22:56:26 +00005427 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose22b74712012-09-05 22:56:19 +00005428 S.Context, ObjCContext);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005429
Jordan Rose22b74712012-09-05 22:56:19 +00005430 if (success) {
5431 // Get the fix string from the fixed format specifier
5432 SmallString<16> buf;
5433 llvm::raw_svector_ostream os(buf);
5434 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005435
Jordan Roseaee34382012-09-05 22:56:26 +00005436 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
5437
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005438 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Daniel Jasperad8d8492015-03-04 14:18:20 +00005439 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
5440 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
5441 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
5442 }
Jordan Rose0e5badd2012-12-05 18:44:49 +00005443 // In this case, the specifier is wrong and should be changed to match
5444 // the argument.
Daniel Jasperad8d8492015-03-04 14:18:20 +00005445 EmitFormatDiagnostic(S.PDiag(diag)
5446 << AT.getRepresentativeTypeName(S.Context)
5447 << IntendedTy << IsEnum << E->getSourceRange(),
5448 E->getLocStart(),
5449 /*IsStringLocation*/ false, SpecRange,
5450 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00005451 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00005452 // The canonical type for formatting this value is different from the
5453 // actual type of the expression. (This occurs, for example, with Darwin's
5454 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
5455 // should be printed as 'long' for 64-bit compatibility.)
5456 // Rather than emitting a normal format/argument mismatch, we want to
5457 // add a cast to the recommended type (and correct the format string
5458 // if necessary).
5459 SmallString<16> CastBuf;
5460 llvm::raw_svector_ostream CastFix(CastBuf);
5461 CastFix << "(";
5462 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
5463 CastFix << ")";
5464
5465 SmallVector<FixItHint,4> Hints;
5466 if (!AT.matchesType(S.Context, IntendedTy))
5467 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
5468
5469 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
5470 // If there's already a cast present, just replace it.
5471 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
5472 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
5473
5474 } else if (!requiresParensToAddCast(E)) {
5475 // If the expression has high enough precedence,
5476 // just write the C-style cast.
5477 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
5478 CastFix.str()));
5479 } else {
5480 // Otherwise, add parens around the expression as well as the cast.
5481 CastFix << "(";
5482 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
5483 CastFix.str()));
5484
Alp Tokerb6cc5922014-05-03 03:45:55 +00005485 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00005486 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
5487 }
5488
Jordan Rose0e5badd2012-12-05 18:44:49 +00005489 if (ShouldNotPrintDirectly) {
5490 // The expression has a type that should not be printed directly.
5491 // We extract the name from the typedef because we don't want to show
5492 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005493 StringRef Name;
5494 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
5495 Name = TypedefTy->getDecl()->getName();
5496 else
5497 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00005498 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00005499 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00005500 << E->getSourceRange(),
5501 E->getLocStart(), /*IsStringLocation=*/false,
5502 SpecRange, Hints);
5503 } else {
5504 // In this case, the expression could be printed using a different
5505 // specifier, but we've decided that the specifier is probably correct
5506 // and we should cast instead. Just use the normal warning message.
5507 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00005508 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5509 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00005510 << E->getSourceRange(),
5511 E->getLocStart(), /*IsStringLocation*/false,
5512 SpecRange, Hints);
5513 }
Jordan Roseaee34382012-09-05 22:56:26 +00005514 }
Jordan Rose22b74712012-09-05 22:56:19 +00005515 } else {
5516 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
5517 SpecifierLen);
5518 // Since the warning for passing non-POD types to variadic functions
5519 // was deferred until now, we emit a warning for non-POD
5520 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00005521 switch (S.isValidVarArgType(ExprTy)) {
5522 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00005523 case Sema::VAK_ValidInCXX11: {
5524 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
5525 if (match == analyze_printf::ArgType::NoMatchPedantic) {
5526 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
5527 }
Richard Smithd7293d72013-08-05 18:49:43 +00005528
Seth Cantrellb4802962015-03-04 03:12:10 +00005529 EmitFormatDiagnostic(
5530 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
5531 << IsEnum << CSR << E->getSourceRange(),
5532 E->getLocStart(), /*IsStringLocation*/ false, CSR);
5533 break;
5534 }
Richard Smithd7293d72013-08-05 18:49:43 +00005535 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00005536 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00005537 EmitFormatDiagnostic(
5538 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005539 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00005540 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00005541 << CallType
5542 << AT.getRepresentativeTypeName(S.Context)
5543 << CSR
5544 << E->getSourceRange(),
5545 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00005546 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00005547 break;
5548
5549 case Sema::VAK_Invalid:
5550 if (ExprTy->isObjCObjectType())
5551 EmitFormatDiagnostic(
5552 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
5553 << S.getLangOpts().CPlusPlus11
5554 << ExprTy
5555 << CallType
5556 << AT.getRepresentativeTypeName(S.Context)
5557 << CSR
5558 << E->getSourceRange(),
5559 E->getLocStart(), /*IsStringLocation*/false, CSR);
5560 else
5561 // FIXME: If this is an initializer list, suggest removing the braces
5562 // or inserting a cast to the target type.
5563 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
5564 << isa<InitListExpr>(E) << ExprTy << CallType
5565 << AT.getRepresentativeTypeName(S.Context)
5566 << E->getSourceRange();
5567 break;
5568 }
5569
5570 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
5571 "format string specifier index out of range");
5572 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005573 }
5574
Ted Kremenekab278de2010-01-28 23:39:18 +00005575 return true;
5576}
5577
Ted Kremenek02087932010-07-16 02:11:22 +00005578//===--- CHECK: Scanf format string checking ------------------------------===//
5579
5580namespace {
5581class CheckScanfHandler : public CheckFormatHandler {
5582public:
Stephen Hines648c3692016-09-16 01:07:04 +00005583 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
Ted Kremenek02087932010-07-16 02:11:22 +00005584 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005585 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005586 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005587 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00005588 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005589 llvm::SmallBitVector &CheckedVarArgs,
5590 UncoveredArgHandler &UncoveredArg)
Richard Smithd7293d72013-08-05 18:49:43 +00005591 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
5592 numDataArgs, beg, hasVAListArg,
5593 Args, formatIdx, inFunctionCall, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005594 CheckedVarArgs, UncoveredArg)
Jordan Rose3e0ec582012-07-19 18:10:23 +00005595 {}
Ted Kremenek02087932010-07-16 02:11:22 +00005596
5597 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
5598 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005599 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00005600
5601 bool HandleInvalidScanfConversionSpecifier(
5602 const analyze_scanf::ScanfSpecifier &FS,
5603 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005604 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00005605
Craig Toppere14c0f82014-03-12 04:55:44 +00005606 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00005607};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005608} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00005609
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00005610void CheckScanfHandler::HandleIncompleteScanList(const char *start,
5611 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005612 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
5613 getLocationOfByte(end), /*IsStringLocation*/true,
5614 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00005615}
5616
Ted Kremenekce815422010-07-19 21:25:57 +00005617bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
5618 const analyze_scanf::ScanfSpecifier &FS,
5619 const char *startSpecifier,
5620 unsigned specifierLen) {
5621
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005622 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00005623 FS.getConversionSpecifier();
5624
5625 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
5626 getLocationOfByte(CS.getStart()),
5627 startSpecifier, specifierLen,
5628 CS.getStart(), CS.getLength());
5629}
5630
Ted Kremenek02087932010-07-16 02:11:22 +00005631bool CheckScanfHandler::HandleScanfSpecifier(
5632 const analyze_scanf::ScanfSpecifier &FS,
5633 const char *startSpecifier,
5634 unsigned specifierLen) {
Ted Kremenek02087932010-07-16 02:11:22 +00005635 using namespace analyze_scanf;
5636 using namespace analyze_format_string;
5637
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005638 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00005639
Ted Kremenek6cd69422010-07-19 22:01:06 +00005640 // Handle case where '%' and '*' don't consume an argument. These shouldn't
5641 // be used to decide if we are using positional arguments consistently.
5642 if (FS.consumesDataArgument()) {
5643 if (atFirstArg) {
5644 atFirstArg = false;
5645 usesPositionalArgs = FS.usesPositionalArg();
5646 }
5647 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005648 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
5649 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00005650 return false;
5651 }
Ted Kremenek02087932010-07-16 02:11:22 +00005652 }
5653
5654 // Check if the field with is non-zero.
5655 const OptionalAmount &Amt = FS.getFieldWidth();
5656 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
5657 if (Amt.getConstantAmount() == 0) {
5658 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
5659 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00005660 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
5661 getLocationOfByte(Amt.getStart()),
5662 /*IsStringLocation*/true, R,
5663 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00005664 }
5665 }
Seth Cantrellb4802962015-03-04 03:12:10 +00005666
Ted Kremenek02087932010-07-16 02:11:22 +00005667 if (!FS.consumesDataArgument()) {
5668 // FIXME: Technically specifying a precision or field width here
5669 // makes no sense. Worth issuing a warning at some point.
5670 return true;
5671 }
Seth Cantrellb4802962015-03-04 03:12:10 +00005672
Ted Kremenek02087932010-07-16 02:11:22 +00005673 // Consume the argument.
5674 unsigned argIndex = FS.getArgIndex();
5675 if (argIndex < NumDataArgs) {
5676 // The check to see if the argIndex is valid will come later.
5677 // We set the bit here because we may exit early from this
5678 // function if we encounter some other error.
5679 CoveredArgs.set(argIndex);
5680 }
Seth Cantrellb4802962015-03-04 03:12:10 +00005681
Ted Kremenek4407ea42010-07-20 20:04:47 +00005682 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00005683 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00005684 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5685 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00005686 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00005687 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00005688 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00005689 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5690 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005691
Jordan Rose92303592012-09-08 04:00:03 +00005692 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
5693 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
5694
Ted Kremenek02087932010-07-16 02:11:22 +00005695 // The remaining checks depend on the data arguments.
5696 if (HasVAListArg)
5697 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00005698
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005699 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00005700 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00005701
Hans Wennborgb1a5e092011-12-10 13:20:11 +00005702 // Check that the argument type matches the format specifier.
5703 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00005704 if (!Ex)
5705 return true;
5706
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00005707 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00005708
5709 if (!AT.isValid()) {
5710 return true;
5711 }
5712
Seth Cantrellb4802962015-03-04 03:12:10 +00005713 analyze_format_string::ArgType::MatchKind match =
5714 AT.matchesType(S.Context, Ex->getType());
Seth Cantrell79340072015-03-04 05:58:08 +00005715 if (match == analyze_format_string::ArgType::Match) {
5716 return true;
5717 }
Seth Cantrellb4802962015-03-04 03:12:10 +00005718
Seth Cantrell79340072015-03-04 05:58:08 +00005719 ScanfSpecifier fixedFS = FS;
5720 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
5721 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00005722
Seth Cantrell79340072015-03-04 05:58:08 +00005723 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
5724 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
5725 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
5726 }
Hans Wennborgb1a5e092011-12-10 13:20:11 +00005727
Seth Cantrell79340072015-03-04 05:58:08 +00005728 if (success) {
5729 // Get the fix string from the fixed format specifier.
5730 SmallString<128> buf;
5731 llvm::raw_svector_ostream os(buf);
5732 fixedFS.toString(os);
5733
5734 EmitFormatDiagnostic(
5735 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
5736 << Ex->getType() << false << Ex->getSourceRange(),
5737 Ex->getLocStart(),
5738 /*IsStringLocation*/ false,
5739 getSpecifierRange(startSpecifier, specifierLen),
5740 FixItHint::CreateReplacement(
5741 getSpecifierRange(startSpecifier, specifierLen), os.str()));
5742 } else {
5743 EmitFormatDiagnostic(S.PDiag(diag)
5744 << AT.getRepresentativeTypeName(S.Context)
5745 << Ex->getType() << false << Ex->getSourceRange(),
5746 Ex->getLocStart(),
5747 /*IsStringLocation*/ false,
5748 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00005749 }
5750
Ted Kremenek02087932010-07-16 02:11:22 +00005751 return true;
5752}
5753
Stephen Hines648c3692016-09-16 01:07:04 +00005754static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005755 const Expr *OrigFormatExpr,
5756 ArrayRef<const Expr *> Args,
5757 bool HasVAListArg, unsigned format_idx,
5758 unsigned firstDataArg,
5759 Sema::FormatStringType Type,
5760 bool inFunctionCall,
5761 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005762 llvm::SmallBitVector &CheckedVarArgs,
5763 UncoveredArgHandler &UncoveredArg) {
Ted Kremenekab278de2010-01-28 23:39:18 +00005764 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00005765 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005766 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005767 S, inFunctionCall, Args[format_idx],
5768 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00005769 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00005770 return;
5771 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005772
Ted Kremenekab278de2010-01-28 23:39:18 +00005773 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005774 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00005775 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00005776 // Account for cases where the string literal is truncated in a declaration.
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005777 const ConstantArrayType *T =
5778 S.Context.getAsConstantArrayType(FExpr->getType());
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00005779 assert(T && "String literal not of constant array type!");
5780 size_t TypeSize = T->getSize().getZExtValue();
5781 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005782 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00005783
5784 // Emit a warning if the string literal is truncated and does not contain an
5785 // embedded null character.
5786 if (TypeSize <= StrRef.size() &&
5787 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
5788 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005789 S, inFunctionCall, Args[format_idx],
5790 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00005791 FExpr->getLocStart(),
5792 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
5793 return;
5794 }
5795
Ted Kremenekab278de2010-01-28 23:39:18 +00005796 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00005797 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005798 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005799 S, inFunctionCall, Args[format_idx],
5800 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00005801 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00005802 return;
5803 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005804
5805 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
5806 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSTrace) {
5807 CheckPrintfHandler H(S, FExpr, OrigFormatExpr, firstDataArg,
5808 numDataArgs, (Type == Sema::FST_NSString ||
5809 Type == Sema::FST_OSTrace),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005810 Str, HasVAListArg, Args, format_idx,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005811 inFunctionCall, CallType, CheckedVarArgs,
5812 UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005813
Hans Wennborg23926bd2011-12-15 10:25:47 +00005814 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005815 S.getLangOpts(),
5816 S.Context.getTargetInfo(),
5817 Type == Sema::FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00005818 H.DoneProcessing();
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005819 } else if (Type == Sema::FST_Scanf) {
5820 CheckScanfHandler H(S, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005821 Str, HasVAListArg, Args, format_idx,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005822 inFunctionCall, CallType, CheckedVarArgs,
5823 UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005824
Hans Wennborg23926bd2011-12-15 10:25:47 +00005825 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005826 S.getLangOpts(),
5827 S.Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00005828 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005829 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00005830}
5831
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00005832bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
5833 // Str - The format string. NOTE: this is NOT null-terminated!
5834 StringRef StrRef = FExpr->getString();
5835 const char *Str = StrRef.data();
5836 // Account for cases where the string literal is truncated in a declaration.
5837 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
5838 assert(T && "String literal not of constant array type!");
5839 size_t TypeSize = T->getSize().getZExtValue();
5840 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
5841 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
5842 getLangOpts(),
5843 Context.getTargetInfo());
5844}
5845
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005846//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
5847
5848// Returns the related absolute value function that is larger, of 0 if one
5849// does not exist.
5850static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
5851 switch (AbsFunction) {
5852 default:
5853 return 0;
5854
5855 case Builtin::BI__builtin_abs:
5856 return Builtin::BI__builtin_labs;
5857 case Builtin::BI__builtin_labs:
5858 return Builtin::BI__builtin_llabs;
5859 case Builtin::BI__builtin_llabs:
5860 return 0;
5861
5862 case Builtin::BI__builtin_fabsf:
5863 return Builtin::BI__builtin_fabs;
5864 case Builtin::BI__builtin_fabs:
5865 return Builtin::BI__builtin_fabsl;
5866 case Builtin::BI__builtin_fabsl:
5867 return 0;
5868
5869 case Builtin::BI__builtin_cabsf:
5870 return Builtin::BI__builtin_cabs;
5871 case Builtin::BI__builtin_cabs:
5872 return Builtin::BI__builtin_cabsl;
5873 case Builtin::BI__builtin_cabsl:
5874 return 0;
5875
5876 case Builtin::BIabs:
5877 return Builtin::BIlabs;
5878 case Builtin::BIlabs:
5879 return Builtin::BIllabs;
5880 case Builtin::BIllabs:
5881 return 0;
5882
5883 case Builtin::BIfabsf:
5884 return Builtin::BIfabs;
5885 case Builtin::BIfabs:
5886 return Builtin::BIfabsl;
5887 case Builtin::BIfabsl:
5888 return 0;
5889
5890 case Builtin::BIcabsf:
5891 return Builtin::BIcabs;
5892 case Builtin::BIcabs:
5893 return Builtin::BIcabsl;
5894 case Builtin::BIcabsl:
5895 return 0;
5896 }
5897}
5898
5899// Returns the argument type of the absolute value function.
5900static QualType getAbsoluteValueArgumentType(ASTContext &Context,
5901 unsigned AbsType) {
5902 if (AbsType == 0)
5903 return QualType();
5904
5905 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
5906 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
5907 if (Error != ASTContext::GE_None)
5908 return QualType();
5909
5910 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
5911 if (!FT)
5912 return QualType();
5913
5914 if (FT->getNumParams() != 1)
5915 return QualType();
5916
5917 return FT->getParamType(0);
5918}
5919
5920// Returns the best absolute value function, or zero, based on type and
5921// current absolute value function.
5922static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
5923 unsigned AbsFunctionKind) {
5924 unsigned BestKind = 0;
5925 uint64_t ArgSize = Context.getTypeSize(ArgType);
5926 for (unsigned Kind = AbsFunctionKind; Kind != 0;
5927 Kind = getLargerAbsoluteValueFunction(Kind)) {
5928 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
5929 if (Context.getTypeSize(ParamType) >= ArgSize) {
5930 if (BestKind == 0)
5931 BestKind = Kind;
5932 else if (Context.hasSameType(ParamType, ArgType)) {
5933 BestKind = Kind;
5934 break;
5935 }
5936 }
5937 }
5938 return BestKind;
5939}
5940
5941enum AbsoluteValueKind {
5942 AVK_Integer,
5943 AVK_Floating,
5944 AVK_Complex
5945};
5946
5947static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
5948 if (T->isIntegralOrEnumerationType())
5949 return AVK_Integer;
5950 if (T->isRealFloatingType())
5951 return AVK_Floating;
5952 if (T->isAnyComplexType())
5953 return AVK_Complex;
5954
5955 llvm_unreachable("Type not integer, floating, or complex");
5956}
5957
5958// Changes the absolute value function to a different type. Preserves whether
5959// the function is a builtin.
5960static unsigned changeAbsFunction(unsigned AbsKind,
5961 AbsoluteValueKind ValueKind) {
5962 switch (ValueKind) {
5963 case AVK_Integer:
5964 switch (AbsKind) {
5965 default:
5966 return 0;
5967 case Builtin::BI__builtin_fabsf:
5968 case Builtin::BI__builtin_fabs:
5969 case Builtin::BI__builtin_fabsl:
5970 case Builtin::BI__builtin_cabsf:
5971 case Builtin::BI__builtin_cabs:
5972 case Builtin::BI__builtin_cabsl:
5973 return Builtin::BI__builtin_abs;
5974 case Builtin::BIfabsf:
5975 case Builtin::BIfabs:
5976 case Builtin::BIfabsl:
5977 case Builtin::BIcabsf:
5978 case Builtin::BIcabs:
5979 case Builtin::BIcabsl:
5980 return Builtin::BIabs;
5981 }
5982 case AVK_Floating:
5983 switch (AbsKind) {
5984 default:
5985 return 0;
5986 case Builtin::BI__builtin_abs:
5987 case Builtin::BI__builtin_labs:
5988 case Builtin::BI__builtin_llabs:
5989 case Builtin::BI__builtin_cabsf:
5990 case Builtin::BI__builtin_cabs:
5991 case Builtin::BI__builtin_cabsl:
5992 return Builtin::BI__builtin_fabsf;
5993 case Builtin::BIabs:
5994 case Builtin::BIlabs:
5995 case Builtin::BIllabs:
5996 case Builtin::BIcabsf:
5997 case Builtin::BIcabs:
5998 case Builtin::BIcabsl:
5999 return Builtin::BIfabsf;
6000 }
6001 case AVK_Complex:
6002 switch (AbsKind) {
6003 default:
6004 return 0;
6005 case Builtin::BI__builtin_abs:
6006 case Builtin::BI__builtin_labs:
6007 case Builtin::BI__builtin_llabs:
6008 case Builtin::BI__builtin_fabsf:
6009 case Builtin::BI__builtin_fabs:
6010 case Builtin::BI__builtin_fabsl:
6011 return Builtin::BI__builtin_cabsf;
6012 case Builtin::BIabs:
6013 case Builtin::BIlabs:
6014 case Builtin::BIllabs:
6015 case Builtin::BIfabsf:
6016 case Builtin::BIfabs:
6017 case Builtin::BIfabsl:
6018 return Builtin::BIcabsf;
6019 }
6020 }
6021 llvm_unreachable("Unable to convert function");
6022}
6023
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00006024static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006025 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
6026 if (!FnInfo)
6027 return 0;
6028
6029 switch (FDecl->getBuiltinID()) {
6030 default:
6031 return 0;
6032 case Builtin::BI__builtin_abs:
6033 case Builtin::BI__builtin_fabs:
6034 case Builtin::BI__builtin_fabsf:
6035 case Builtin::BI__builtin_fabsl:
6036 case Builtin::BI__builtin_labs:
6037 case Builtin::BI__builtin_llabs:
6038 case Builtin::BI__builtin_cabs:
6039 case Builtin::BI__builtin_cabsf:
6040 case Builtin::BI__builtin_cabsl:
6041 case Builtin::BIabs:
6042 case Builtin::BIlabs:
6043 case Builtin::BIllabs:
6044 case Builtin::BIfabs:
6045 case Builtin::BIfabsf:
6046 case Builtin::BIfabsl:
6047 case Builtin::BIcabs:
6048 case Builtin::BIcabsf:
6049 case Builtin::BIcabsl:
6050 return FDecl->getBuiltinID();
6051 }
6052 llvm_unreachable("Unknown Builtin type");
6053}
6054
6055// If the replacement is valid, emit a note with replacement function.
6056// Additionally, suggest including the proper header if not already included.
6057static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00006058 unsigned AbsKind, QualType ArgType) {
6059 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00006060 const char *HeaderName = nullptr;
6061 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00006062 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
6063 FunctionName = "std::abs";
6064 if (ArgType->isIntegralOrEnumerationType()) {
6065 HeaderName = "cstdlib";
6066 } else if (ArgType->isRealFloatingType()) {
6067 HeaderName = "cmath";
6068 } else {
6069 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006070 }
Richard Trieubeffb832014-04-15 23:47:53 +00006071
6072 // Lookup all std::abs
6073 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00006074 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00006075 R.suppressDiagnostics();
6076 S.LookupQualifiedName(R, Std);
6077
6078 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006079 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00006080 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
6081 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
6082 } else {
6083 FDecl = dyn_cast<FunctionDecl>(I);
6084 }
6085 if (!FDecl)
6086 continue;
6087
6088 // Found std::abs(), check that they are the right ones.
6089 if (FDecl->getNumParams() != 1)
6090 continue;
6091
6092 // Check that the parameter type can handle the argument.
6093 QualType ParamType = FDecl->getParamDecl(0)->getType();
6094 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
6095 S.Context.getTypeSize(ArgType) <=
6096 S.Context.getTypeSize(ParamType)) {
6097 // Found a function, don't need the header hint.
6098 EmitHeaderHint = false;
6099 break;
6100 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006101 }
Richard Trieubeffb832014-04-15 23:47:53 +00006102 }
6103 } else {
Eric Christopher02d5d862015-08-06 01:01:12 +00006104 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
Richard Trieubeffb832014-04-15 23:47:53 +00006105 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
6106
6107 if (HeaderName) {
6108 DeclarationName DN(&S.Context.Idents.get(FunctionName));
6109 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
6110 R.suppressDiagnostics();
6111 S.LookupName(R, S.getCurScope());
6112
6113 if (R.isSingleResult()) {
6114 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
6115 if (FD && FD->getBuiltinID() == AbsKind) {
6116 EmitHeaderHint = false;
6117 } else {
6118 return;
6119 }
6120 } else if (!R.empty()) {
6121 return;
6122 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006123 }
6124 }
6125
6126 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00006127 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006128
Richard Trieubeffb832014-04-15 23:47:53 +00006129 if (!HeaderName)
6130 return;
6131
6132 if (!EmitHeaderHint)
6133 return;
6134
Alp Toker5d96e0a2014-07-11 20:53:51 +00006135 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
6136 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00006137}
6138
6139static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
6140 if (!FDecl)
6141 return false;
6142
6143 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
6144 return false;
6145
6146 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
6147
6148 while (ND && ND->isInlineNamespace()) {
6149 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006150 }
Richard Trieubeffb832014-04-15 23:47:53 +00006151
6152 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
6153 return false;
6154
6155 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
6156 return false;
6157
6158 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006159}
6160
6161// Warn when using the wrong abs() function.
6162void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
6163 const FunctionDecl *FDecl,
6164 IdentifierInfo *FnInfo) {
6165 if (Call->getNumArgs() != 1)
6166 return;
6167
6168 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieubeffb832014-04-15 23:47:53 +00006169 bool IsStdAbs = IsFunctionStdAbs(FDecl);
6170 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006171 return;
6172
6173 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
6174 QualType ParamType = Call->getArg(0)->getType();
6175
Alp Toker5d96e0a2014-07-11 20:53:51 +00006176 // Unsigned types cannot be negative. Suggest removing the absolute value
6177 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006178 if (ArgType->isUnsignedIntegerType()) {
Richard Trieubeffb832014-04-15 23:47:53 +00006179 const char *FunctionName =
Eric Christopher02d5d862015-08-06 01:01:12 +00006180 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006181 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
6182 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00006183 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006184 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
6185 return;
6186 }
6187
David Majnemer7f77eb92015-11-15 03:04:34 +00006188 // Taking the absolute value of a pointer is very suspicious, they probably
6189 // wanted to index into an array, dereference a pointer, call a function, etc.
6190 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
6191 unsigned DiagType = 0;
6192 if (ArgType->isFunctionType())
6193 DiagType = 1;
6194 else if (ArgType->isArrayType())
6195 DiagType = 2;
6196
6197 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
6198 return;
6199 }
6200
Richard Trieubeffb832014-04-15 23:47:53 +00006201 // std::abs has overloads which prevent most of the absolute value problems
6202 // from occurring.
6203 if (IsStdAbs)
6204 return;
6205
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006206 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
6207 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
6208
6209 // The argument and parameter are the same kind. Check if they are the right
6210 // size.
6211 if (ArgValueKind == ParamValueKind) {
6212 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
6213 return;
6214
6215 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
6216 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
6217 << FDecl << ArgType << ParamType;
6218
6219 if (NewAbsKind == 0)
6220 return;
6221
6222 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00006223 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006224 return;
6225 }
6226
6227 // ArgValueKind != ParamValueKind
6228 // The wrong type of absolute value function was used. Attempt to find the
6229 // proper one.
6230 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
6231 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
6232 if (NewAbsKind == 0)
6233 return;
6234
6235 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
6236 << FDecl << ParamValueKind << ArgValueKind;
6237
6238 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00006239 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006240}
6241
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006242//===--- CHECK: Standard memory functions ---------------------------------===//
6243
Nico Weber0e6daef2013-12-26 23:38:39 +00006244/// \brief Takes the expression passed to the size_t parameter of functions
6245/// such as memcmp, strncat, etc and warns if it's a comparison.
6246///
6247/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
6248static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
6249 IdentifierInfo *FnName,
6250 SourceLocation FnLoc,
6251 SourceLocation RParenLoc) {
6252 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
6253 if (!Size)
6254 return false;
6255
6256 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
6257 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
6258 return false;
6259
Nico Weber0e6daef2013-12-26 23:38:39 +00006260 SourceRange SizeRange = Size->getSourceRange();
6261 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
6262 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00006263 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00006264 << FnName << FixItHint::CreateInsertion(
6265 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00006266 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00006267 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00006268 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00006269 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
6270 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00006271
6272 return true;
6273}
6274
Reid Kleckner5fb5b122014-06-27 23:58:21 +00006275/// \brief Determine whether the given type is or contains a dynamic class type
6276/// (e.g., whether it has a vtable).
6277static const CXXRecordDecl *getContainedDynamicClass(QualType T,
6278 bool &IsContained) {
6279 // Look through array types while ignoring qualifiers.
6280 const Type *Ty = T->getBaseElementTypeUnsafe();
6281 IsContained = false;
6282
6283 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
6284 RD = RD ? RD->getDefinition() : nullptr;
Richard Trieu1c7237a2016-03-31 04:18:07 +00006285 if (!RD || RD->isInvalidDecl())
Reid Kleckner5fb5b122014-06-27 23:58:21 +00006286 return nullptr;
6287
6288 if (RD->isDynamicClass())
6289 return RD;
6290
6291 // Check all the fields. If any bases were dynamic, the class is dynamic.
6292 // It's impossible for a class to transitively contain itself by value, so
6293 // infinite recursion is impossible.
6294 for (auto *FD : RD->fields()) {
6295 bool SubContained;
6296 if (const CXXRecordDecl *ContainedRD =
6297 getContainedDynamicClass(FD->getType(), SubContained)) {
6298 IsContained = true;
6299 return ContainedRD;
6300 }
6301 }
6302
6303 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00006304}
6305
Chandler Carruth889ed862011-06-21 23:04:20 +00006306/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006307/// otherwise returns NULL.
Nico Weberc44b35e2015-03-21 17:37:46 +00006308static const Expr *getSizeOfExprArg(const Expr *E) {
Nico Weberc5e73862011-06-14 16:14:58 +00006309 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006310 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
6311 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
6312 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00006313
Craig Topperc3ec1492014-05-26 06:22:03 +00006314 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006315}
6316
Chandler Carruth889ed862011-06-21 23:04:20 +00006317/// \brief If E is a sizeof expression, returns its argument type.
Nico Weberc44b35e2015-03-21 17:37:46 +00006318static QualType getSizeOfArgType(const Expr *E) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006319 if (const UnaryExprOrTypeTraitExpr *SizeOf =
6320 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
6321 if (SizeOf->getKind() == clang::UETT_SizeOf)
6322 return SizeOf->getTypeOfArgument();
6323
6324 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00006325}
6326
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006327/// \brief Check for dangerous or invalid arguments to memset().
6328///
Chandler Carruthac687262011-06-03 06:23:57 +00006329/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00006330/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
6331/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006332///
6333/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00006334void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00006335 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00006336 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00006337 assert(BId != 0);
6338
Ted Kremenekb5fabb22011-04-28 01:38:02 +00006339 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00006340 // we have enough arguments, and if not, abort further checking.
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00006341 unsigned ExpectedNumArgs =
6342 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00006343 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00006344 return;
6345
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00006346 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
Anna Zaks22122702012-01-17 00:37:07 +00006347 BId == Builtin::BIstrndup ? 1 : 2);
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00006348 unsigned LenArg =
6349 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00006350 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006351
Nico Weber0e6daef2013-12-26 23:38:39 +00006352 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
6353 Call->getLocStart(), Call->getRParenLoc()))
6354 return;
6355
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006356 // We have special checking when the length is a sizeof expression.
6357 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
6358 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
6359 llvm::FoldingSetNodeID SizeOfArgID;
6360
Bruno Cardoso Lopesc73e4c32016-08-11 18:33:15 +00006361 // Although widely used, 'bzero' is not a standard function. Be more strict
6362 // with the argument types before allowing diagnostics and only allow the
6363 // form bzero(ptr, sizeof(...)).
6364 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
6365 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
6366 return;
6367
Douglas Gregor3bb2a812011-05-03 20:37:33 +00006368 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
6369 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00006370 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006371
Douglas Gregor3bb2a812011-05-03 20:37:33 +00006372 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00006373 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00006374 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00006375 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00006376
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006377 // Never warn about void type pointers. This can be used to suppress
6378 // false positives.
6379 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00006380 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006381
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006382 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
6383 // actually comparing the expressions for equality. Because computing the
6384 // expression IDs can be expensive, we only do this if the diagnostic is
6385 // enabled.
6386 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00006387 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
6388 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006389 // We only compute IDs for expressions if the warning is enabled, and
6390 // cache the sizeof arg's ID.
6391 if (SizeOfArgID == llvm::FoldingSetNodeID())
6392 SizeOfArg->Profile(SizeOfArgID, Context, true);
6393 llvm::FoldingSetNodeID DestID;
6394 Dest->Profile(DestID, Context, true);
6395 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00006396 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
6397 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006398 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00006399 StringRef ReadableName = FnName->getName();
6400
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006401 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00006402 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006403 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00006404 if (!PointeeTy->isIncompleteType() &&
6405 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006406 ActionIdx = 2; // If the pointee's size is sizeof(char),
6407 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00006408
6409 // If the function is defined as a builtin macro, do not show macro
6410 // expansion.
6411 SourceLocation SL = SizeOfArg->getExprLoc();
6412 SourceRange DSR = Dest->getSourceRange();
6413 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00006414 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00006415
6416 if (SM.isMacroArgExpansion(SL)) {
6417 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
6418 SL = SM.getSpellingLoc(SL);
6419 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
6420 SM.getSpellingLoc(DSR.getEnd()));
6421 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
6422 SM.getSpellingLoc(SSR.getEnd()));
6423 }
6424
Anna Zaksd08d9152012-05-30 23:14:52 +00006425 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006426 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00006427 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00006428 << PointeeTy
6429 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00006430 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00006431 << SSR);
6432 DiagRuntimeBehavior(SL, SizeOfArg,
6433 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
6434 << ActionIdx
6435 << SSR);
6436
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006437 break;
6438 }
6439 }
6440
6441 // Also check for cases where the sizeof argument is the exact same
6442 // type as the memory argument, and where it points to a user-defined
6443 // record type.
6444 if (SizeOfArgTy != QualType()) {
6445 if (PointeeTy->isRecordType() &&
6446 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
6447 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
6448 PDiag(diag::warn_sizeof_pointer_type_memaccess)
6449 << FnName << SizeOfArgTy << ArgIdx
6450 << PointeeTy << Dest->getSourceRange()
6451 << LenExpr->getSourceRange());
6452 break;
6453 }
Nico Weberc5e73862011-06-14 16:14:58 +00006454 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00006455 } else if (DestTy->isArrayType()) {
6456 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00006457 }
Nico Weberc5e73862011-06-14 16:14:58 +00006458
Nico Weberc44b35e2015-03-21 17:37:46 +00006459 if (PointeeTy == QualType())
6460 continue;
Anna Zaks22122702012-01-17 00:37:07 +00006461
Nico Weberc44b35e2015-03-21 17:37:46 +00006462 // Always complain about dynamic classes.
6463 bool IsContained;
6464 if (const CXXRecordDecl *ContainedRD =
6465 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00006466
Nico Weberc44b35e2015-03-21 17:37:46 +00006467 unsigned OperationType = 0;
6468 // "overwritten" if we're warning about the destination for any call
6469 // but memcmp; otherwise a verb appropriate to the call.
6470 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
6471 if (BId == Builtin::BImemcpy)
6472 OperationType = 1;
6473 else if(BId == Builtin::BImemmove)
6474 OperationType = 2;
6475 else if (BId == Builtin::BImemcmp)
6476 OperationType = 3;
6477 }
6478
John McCall31168b02011-06-15 23:02:42 +00006479 DiagRuntimeBehavior(
6480 Dest->getExprLoc(), Dest,
Nico Weberc44b35e2015-03-21 17:37:46 +00006481 PDiag(diag::warn_dyn_class_memaccess)
6482 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
6483 << FnName << IsContained << ContainedRD << OperationType
6484 << Call->getCallee()->getSourceRange());
6485 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
6486 BId != Builtin::BImemset)
6487 DiagRuntimeBehavior(
6488 Dest->getExprLoc(), Dest,
6489 PDiag(diag::warn_arc_object_memaccess)
6490 << ArgIdx << FnName << PointeeTy
6491 << Call->getCallee()->getSourceRange());
6492 else
6493 continue;
6494
6495 DiagRuntimeBehavior(
6496 Dest->getExprLoc(), Dest,
6497 PDiag(diag::note_bad_memaccess_silence)
6498 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
6499 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006500 }
6501}
6502
Ted Kremenek6865f772011-08-18 20:55:45 +00006503// A little helper routine: ignore addition and subtraction of integer literals.
6504// This intentionally does not ignore all integer constant expressions because
6505// we don't want to remove sizeof().
6506static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
6507 Ex = Ex->IgnoreParenCasts();
6508
6509 for (;;) {
6510 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
6511 if (!BO || !BO->isAdditiveOp())
6512 break;
6513
6514 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
6515 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
6516
6517 if (isa<IntegerLiteral>(RHS))
6518 Ex = LHS;
6519 else if (isa<IntegerLiteral>(LHS))
6520 Ex = RHS;
6521 else
6522 break;
6523 }
6524
6525 return Ex;
6526}
6527
Anna Zaks13b08572012-08-08 21:42:23 +00006528static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
6529 ASTContext &Context) {
6530 // Only handle constant-sized or VLAs, but not flexible members.
6531 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
6532 // Only issue the FIXIT for arrays of size > 1.
6533 if (CAT->getSize().getSExtValue() <= 1)
6534 return false;
6535 } else if (!Ty->isVariableArrayType()) {
6536 return false;
6537 }
6538 return true;
6539}
6540
Ted Kremenek6865f772011-08-18 20:55:45 +00006541// Warn if the user has made the 'size' argument to strlcpy or strlcat
6542// be the size of the source, instead of the destination.
6543void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
6544 IdentifierInfo *FnName) {
6545
6546 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00006547 unsigned NumArgs = Call->getNumArgs();
6548 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00006549 return;
6550
6551 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
6552 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00006553 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00006554
6555 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
6556 Call->getLocStart(), Call->getRParenLoc()))
6557 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00006558
6559 // Look for 'strlcpy(dst, x, sizeof(x))'
6560 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
6561 CompareWithSrc = Ex;
6562 else {
6563 // Look for 'strlcpy(dst, x, strlen(x))'
6564 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00006565 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
6566 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00006567 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
6568 }
6569 }
6570
6571 if (!CompareWithSrc)
6572 return;
6573
6574 // Determine if the argument to sizeof/strlen is equal to the source
6575 // argument. In principle there's all kinds of things you could do
6576 // here, for instance creating an == expression and evaluating it with
6577 // EvaluateAsBooleanCondition, but this uses a more direct technique:
6578 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
6579 if (!SrcArgDRE)
6580 return;
6581
6582 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
6583 if (!CompareWithSrcDRE ||
6584 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
6585 return;
6586
6587 const Expr *OriginalSizeArg = Call->getArg(2);
6588 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
6589 << OriginalSizeArg->getSourceRange() << FnName;
6590
6591 // Output a FIXIT hint if the destination is an array (rather than a
6592 // pointer to an array). This could be enhanced to handle some
6593 // pointers if we know the actual size, like if DstArg is 'array+2'
6594 // we could say 'sizeof(array)-2'.
6595 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00006596 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00006597 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00006598
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00006599 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00006600 llvm::raw_svector_ostream OS(sizeString);
6601 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00006602 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00006603 OS << ")";
6604
6605 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
6606 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
6607 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00006608}
6609
Anna Zaks314cd092012-02-01 19:08:57 +00006610/// Check if two expressions refer to the same declaration.
6611static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
6612 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
6613 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
6614 return D1->getDecl() == D2->getDecl();
6615 return false;
6616}
6617
6618static const Expr *getStrlenExprArg(const Expr *E) {
6619 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
6620 const FunctionDecl *FD = CE->getDirectCallee();
6621 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00006622 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00006623 return CE->getArg(0)->IgnoreParenCasts();
6624 }
Craig Topperc3ec1492014-05-26 06:22:03 +00006625 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00006626}
6627
6628// Warn on anti-patterns as the 'size' argument to strncat.
6629// The correct size argument should look like following:
6630// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
6631void Sema::CheckStrncatArguments(const CallExpr *CE,
6632 IdentifierInfo *FnName) {
6633 // Don't crash if the user has the wrong number of arguments.
6634 if (CE->getNumArgs() < 3)
6635 return;
6636 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
6637 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
6638 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
6639
Nico Weber0e6daef2013-12-26 23:38:39 +00006640 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
6641 CE->getRParenLoc()))
6642 return;
6643
Anna Zaks314cd092012-02-01 19:08:57 +00006644 // Identify common expressions, which are wrongly used as the size argument
6645 // to strncat and may lead to buffer overflows.
6646 unsigned PatternType = 0;
6647 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
6648 // - sizeof(dst)
6649 if (referToTheSameDecl(SizeOfArg, DstArg))
6650 PatternType = 1;
6651 // - sizeof(src)
6652 else if (referToTheSameDecl(SizeOfArg, SrcArg))
6653 PatternType = 2;
6654 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
6655 if (BE->getOpcode() == BO_Sub) {
6656 const Expr *L = BE->getLHS()->IgnoreParenCasts();
6657 const Expr *R = BE->getRHS()->IgnoreParenCasts();
6658 // - sizeof(dst) - strlen(dst)
6659 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
6660 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
6661 PatternType = 1;
6662 // - sizeof(src) - (anything)
6663 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
6664 PatternType = 2;
6665 }
6666 }
6667
6668 if (PatternType == 0)
6669 return;
6670
Anna Zaks5069aa32012-02-03 01:27:37 +00006671 // Generate the diagnostic.
6672 SourceLocation SL = LenArg->getLocStart();
6673 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00006674 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00006675
6676 // If the function is defined as a builtin macro, do not show macro expansion.
6677 if (SM.isMacroArgExpansion(SL)) {
6678 SL = SM.getSpellingLoc(SL);
6679 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
6680 SM.getSpellingLoc(SR.getEnd()));
6681 }
6682
Anna Zaks13b08572012-08-08 21:42:23 +00006683 // Check if the destination is an array (rather than a pointer to an array).
6684 QualType DstTy = DstArg->getType();
6685 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
6686 Context);
6687 if (!isKnownSizeArray) {
6688 if (PatternType == 1)
6689 Diag(SL, diag::warn_strncat_wrong_size) << SR;
6690 else
6691 Diag(SL, diag::warn_strncat_src_size) << SR;
6692 return;
6693 }
6694
Anna Zaks314cd092012-02-01 19:08:57 +00006695 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00006696 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00006697 else
Anna Zaks5069aa32012-02-03 01:27:37 +00006698 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00006699
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00006700 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00006701 llvm::raw_svector_ostream OS(sizeString);
6702 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00006703 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00006704 OS << ") - ";
6705 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00006706 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00006707 OS << ") - 1";
6708
Anna Zaks5069aa32012-02-03 01:27:37 +00006709 Diag(SL, diag::note_strncat_wrong_size)
6710 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00006711}
6712
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006713//===--- CHECK: Return Address of Stack Variable --------------------------===//
6714
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006715static const Expr *EvalVal(const Expr *E,
6716 SmallVectorImpl<const DeclRefExpr *> &refVars,
6717 const Decl *ParentDecl);
6718static const Expr *EvalAddr(const Expr *E,
6719 SmallVectorImpl<const DeclRefExpr *> &refVars,
6720 const Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006721
6722/// CheckReturnStackAddr - Check if a return statement returns the address
6723/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006724static void
6725CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
6726 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00006727
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006728 const Expr *stackE = nullptr;
6729 SmallVector<const DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006730
6731 // Perform checking for returned stack addresses, local blocks,
6732 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00006733 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006734 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006735 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00006736 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006737 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006738 }
6739
Craig Topperc3ec1492014-05-26 06:22:03 +00006740 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006741 return; // Nothing suspicious was found.
6742
Richard Trieu81b6c562016-08-05 23:24:47 +00006743 // Parameters are initalized in the calling scope, so taking the address
6744 // of a parameter reference doesn't need a warning.
6745 for (auto *DRE : refVars)
6746 if (isa<ParmVarDecl>(DRE->getDecl()))
6747 return;
6748
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006749 SourceLocation diagLoc;
6750 SourceRange diagRange;
6751 if (refVars.empty()) {
6752 diagLoc = stackE->getLocStart();
6753 diagRange = stackE->getSourceRange();
6754 } else {
6755 // We followed through a reference variable. 'stackE' contains the
6756 // problematic expression but we will warn at the return statement pointing
6757 // at the reference variable. We will later display the "trail" of
6758 // reference variables using notes.
6759 diagLoc = refVars[0]->getLocStart();
6760 diagRange = refVars[0]->getSourceRange();
6761 }
6762
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006763 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
6764 // address of local var
Craig Topperda7b27f2015-11-17 05:40:09 +00006765 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006766 << DR->getDecl()->getDeclName() << diagRange;
6767 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006768 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006769 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006770 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006771 } else { // local temporary.
Richard Trieu81b6c562016-08-05 23:24:47 +00006772 // If there is an LValue->RValue conversion, then the value of the
6773 // reference type is used, not the reference.
6774 if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
6775 if (ICE->getCastKind() == CK_LValueToRValue) {
6776 return;
6777 }
6778 }
Craig Topperda7b27f2015-11-17 05:40:09 +00006779 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
6780 << lhsType->isReferenceType() << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006781 }
6782
6783 // Display the "trail" of reference variables that we followed until we
6784 // found the problematic expression using notes.
6785 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006786 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006787 // If this var binds to another reference var, show the range of the next
6788 // var, otherwise the var binds to the problematic expression, in which case
6789 // show the range of the expression.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006790 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
6791 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006792 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
6793 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006794 }
6795}
6796
6797/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
6798/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006799/// to a location on the stack, a local block, an address of a label, or a
6800/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006801/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006802/// encounter a subexpression that (1) clearly does not lead to one of the
6803/// above problematic expressions (2) is something we cannot determine leads to
6804/// a problematic expression based on such local checking.
6805///
6806/// Both EvalAddr and EvalVal follow through reference variables to evaluate
6807/// the expression that they point to. Such variables are added to the
6808/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006809///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00006810/// EvalAddr processes expressions that are pointers that are used as
6811/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006812/// At the base case of the recursion is a check for the above problematic
6813/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006814///
6815/// This implementation handles:
6816///
6817/// * pointer-to-pointer casts
6818/// * implicit conversions from array references to pointers
6819/// * taking the address of fields
6820/// * arbitrary interplay between "&" and "*" operators
6821/// * pointer arithmetic from an address of a stack variable
6822/// * taking the address of an array element where the array is on the stack
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006823static const Expr *EvalAddr(const Expr *E,
6824 SmallVectorImpl<const DeclRefExpr *> &refVars,
6825 const Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006826 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00006827 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006828
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006829 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00006830 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00006831 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006832 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00006833 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00006834
Peter Collingbourne91147592011-04-15 00:35:48 +00006835 E = E->IgnoreParens();
6836
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006837 // Our "symbolic interpreter" is just a dispatch off the currently
6838 // viewed AST node. We then recursively traverse the AST by calling
6839 // EvalAddr and EvalVal appropriately.
6840 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006841 case Stmt::DeclRefExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006842 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006843
Richard Smith40f08eb2014-01-30 22:05:38 +00006844 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00006845 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00006846 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00006847
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006848 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006849 // If this is a reference variable, follow through to the expression that
6850 // it points to.
6851 if (V->hasLocalStorage() &&
6852 V->getType()->isReferenceType() && V->hasInit()) {
6853 // Add the reference variable to the "trail".
6854 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006855 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006856 }
6857
Craig Topperc3ec1492014-05-26 06:22:03 +00006858 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006859 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006860
Chris Lattner934edb22007-12-28 05:31:15 +00006861 case Stmt::UnaryOperatorClass: {
6862 // The only unary operator that make sense to handle here
6863 // is AddrOf. All others don't make sense as pointers.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006864 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00006865
John McCalle3027922010-08-25 11:45:40 +00006866 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006867 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006868 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006869 }
Mike Stump11289f42009-09-09 15:08:12 +00006870
Chris Lattner934edb22007-12-28 05:31:15 +00006871 case Stmt::BinaryOperatorClass: {
6872 // Handle pointer arithmetic. All other binary operators are not valid
6873 // in this context.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006874 const BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00006875 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00006876
John McCalle3027922010-08-25 11:45:40 +00006877 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00006878 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00006879
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006880 const Expr *Base = B->getLHS();
Chris Lattner934edb22007-12-28 05:31:15 +00006881
6882 // Determine which argument is the real pointer base. It could be
6883 // the RHS argument instead of the LHS.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006884 if (!Base->getType()->isPointerType())
6885 Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00006886
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006887 assert(Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006888 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00006889 }
Steve Naroff2752a172008-09-10 19:17:48 +00006890
Chris Lattner934edb22007-12-28 05:31:15 +00006891 // For conditional operators we need to see if either the LHS or RHS are
6892 // valid DeclRefExpr*s. If one of them is valid, we return it.
6893 case Stmt::ConditionalOperatorClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006894 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00006895
Chris Lattner934edb22007-12-28 05:31:15 +00006896 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006897 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006898 if (const Expr *LHSExpr = C->getLHS()) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006899 // In C++, we can have a throw-expression, which has 'void' type.
6900 if (!LHSExpr->getType()->isVoidType())
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006901 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00006902 return LHS;
6903 }
Chris Lattner934edb22007-12-28 05:31:15 +00006904
Douglas Gregor270b2ef2010-10-21 16:21:08 +00006905 // In C++, we can have a throw-expression, which has 'void' type.
6906 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00006907 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00006908
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006909 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00006910 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006911
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006912 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00006913 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006914 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00006915 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006916
6917 case Stmt::AddrLabelExprClass:
6918 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00006919
John McCall28fc7092011-11-10 05:35:25 +00006920 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006921 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
6922 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00006923
Ted Kremenekc3b4c522008-08-07 00:49:01 +00006924 // For casts, we need to handle conversions from arrays to
6925 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00006926 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00006927 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00006928 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00006929 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00006930 case Stmt::CXXStaticCastExprClass:
6931 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00006932 case Stmt::CXXConstCastExprClass:
6933 case Stmt::CXXReinterpretCastExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006934 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Eli Friedman8195ad72012-02-23 23:04:32 +00006935 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00006936 case CK_LValueToRValue:
6937 case CK_NoOp:
6938 case CK_BaseToDerived:
6939 case CK_DerivedToBase:
6940 case CK_UncheckedDerivedToBase:
6941 case CK_Dynamic:
6942 case CK_CPointerToObjCPointerCast:
6943 case CK_BlockPointerToObjCPointerCast:
6944 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006945 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00006946
6947 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006948 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00006949
Richard Trieudadefde2014-07-02 04:39:38 +00006950 case CK_BitCast:
6951 if (SubExpr->getType()->isAnyPointerType() ||
6952 SubExpr->getType()->isBlockPointerType() ||
6953 SubExpr->getType()->isObjCQualifiedIdType())
6954 return EvalAddr(SubExpr, refVars, ParentDecl);
6955 else
6956 return nullptr;
6957
Eli Friedman8195ad72012-02-23 23:04:32 +00006958 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00006959 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00006960 }
Chris Lattner934edb22007-12-28 05:31:15 +00006961 }
Mike Stump11289f42009-09-09 15:08:12 +00006962
Douglas Gregorfe314812011-06-21 17:03:29 +00006963 case Stmt::MaterializeTemporaryExprClass:
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006964 if (const Expr *Result =
6965 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
6966 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00006967 return Result;
Douglas Gregorfe314812011-06-21 17:03:29 +00006968 return E;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006969
Chris Lattner934edb22007-12-28 05:31:15 +00006970 // Everything else: we simply don't reason about them.
6971 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00006972 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00006973 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006974}
Mike Stump11289f42009-09-09 15:08:12 +00006975
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006976/// EvalVal - This function is complements EvalAddr in the mutual recursion.
6977/// See the comments for EvalAddr for more details.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006978static const Expr *EvalVal(const Expr *E,
6979 SmallVectorImpl<const DeclRefExpr *> &refVars,
6980 const Decl *ParentDecl) {
6981 do {
6982 // We should only be called for evaluating non-pointer expressions, or
6983 // expressions with a pointer type that are not used as references but
6984 // instead
6985 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00006986
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006987 // Our "symbolic interpreter" is just a dispatch off the currently
6988 // viewed AST node. We then recursively traverse the AST by calling
6989 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00006990
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006991 E = E->IgnoreParens();
6992 switch (E->getStmtClass()) {
6993 case Stmt::ImplicitCastExprClass: {
6994 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
6995 if (IE->getValueKind() == VK_LValue) {
6996 E = IE->getSubExpr();
6997 continue;
6998 }
Craig Topperc3ec1492014-05-26 06:22:03 +00006999 return nullptr;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007000 }
Richard Smith40f08eb2014-01-30 22:05:38 +00007001
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007002 case Stmt::ExprWithCleanupsClass:
7003 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7004 ParentDecl);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007005
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007006 case Stmt::DeclRefExprClass: {
7007 // When we hit a DeclRefExpr we are looking at code that refers to a
7008 // variable's name. If it's not a reference variable we check if it has
7009 // local storage within the function, and if so, return the expression.
7010 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7011
7012 // If we leave the immediate function, the lifetime isn't about to end.
7013 if (DR->refersToEnclosingVariableOrCapture())
7014 return nullptr;
7015
7016 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
7017 // Check if it refers to itself, e.g. "int& i = i;".
7018 if (V == ParentDecl)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007019 return DR;
7020
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007021 if (V->hasLocalStorage()) {
7022 if (!V->getType()->isReferenceType())
7023 return DR;
7024
7025 // Reference variable, follow through to the expression that
7026 // it points to.
7027 if (V->hasInit()) {
7028 // Add the reference variable to the "trail".
7029 refVars.push_back(DR);
7030 return EvalVal(V->getInit(), refVars, V);
7031 }
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007032 }
7033 }
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007034
7035 return nullptr;
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007036 }
Mike Stump11289f42009-09-09 15:08:12 +00007037
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007038 case Stmt::UnaryOperatorClass: {
7039 // The only unary operator that make sense to handle here
7040 // is Deref. All others don't resolve to a "name." This includes
7041 // handling all sorts of rvalues passed to a unary operator.
7042 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007043
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007044 if (U->getOpcode() == UO_Deref)
7045 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Mike Stump11289f42009-09-09 15:08:12 +00007046
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007047 return nullptr;
7048 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007049
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007050 case Stmt::ArraySubscriptExprClass: {
7051 // Array subscripts are potential references to data on the stack. We
7052 // retrieve the DeclRefExpr* for the array variable if it indeed
7053 // has local storage.
Saleem Abdulrasoolcfd45532016-02-15 01:51:24 +00007054 const auto *ASE = cast<ArraySubscriptExpr>(E);
7055 if (ASE->isTypeDependent())
7056 return nullptr;
7057 return EvalAddr(ASE->getBase(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007058 }
Mike Stump11289f42009-09-09 15:08:12 +00007059
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007060 case Stmt::OMPArraySectionExprClass: {
7061 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
7062 ParentDecl);
7063 }
Mike Stump11289f42009-09-09 15:08:12 +00007064
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007065 case Stmt::ConditionalOperatorClass: {
7066 // For conditional operators we need to see if either the LHS or RHS are
7067 // non-NULL Expr's. If one is non-NULL, we return it.
7068 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Alexey Bataev1a3320e2015-08-25 14:24:04 +00007069
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007070 // Handle the GNU extension for missing LHS.
7071 if (const Expr *LHSExpr = C->getLHS()) {
7072 // In C++, we can have a throw-expression, which has 'void' type.
7073 if (!LHSExpr->getType()->isVoidType())
7074 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
7075 return LHS;
7076 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007077
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007078 // In C++, we can have a throw-expression, which has 'void' type.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007079 if (C->getRHS()->getType()->isVoidType())
7080 return nullptr;
7081
7082 return EvalVal(C->getRHS(), refVars, ParentDecl);
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007083 }
7084
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007085 // Accesses to members are potential references to data on the stack.
7086 case Stmt::MemberExprClass: {
7087 const MemberExpr *M = cast<MemberExpr>(E);
Anders Carlsson801c5c72007-11-30 19:04:31 +00007088
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007089 // Check for indirect access. We only want direct field accesses.
7090 if (M->isArrow())
7091 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00007092
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007093 // Check whether the member type is itself a reference, in which case
7094 // we're not going to refer to the member, but to what the member refers
7095 // to.
7096 if (M->getMemberDecl()->getType()->isReferenceType())
7097 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00007098
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007099 return EvalVal(M->getBase(), refVars, ParentDecl);
7100 }
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00007101
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007102 case Stmt::MaterializeTemporaryExprClass:
7103 if (const Expr *Result =
7104 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7105 refVars, ParentDecl))
7106 return Result;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007107 return E;
7108
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007109 default:
7110 // Check that we don't return or take the address of a reference to a
7111 // temporary. This is only useful in C++.
7112 if (!E->isTypeDependent() && E->isRValue())
7113 return E;
7114
7115 // Everything else: we simply don't reason about them.
7116 return nullptr;
7117 }
7118 } while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007119}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007120
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007121void
7122Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
7123 SourceLocation ReturnLoc,
7124 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00007125 const AttrVec *Attrs,
7126 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007127 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
7128
7129 // Check if the return value is null but should not be.
Douglas Gregorb4866e82015-06-19 18:13:19 +00007130 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
7131 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
Benjamin Kramerae852a62014-02-23 14:34:50 +00007132 CheckNonNullExpr(*this, RetValExp))
7133 Diag(ReturnLoc, diag::warn_null_ret)
7134 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00007135
7136 // C++11 [basic.stc.dynamic.allocation]p4:
7137 // If an allocation function declared with a non-throwing
7138 // exception-specification fails to allocate storage, it shall return
7139 // a null pointer. Any other allocation function that fails to allocate
7140 // storage shall indicate failure only by throwing an exception [...]
7141 if (FD) {
7142 OverloadedOperatorKind Op = FD->getOverloadedOperator();
7143 if (Op == OO_New || Op == OO_Array_New) {
7144 const FunctionProtoType *Proto
7145 = FD->getType()->castAs<FunctionProtoType>();
7146 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
7147 CheckNonNullExpr(*this, RetValExp))
7148 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
7149 << FD << getLangOpts().CPlusPlus11;
7150 }
7151 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007152}
7153
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007154//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
7155
7156/// Check for comparisons of floating point operands using != and ==.
7157/// Issue a warning if these are no self-comparisons, as they are not likely
7158/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00007159void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00007160 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
7161 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007162
7163 // Special case: check for x == x (which is OK).
7164 // Do not emit warnings for such cases.
7165 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
7166 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
7167 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00007168 return;
Mike Stump11289f42009-09-09 15:08:12 +00007169
Ted Kremenekeda40e22007-11-29 00:59:04 +00007170 // Special case: check for comparisons against literals that can be exactly
7171 // represented by APFloat. In such cases, do not emit a warning. This
7172 // is a heuristic: often comparison against such literals are used to
7173 // detect if a value in a variable has not changed. This clearly can
7174 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00007175 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
7176 if (FLL->isExact())
7177 return;
7178 } else
7179 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
7180 if (FLR->isExact())
7181 return;
Mike Stump11289f42009-09-09 15:08:12 +00007182
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007183 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00007184 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00007185 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00007186 return;
Mike Stump11289f42009-09-09 15:08:12 +00007187
David Blaikie1f4ff152012-07-16 20:47:22 +00007188 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00007189 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00007190 return;
Mike Stump11289f42009-09-09 15:08:12 +00007191
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007192 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00007193 Diag(Loc, diag::warn_floatingpoint_eq)
7194 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007195}
John McCallca01b222010-01-04 23:21:16 +00007196
John McCall70aa5392010-01-06 05:24:50 +00007197//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
7198//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00007199
John McCall70aa5392010-01-06 05:24:50 +00007200namespace {
John McCallca01b222010-01-04 23:21:16 +00007201
John McCall70aa5392010-01-06 05:24:50 +00007202/// Structure recording the 'active' range of an integer-valued
7203/// expression.
7204struct IntRange {
7205 /// The number of bits active in the int.
7206 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00007207
John McCall70aa5392010-01-06 05:24:50 +00007208 /// True if the int is known not to have negative values.
7209 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00007210
John McCall70aa5392010-01-06 05:24:50 +00007211 IntRange(unsigned Width, bool NonNegative)
7212 : Width(Width), NonNegative(NonNegative)
7213 {}
John McCallca01b222010-01-04 23:21:16 +00007214
John McCall817d4af2010-11-10 23:38:19 +00007215 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00007216 static IntRange forBoolType() {
7217 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00007218 }
7219
John McCall817d4af2010-11-10 23:38:19 +00007220 /// Returns the range of an opaque value of the given integral type.
7221 static IntRange forValueOfType(ASTContext &C, QualType T) {
7222 return forValueOfCanonicalType(C,
7223 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00007224 }
7225
John McCall817d4af2010-11-10 23:38:19 +00007226 /// Returns the range of an opaque value of a canonical integral type.
7227 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00007228 assert(T->isCanonicalUnqualified());
7229
7230 if (const VectorType *VT = dyn_cast<VectorType>(T))
7231 T = VT->getElementType().getTypePtr();
7232 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
7233 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00007234 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
7235 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00007236
David Majnemer6a426652013-06-07 22:07:20 +00007237 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00007238 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00007239 EnumDecl *Enum = ET->getDecl();
7240 if (!Enum->isCompleteDefinition())
7241 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00007242
David Majnemer6a426652013-06-07 22:07:20 +00007243 unsigned NumPositive = Enum->getNumPositiveBits();
7244 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00007245
David Majnemer6a426652013-06-07 22:07:20 +00007246 if (NumNegative == 0)
7247 return IntRange(NumPositive, true/*NonNegative*/);
7248 else
7249 return IntRange(std::max(NumPositive + 1, NumNegative),
7250 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00007251 }
John McCall70aa5392010-01-06 05:24:50 +00007252
7253 const BuiltinType *BT = cast<BuiltinType>(T);
7254 assert(BT->isInteger());
7255
7256 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
7257 }
7258
John McCall817d4af2010-11-10 23:38:19 +00007259 /// Returns the "target" range of a canonical integral type, i.e.
7260 /// the range of values expressible in the type.
7261 ///
7262 /// This matches forValueOfCanonicalType except that enums have the
7263 /// full range of their type, not the range of their enumerators.
7264 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
7265 assert(T->isCanonicalUnqualified());
7266
7267 if (const VectorType *VT = dyn_cast<VectorType>(T))
7268 T = VT->getElementType().getTypePtr();
7269 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
7270 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00007271 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
7272 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00007273 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00007274 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00007275
7276 const BuiltinType *BT = cast<BuiltinType>(T);
7277 assert(BT->isInteger());
7278
7279 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
7280 }
7281
7282 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00007283 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00007284 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00007285 L.NonNegative && R.NonNegative);
7286 }
7287
John McCall817d4af2010-11-10 23:38:19 +00007288 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00007289 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00007290 return IntRange(std::min(L.Width, R.Width),
7291 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00007292 }
7293};
7294
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007295IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00007296 if (value.isSigned() && value.isNegative())
7297 return IntRange(value.getMinSignedBits(), false);
7298
7299 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00007300 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00007301
7302 // isNonNegative() just checks the sign bit without considering
7303 // signedness.
7304 return IntRange(value.getActiveBits(), true);
7305}
7306
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007307IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
7308 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00007309 if (result.isInt())
7310 return GetValueRange(C, result.getInt(), MaxWidth);
7311
7312 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00007313 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
7314 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
7315 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
7316 R = IntRange::join(R, El);
7317 }
John McCall70aa5392010-01-06 05:24:50 +00007318 return R;
7319 }
7320
7321 if (result.isComplexInt()) {
7322 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
7323 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
7324 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00007325 }
7326
7327 // This can happen with lossless casts to intptr_t of "based" lvalues.
7328 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00007329 // FIXME: The only reason we need to pass the type in here is to get
7330 // the sign right on this one case. It would be nice if APValue
7331 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007332 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00007333 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00007334}
John McCall70aa5392010-01-06 05:24:50 +00007335
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007336QualType GetExprType(const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00007337 QualType Ty = E->getType();
7338 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
7339 Ty = AtomicRHS->getValueType();
7340 return Ty;
7341}
7342
John McCall70aa5392010-01-06 05:24:50 +00007343/// Pseudo-evaluate the given integer expression, estimating the
7344/// range of values it might take.
7345///
7346/// \param MaxWidth - the width to which the value will be truncated
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007347IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00007348 E = E->IgnoreParens();
7349
7350 // Try a full evaluation first.
7351 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00007352 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00007353 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00007354
7355 // I think we only want to look through implicit casts here; if the
7356 // user has an explicit widening cast, we should treat the value as
7357 // being of the new, wider type.
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007358 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00007359 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00007360 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
7361
Eli Friedmane6d33952013-07-08 20:20:06 +00007362 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00007363
George Burgess IVdf1ed002016-01-13 01:52:39 +00007364 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
7365 CE->getCastKind() == CK_BooleanToSignedIntegral;
John McCall2ce81ad2010-01-06 22:07:33 +00007366
John McCall70aa5392010-01-06 05:24:50 +00007367 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00007368 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00007369 return OutputTypeRange;
7370
7371 IntRange SubRange
7372 = GetExprRange(C, CE->getSubExpr(),
7373 std::min(MaxWidth, OutputTypeRange.Width));
7374
7375 // Bail out if the subexpr's range is as wide as the cast type.
7376 if (SubRange.Width >= OutputTypeRange.Width)
7377 return OutputTypeRange;
7378
7379 // Otherwise, we take the smaller width, and we're non-negative if
7380 // either the output type or the subexpr is.
7381 return IntRange(SubRange.Width,
7382 SubRange.NonNegative || OutputTypeRange.NonNegative);
7383 }
7384
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007385 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00007386 // If we can fold the condition, just take that operand.
7387 bool CondResult;
7388 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
7389 return GetExprRange(C, CondResult ? CO->getTrueExpr()
7390 : CO->getFalseExpr(),
7391 MaxWidth);
7392
7393 // Otherwise, conservatively merge.
7394 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
7395 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
7396 return IntRange::join(L, R);
7397 }
7398
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007399 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00007400 switch (BO->getOpcode()) {
7401
7402 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00007403 case BO_LAnd:
7404 case BO_LOr:
7405 case BO_LT:
7406 case BO_GT:
7407 case BO_LE:
7408 case BO_GE:
7409 case BO_EQ:
7410 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00007411 return IntRange::forBoolType();
7412
John McCallc3688382011-07-13 06:35:24 +00007413 // The type of the assignments is the type of the LHS, so the RHS
7414 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00007415 case BO_MulAssign:
7416 case BO_DivAssign:
7417 case BO_RemAssign:
7418 case BO_AddAssign:
7419 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00007420 case BO_XorAssign:
7421 case BO_OrAssign:
7422 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00007423 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00007424
John McCallc3688382011-07-13 06:35:24 +00007425 // Simple assignments just pass through the RHS, which will have
7426 // been coerced to the LHS type.
7427 case BO_Assign:
7428 // TODO: bitfields?
7429 return GetExprRange(C, BO->getRHS(), MaxWidth);
7430
John McCall70aa5392010-01-06 05:24:50 +00007431 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00007432 case BO_PtrMemD:
7433 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00007434 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00007435
John McCall2ce81ad2010-01-06 22:07:33 +00007436 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00007437 case BO_And:
7438 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00007439 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
7440 GetExprRange(C, BO->getRHS(), MaxWidth));
7441
John McCall70aa5392010-01-06 05:24:50 +00007442 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00007443 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00007444 // ...except that we want to treat '1 << (blah)' as logically
7445 // positive. It's an important idiom.
7446 if (IntegerLiteral *I
7447 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
7448 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00007449 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00007450 return IntRange(R.Width, /*NonNegative*/ true);
7451 }
7452 }
7453 // fallthrough
7454
John McCalle3027922010-08-25 11:45:40 +00007455 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00007456 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00007457
John McCall2ce81ad2010-01-06 22:07:33 +00007458 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00007459 case BO_Shr:
7460 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00007461 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
7462
7463 // If the shift amount is a positive constant, drop the width by
7464 // that much.
7465 llvm::APSInt shift;
7466 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
7467 shift.isNonNegative()) {
7468 unsigned zext = shift.getZExtValue();
7469 if (zext >= L.Width)
7470 L.Width = (L.NonNegative ? 0 : 1);
7471 else
7472 L.Width -= zext;
7473 }
7474
7475 return L;
7476 }
7477
7478 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00007479 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00007480 return GetExprRange(C, BO->getRHS(), MaxWidth);
7481
John McCall2ce81ad2010-01-06 22:07:33 +00007482 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00007483 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00007484 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00007485 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00007486 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00007487
John McCall51431812011-07-14 22:39:48 +00007488 // The width of a division result is mostly determined by the size
7489 // of the LHS.
7490 case BO_Div: {
7491 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00007492 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00007493 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
7494
7495 // If the divisor is constant, use that.
7496 llvm::APSInt divisor;
7497 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
7498 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
7499 if (log2 >= L.Width)
7500 L.Width = (L.NonNegative ? 0 : 1);
7501 else
7502 L.Width = std::min(L.Width - log2, MaxWidth);
7503 return L;
7504 }
7505
7506 // Otherwise, just use the LHS's width.
7507 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
7508 return IntRange(L.Width, L.NonNegative && R.NonNegative);
7509 }
7510
7511 // The result of a remainder can't be larger than the result of
7512 // either side.
7513 case BO_Rem: {
7514 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00007515 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00007516 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
7517 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
7518
7519 IntRange meet = IntRange::meet(L, R);
7520 meet.Width = std::min(meet.Width, MaxWidth);
7521 return meet;
7522 }
7523
7524 // The default behavior is okay for these.
7525 case BO_Mul:
7526 case BO_Add:
7527 case BO_Xor:
7528 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00007529 break;
7530 }
7531
John McCall51431812011-07-14 22:39:48 +00007532 // The default case is to treat the operation as if it were closed
7533 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00007534 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
7535 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
7536 return IntRange::join(L, R);
7537 }
7538
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007539 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00007540 switch (UO->getOpcode()) {
7541 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00007542 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00007543 return IntRange::forBoolType();
7544
7545 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00007546 case UO_Deref:
7547 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00007548 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00007549
7550 default:
7551 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
7552 }
7553 }
7554
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007555 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
Ted Kremeneka553fbf2013-10-14 18:55:27 +00007556 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
7557
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007558 if (const auto *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00007559 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00007560 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00007561
Eli Friedmane6d33952013-07-08 20:20:06 +00007562 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00007563}
John McCall263a48b2010-01-04 23:31:57 +00007564
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007565IntRange GetExprRange(ASTContext &C, const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00007566 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00007567}
7568
John McCall263a48b2010-01-04 23:31:57 +00007569/// Checks whether the given value, which currently has the given
7570/// source semantics, has the same value when coerced through the
7571/// target semantics.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007572bool IsSameFloatAfterCast(const llvm::APFloat &value,
7573 const llvm::fltSemantics &Src,
7574 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00007575 llvm::APFloat truncated = value;
7576
7577 bool ignored;
7578 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
7579 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
7580
7581 return truncated.bitwiseIsEqual(value);
7582}
7583
7584/// Checks whether the given value, which currently has the given
7585/// source semantics, has the same value when coerced through the
7586/// target semantics.
7587///
7588/// The value might be a vector of floats (or a complex number).
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007589bool IsSameFloatAfterCast(const APValue &value,
7590 const llvm::fltSemantics &Src,
7591 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00007592 if (value.isFloat())
7593 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
7594
7595 if (value.isVector()) {
7596 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
7597 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
7598 return false;
7599 return true;
7600 }
7601
7602 assert(value.isComplexFloat());
7603 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
7604 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
7605}
7606
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007607void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007608
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007609bool IsZero(Sema &S, Expr *E) {
Ted Kremenek6274be42010-09-23 21:43:44 +00007610 // Suppress cases where we are comparing against an enum constant.
7611 if (const DeclRefExpr *DR =
7612 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
7613 if (isa<EnumConstantDecl>(DR->getDecl()))
7614 return false;
7615
7616 // Suppress cases where the '0' value is expanded from a macro.
7617 if (E->getLocStart().isMacroID())
7618 return false;
7619
John McCallcc7e5bf2010-05-06 08:58:33 +00007620 llvm::APSInt Value;
7621 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
7622}
7623
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007624bool HasEnumType(Expr *E) {
John McCall2551c1b2010-10-06 00:25:24 +00007625 // Strip off implicit integral promotions.
7626 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00007627 if (ICE->getCastKind() != CK_IntegralCast &&
7628 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00007629 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00007630 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00007631 }
7632
7633 return E->getType()->isEnumeralType();
7634}
7635
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007636void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00007637 // Disable warning in template instantiations.
7638 if (!S.ActiveTemplateInstantiations.empty())
7639 return;
7640
John McCalle3027922010-08-25 11:45:40 +00007641 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00007642 if (E->isValueDependent())
7643 return;
7644
John McCalle3027922010-08-25 11:45:40 +00007645 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007646 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00007647 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00007648 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00007649 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007650 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00007651 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00007652 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00007653 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007654 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00007655 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00007656 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00007657 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007658 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00007659 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00007660 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
7661 }
7662}
7663
Benjamin Kramer7320b992016-06-15 14:20:56 +00007664void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E, Expr *Constant,
7665 Expr *Other, const llvm::APSInt &Value,
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007666 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00007667 // Disable warning in template instantiations.
7668 if (!S.ActiveTemplateInstantiations.empty())
7669 return;
7670
Richard Trieu0f097742014-04-04 04:13:47 +00007671 // TODO: Investigate using GetExprRange() to get tighter bounds
7672 // on the bit ranges.
7673 QualType OtherT = Other->getType();
David Majnemer7800f1f2015-05-23 01:32:17 +00007674 if (const auto *AT = OtherT->getAs<AtomicType>())
Justin Bogner4f42fc42014-07-21 18:01:53 +00007675 OtherT = AT->getValueType();
Richard Trieu0f097742014-04-04 04:13:47 +00007676 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
7677 unsigned OtherWidth = OtherRange.Width;
7678
7679 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
7680
Richard Trieu560910c2012-11-14 22:50:24 +00007681 // 0 values are handled later by CheckTrivialUnsignedComparison().
Richard Trieu0f097742014-04-04 04:13:47 +00007682 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00007683 return;
7684
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007685 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00007686 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00007687
Richard Trieu0f097742014-04-04 04:13:47 +00007688 // Used for diagnostic printout.
7689 enum {
7690 LiteralConstant = 0,
7691 CXXBoolLiteralTrue,
7692 CXXBoolLiteralFalse
7693 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00007694
Richard Trieu0f097742014-04-04 04:13:47 +00007695 if (!OtherIsBooleanType) {
7696 QualType ConstantT = Constant->getType();
7697 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00007698
Richard Trieu0f097742014-04-04 04:13:47 +00007699 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
7700 return;
7701 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
7702 "comparison with non-integer type");
7703
7704 bool ConstantSigned = ConstantT->isSignedIntegerType();
7705 bool CommonSigned = CommonT->isSignedIntegerType();
7706
7707 bool EqualityOnly = false;
7708
7709 if (CommonSigned) {
7710 // The common type is signed, therefore no signed to unsigned conversion.
7711 if (!OtherRange.NonNegative) {
7712 // Check that the constant is representable in type OtherT.
7713 if (ConstantSigned) {
7714 if (OtherWidth >= Value.getMinSignedBits())
7715 return;
7716 } else { // !ConstantSigned
7717 if (OtherWidth >= Value.getActiveBits() + 1)
7718 return;
7719 }
7720 } else { // !OtherSigned
7721 // Check that the constant is representable in type OtherT.
7722 // Negative values are out of range.
7723 if (ConstantSigned) {
7724 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
7725 return;
7726 } else { // !ConstantSigned
7727 if (OtherWidth >= Value.getActiveBits())
7728 return;
7729 }
Richard Trieu560910c2012-11-14 22:50:24 +00007730 }
Richard Trieu0f097742014-04-04 04:13:47 +00007731 } else { // !CommonSigned
7732 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00007733 if (OtherWidth >= Value.getActiveBits())
7734 return;
Craig Toppercf360162014-06-18 05:13:11 +00007735 } else { // OtherSigned
7736 assert(!ConstantSigned &&
7737 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00007738 // Check to see if the constant is representable in OtherT.
7739 if (OtherWidth > Value.getActiveBits())
7740 return;
7741 // Check to see if the constant is equivalent to a negative value
7742 // cast to CommonT.
7743 if (S.Context.getIntWidth(ConstantT) ==
7744 S.Context.getIntWidth(CommonT) &&
7745 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
7746 return;
7747 // The constant value rests between values that OtherT can represent
7748 // after conversion. Relational comparison still works, but equality
7749 // comparisons will be tautological.
7750 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00007751 }
7752 }
Richard Trieu0f097742014-04-04 04:13:47 +00007753
7754 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
7755
7756 if (op == BO_EQ || op == BO_NE) {
7757 IsTrue = op == BO_NE;
7758 } else if (EqualityOnly) {
7759 return;
7760 } else if (RhsConstant) {
7761 if (op == BO_GT || op == BO_GE)
7762 IsTrue = !PositiveConstant;
7763 else // op == BO_LT || op == BO_LE
7764 IsTrue = PositiveConstant;
7765 } else {
7766 if (op == BO_LT || op == BO_LE)
7767 IsTrue = !PositiveConstant;
7768 else // op == BO_GT || op == BO_GE
7769 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00007770 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00007771 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00007772 // Other isKnownToHaveBooleanValue
7773 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
7774 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
7775 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
7776
7777 static const struct LinkedConditions {
7778 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
7779 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
7780 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
7781 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
7782 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
7783 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
7784
7785 } TruthTable = {
7786 // Constant on LHS. | Constant on RHS. |
7787 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
7788 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
7789 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
7790 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
7791 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
7792 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
7793 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
7794 };
7795
7796 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
7797
7798 enum ConstantValue ConstVal = Zero;
7799 if (Value.isUnsigned() || Value.isNonNegative()) {
7800 if (Value == 0) {
7801 LiteralOrBoolConstant =
7802 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
7803 ConstVal = Zero;
7804 } else if (Value == 1) {
7805 LiteralOrBoolConstant =
7806 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
7807 ConstVal = One;
7808 } else {
7809 LiteralOrBoolConstant = LiteralConstant;
7810 ConstVal = GT_One;
7811 }
7812 } else {
7813 ConstVal = LT_Zero;
7814 }
7815
7816 CompareBoolWithConstantResult CmpRes;
7817
7818 switch (op) {
7819 case BO_LT:
7820 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
7821 break;
7822 case BO_GT:
7823 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
7824 break;
7825 case BO_LE:
7826 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
7827 break;
7828 case BO_GE:
7829 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
7830 break;
7831 case BO_EQ:
7832 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
7833 break;
7834 case BO_NE:
7835 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
7836 break;
7837 default:
7838 CmpRes = Unkwn;
7839 break;
7840 }
7841
7842 if (CmpRes == AFals) {
7843 IsTrue = false;
7844 } else if (CmpRes == ATrue) {
7845 IsTrue = true;
7846 } else {
7847 return;
7848 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007849 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00007850
7851 // If this is a comparison to an enum constant, include that
7852 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00007853 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00007854 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
7855 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
7856
7857 SmallString<64> PrettySourceValue;
7858 llvm::raw_svector_ostream OS(PrettySourceValue);
7859 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00007860 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00007861 else
7862 OS << Value;
7863
Richard Trieu0f097742014-04-04 04:13:47 +00007864 S.DiagRuntimeBehavior(
7865 E->getOperatorLoc(), E,
7866 S.PDiag(diag::warn_out_of_range_compare)
7867 << OS.str() << LiteralOrBoolConstant
7868 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
7869 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007870}
7871
John McCallcc7e5bf2010-05-06 08:58:33 +00007872/// Analyze the operands of the given comparison. Implements the
7873/// fallback case from AnalyzeComparison.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007874void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00007875 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
7876 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00007877}
John McCall263a48b2010-01-04 23:31:57 +00007878
John McCallca01b222010-01-04 23:21:16 +00007879/// \brief Implements -Wsign-compare.
7880///
Richard Trieu82402a02011-09-15 21:56:47 +00007881/// \param E the binary operator to check for warnings
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007882void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007883 // The type the comparison is being performed in.
7884 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00007885
7886 // Only analyze comparison operators where both sides have been converted to
7887 // the same type.
7888 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
7889 return AnalyzeImpConvsInComparison(S, E);
7890
7891 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00007892 if (E->isValueDependent())
7893 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00007894
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007895 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
7896 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007897
7898 bool IsComparisonConstant = false;
7899
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00007900 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007901 // of 'true' or 'false'.
7902 if (T->isIntegralType(S.Context)) {
7903 llvm::APSInt RHSValue;
7904 bool IsRHSIntegralLiteral =
7905 RHS->isIntegerConstantExpr(RHSValue, S.Context);
7906 llvm::APSInt LHSValue;
7907 bool IsLHSIntegralLiteral =
7908 LHS->isIntegerConstantExpr(LHSValue, S.Context);
7909 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
7910 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
7911 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
7912 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
7913 else
7914 IsComparisonConstant =
7915 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00007916 } else if (!T->hasUnsignedIntegerRepresentation())
7917 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007918
John McCallcc7e5bf2010-05-06 08:58:33 +00007919 // We don't do anything special if this isn't an unsigned integral
7920 // comparison: we're only interested in integral comparisons, and
7921 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00007922 //
7923 // We also don't care about value-dependent expressions or expressions
7924 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007925 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00007926 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007927
John McCallcc7e5bf2010-05-06 08:58:33 +00007928 // Check to see if one of the (unmodified) operands is of different
7929 // signedness.
7930 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00007931 if (LHS->getType()->hasSignedIntegerRepresentation()) {
7932 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00007933 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00007934 signedOperand = LHS;
7935 unsignedOperand = RHS;
7936 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
7937 signedOperand = RHS;
7938 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00007939 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00007940 CheckTrivialUnsignedComparison(S, E);
7941 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00007942 }
7943
John McCallcc7e5bf2010-05-06 08:58:33 +00007944 // Otherwise, calculate the effective range of the signed operand.
7945 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00007946
John McCallcc7e5bf2010-05-06 08:58:33 +00007947 // Go ahead and analyze implicit conversions in the operands. Note
7948 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00007949 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
7950 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00007951
John McCallcc7e5bf2010-05-06 08:58:33 +00007952 // If the signed range is non-negative, -Wsign-compare won't fire,
7953 // but we should still check for comparisons which are always true
7954 // or false.
7955 if (signedRange.NonNegative)
7956 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00007957
7958 // For (in)equality comparisons, if the unsigned operand is a
7959 // constant which cannot collide with a overflowed signed operand,
7960 // then reinterpreting the signed operand as unsigned will not
7961 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00007962 if (E->isEqualityOp()) {
7963 unsigned comparisonWidth = S.Context.getIntWidth(T);
7964 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00007965
John McCallcc7e5bf2010-05-06 08:58:33 +00007966 // We should never be unable to prove that the unsigned operand is
7967 // non-negative.
7968 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
7969
7970 if (unsignedRange.Width < comparisonWidth)
7971 return;
7972 }
7973
Douglas Gregorbfb4a212012-05-01 01:53:49 +00007974 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
7975 S.PDiag(diag::warn_mixed_sign_comparison)
7976 << LHS->getType() << RHS->getType()
7977 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00007978}
7979
John McCall1f425642010-11-11 03:21:53 +00007980/// Analyzes an attempt to assign the given value to a bitfield.
7981///
7982/// Returns true if there was something fishy about the attempt.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007983bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
7984 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00007985 assert(Bitfield->isBitField());
7986 if (Bitfield->isInvalidDecl())
7987 return false;
7988
John McCalldeebbcf2010-11-11 05:33:51 +00007989 // White-list bool bitfields.
7990 if (Bitfield->getType()->isBooleanType())
7991 return false;
7992
Douglas Gregor789adec2011-02-04 13:09:01 +00007993 // Ignore value- or type-dependent expressions.
7994 if (Bitfield->getBitWidth()->isValueDependent() ||
7995 Bitfield->getBitWidth()->isTypeDependent() ||
7996 Init->isValueDependent() ||
7997 Init->isTypeDependent())
7998 return false;
7999
John McCall1f425642010-11-11 03:21:53 +00008000 Expr *OriginalInit = Init->IgnoreParenImpCasts();
8001
Richard Smith5fab0c92011-12-28 19:48:30 +00008002 llvm::APSInt Value;
8003 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00008004 return false;
8005
John McCall1f425642010-11-11 03:21:53 +00008006 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00008007 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00008008
Richard Trieu7561ed02016-08-05 02:39:30 +00008009 if (Value.isSigned() && Value.isNegative())
8010 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
8011 if (UO->getOpcode() == UO_Minus)
8012 if (isa<IntegerLiteral>(UO->getSubExpr()))
8013 OriginalWidth = Value.getMinSignedBits();
8014
John McCall1f425642010-11-11 03:21:53 +00008015 if (OriginalWidth <= FieldWidth)
8016 return false;
8017
Eli Friedmanc267a322012-01-26 23:11:39 +00008018 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00008019 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedmanc267a322012-01-26 23:11:39 +00008020 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00008021
Eli Friedmanc267a322012-01-26 23:11:39 +00008022 // Check whether the stored value is equal to the original value.
8023 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00008024 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00008025 return false;
8026
Eli Friedmanc267a322012-01-26 23:11:39 +00008027 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00008028 // therefore don't strictly fit into a signed bitfield of width 1.
8029 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00008030 return false;
8031
John McCall1f425642010-11-11 03:21:53 +00008032 std::string PrettyValue = Value.toString(10);
8033 std::string PrettyTrunc = TruncatedValue.toString(10);
8034
8035 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
8036 << PrettyValue << PrettyTrunc << OriginalInit->getType()
8037 << Init->getSourceRange();
8038
8039 return true;
8040}
8041
John McCalld2a53122010-11-09 23:24:47 +00008042/// Analyze the given simple or compound assignment for warning-worthy
8043/// operations.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008044void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00008045 // Just recurse on the LHS.
8046 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8047
8048 // We want to recurse on the RHS as normal unless we're assigning to
8049 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00008050 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008051 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00008052 E->getOperatorLoc())) {
8053 // Recurse, ignoring any implicit conversions on the RHS.
8054 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
8055 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00008056 }
8057 }
8058
8059 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
8060}
8061
John McCall263a48b2010-01-04 23:31:57 +00008062/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008063void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
8064 SourceLocation CContext, unsigned diag,
8065 bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00008066 if (pruneControlFlow) {
8067 S.DiagRuntimeBehavior(E->getExprLoc(), E,
8068 S.PDiag(diag)
8069 << SourceType << T << E->getSourceRange()
8070 << SourceRange(CContext));
8071 return;
8072 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00008073 S.Diag(E->getExprLoc(), diag)
8074 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
8075}
8076
Chandler Carruth7f3654f2011-04-05 06:47:57 +00008077/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008078void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
8079 unsigned diag, bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00008080 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00008081}
8082
Richard Trieube234c32016-04-21 21:04:55 +00008083
8084/// Diagnose an implicit cast from a floating point value to an integer value.
8085void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
8086
8087 SourceLocation CContext) {
8088 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
8089 const bool PruneWarnings = !S.ActiveTemplateInstantiations.empty();
8090
8091 Expr *InnerE = E->IgnoreParenImpCasts();
8092 // We also want to warn on, e.g., "int i = -1.234"
8093 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
8094 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
8095 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
8096
8097 const bool IsLiteral =
8098 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
8099
8100 llvm::APFloat Value(0.0);
8101 bool IsConstant =
8102 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
8103 if (!IsConstant) {
Richard Trieu891f0f12016-04-22 22:14:32 +00008104 return DiagnoseImpCast(S, E, T, CContext,
8105 diag::warn_impcast_float_integer, PruneWarnings);
Richard Trieube234c32016-04-21 21:04:55 +00008106 }
8107
Chandler Carruth016ef402011-04-10 08:36:24 +00008108 bool isExact = false;
Richard Trieube234c32016-04-21 21:04:55 +00008109
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00008110 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
8111 T->hasUnsignedIntegerRepresentation());
Richard Trieube234c32016-04-21 21:04:55 +00008112 if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero,
8113 &isExact) == llvm::APFloat::opOK &&
Richard Trieu891f0f12016-04-22 22:14:32 +00008114 isExact) {
Richard Trieube234c32016-04-21 21:04:55 +00008115 if (IsLiteral) return;
8116 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
8117 PruneWarnings);
8118 }
8119
8120 unsigned DiagID = 0;
Richard Trieu891f0f12016-04-22 22:14:32 +00008121 if (IsLiteral) {
Richard Trieube234c32016-04-21 21:04:55 +00008122 // Warn on floating point literal to integer.
8123 DiagID = diag::warn_impcast_literal_float_to_integer;
8124 } else if (IntegerValue == 0) {
8125 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
8126 return DiagnoseImpCast(S, E, T, CContext,
8127 diag::warn_impcast_float_integer, PruneWarnings);
8128 }
8129 // Warn on non-zero to zero conversion.
8130 DiagID = diag::warn_impcast_float_to_integer_zero;
8131 } else {
8132 if (IntegerValue.isUnsigned()) {
8133 if (!IntegerValue.isMaxValue()) {
8134 return DiagnoseImpCast(S, E, T, CContext,
8135 diag::warn_impcast_float_integer, PruneWarnings);
8136 }
8137 } else { // IntegerValue.isSigned()
8138 if (!IntegerValue.isMaxSignedValue() &&
8139 !IntegerValue.isMinSignedValue()) {
8140 return DiagnoseImpCast(S, E, T, CContext,
8141 diag::warn_impcast_float_integer, PruneWarnings);
8142 }
8143 }
8144 // Warn on evaluatable floating point expression to integer conversion.
8145 DiagID = diag::warn_impcast_float_to_integer;
8146 }
Chandler Carruth016ef402011-04-10 08:36:24 +00008147
Eli Friedman07185912013-08-29 23:44:43 +00008148 // FIXME: Force the precision of the source value down so we don't print
8149 // digits which are usually useless (we don't really care here if we
8150 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
8151 // would automatically print the shortest representation, but it's a bit
8152 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00008153 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00008154 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
8155 precision = (precision * 59 + 195) / 196;
8156 Value.toString(PrettySourceValue, precision);
8157
David Blaikie9b88cc02012-05-15 17:18:27 +00008158 SmallString<16> PrettyTargetValue;
Richard Trieube234c32016-04-21 21:04:55 +00008159 if (IsBool)
Aaron Ballmandbc441e2015-12-30 14:26:07 +00008160 PrettyTargetValue = Value.isZero() ? "false" : "true";
David Blaikie7555b6a2012-05-15 16:56:36 +00008161 else
David Blaikie9b88cc02012-05-15 17:18:27 +00008162 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00008163
Richard Trieube234c32016-04-21 21:04:55 +00008164 if (PruneWarnings) {
8165 S.DiagRuntimeBehavior(E->getExprLoc(), E,
8166 S.PDiag(DiagID)
8167 << E->getType() << T.getUnqualifiedType()
8168 << PrettySourceValue << PrettyTargetValue
8169 << E->getSourceRange() << SourceRange(CContext));
8170 } else {
8171 S.Diag(E->getExprLoc(), DiagID)
8172 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
8173 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
8174 }
Chandler Carruth016ef402011-04-10 08:36:24 +00008175}
8176
John McCall18a2c2c2010-11-09 22:22:12 +00008177std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
8178 if (!Range.Width) return "0";
8179
8180 llvm::APSInt ValueInRange = Value;
8181 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00008182 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00008183 return ValueInRange.toString(10);
8184}
8185
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008186bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00008187 if (!isa<ImplicitCastExpr>(Ex))
8188 return false;
8189
8190 Expr *InnerE = Ex->IgnoreParenImpCasts();
8191 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
8192 const Type *Source =
8193 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
8194 if (Target->isDependentType())
8195 return false;
8196
8197 const BuiltinType *FloatCandidateBT =
8198 dyn_cast<BuiltinType>(ToBool ? Source : Target);
8199 const Type *BoolCandidateType = ToBool ? Target : Source;
8200
8201 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
8202 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
8203}
8204
8205void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
8206 SourceLocation CC) {
8207 unsigned NumArgs = TheCall->getNumArgs();
8208 for (unsigned i = 0; i < NumArgs; ++i) {
8209 Expr *CurrA = TheCall->getArg(i);
8210 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
8211 continue;
8212
8213 bool IsSwapped = ((i > 0) &&
8214 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
8215 IsSwapped |= ((i < (NumArgs - 1)) &&
8216 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
8217 if (IsSwapped) {
8218 // Warn on this floating-point to bool conversion.
8219 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
8220 CurrA->getType(), CC,
8221 diag::warn_impcast_floating_point_to_bool);
8222 }
8223 }
8224}
8225
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008226void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) {
Richard Trieu5b993502014-10-15 03:42:06 +00008227 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
8228 E->getExprLoc()))
8229 return;
8230
Richard Trieu09d6b802016-01-08 23:35:06 +00008231 // Don't warn on functions which have return type nullptr_t.
8232 if (isa<CallExpr>(E))
8233 return;
8234
Richard Trieu5b993502014-10-15 03:42:06 +00008235 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
8236 const Expr::NullPointerConstantKind NullKind =
8237 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
8238 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
8239 return;
8240
8241 // Return if target type is a safe conversion.
8242 if (T->isAnyPointerType() || T->isBlockPointerType() ||
8243 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
8244 return;
8245
8246 SourceLocation Loc = E->getSourceRange().getBegin();
8247
Richard Trieu0a5e1662016-02-13 00:58:53 +00008248 // Venture through the macro stacks to get to the source of macro arguments.
8249 // The new location is a better location than the complete location that was
8250 // passed in.
8251 while (S.SourceMgr.isMacroArgExpansion(Loc))
8252 Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc);
8253
8254 while (S.SourceMgr.isMacroArgExpansion(CC))
8255 CC = S.SourceMgr.getImmediateMacroCallerLoc(CC);
8256
Richard Trieu5b993502014-10-15 03:42:06 +00008257 // __null is usually wrapped in a macro. Go up a macro if that is the case.
Richard Trieu0a5e1662016-02-13 00:58:53 +00008258 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
8259 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
8260 Loc, S.SourceMgr, S.getLangOpts());
8261 if (MacroName == "NULL")
8262 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
Richard Trieu5b993502014-10-15 03:42:06 +00008263 }
8264
8265 // Only warn if the null and context location are in the same macro expansion.
8266 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
8267 return;
8268
8269 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
8270 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
8271 << FixItHint::CreateReplacement(Loc,
8272 S.getFixItZeroLiteralForType(T, Loc));
8273}
8274
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008275void checkObjCArrayLiteral(Sema &S, QualType TargetType,
8276 ObjCArrayLiteral *ArrayLiteral);
8277void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
8278 ObjCDictionaryLiteral *DictionaryLiteral);
Douglas Gregor5054cb02015-07-07 03:58:22 +00008279
8280/// Check a single element within a collection literal against the
8281/// target element type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008282void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType,
8283 Expr *Element, unsigned ElementKind) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00008284 // Skip a bitcast to 'id' or qualified 'id'.
8285 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
8286 if (ICE->getCastKind() == CK_BitCast &&
8287 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
8288 Element = ICE->getSubExpr();
8289 }
8290
8291 QualType ElementType = Element->getType();
8292 ExprResult ElementResult(Element);
8293 if (ElementType->getAs<ObjCObjectPointerType>() &&
8294 S.CheckSingleAssignmentConstraints(TargetElementType,
8295 ElementResult,
8296 false, false)
8297 != Sema::Compatible) {
8298 S.Diag(Element->getLocStart(),
8299 diag::warn_objc_collection_literal_element)
8300 << ElementType << ElementKind << TargetElementType
8301 << Element->getSourceRange();
8302 }
8303
8304 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
8305 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
8306 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
8307 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
8308}
8309
8310/// Check an Objective-C array literal being converted to the given
8311/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008312void checkObjCArrayLiteral(Sema &S, QualType TargetType,
8313 ObjCArrayLiteral *ArrayLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00008314 if (!S.NSArrayDecl)
8315 return;
8316
8317 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
8318 if (!TargetObjCPtr)
8319 return;
8320
8321 if (TargetObjCPtr->isUnspecialized() ||
8322 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
8323 != S.NSArrayDecl->getCanonicalDecl())
8324 return;
8325
8326 auto TypeArgs = TargetObjCPtr->getTypeArgs();
8327 if (TypeArgs.size() != 1)
8328 return;
8329
8330 QualType TargetElementType = TypeArgs[0];
8331 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
8332 checkObjCCollectionLiteralElement(S, TargetElementType,
8333 ArrayLiteral->getElement(I),
8334 0);
8335 }
8336}
8337
8338/// Check an Objective-C dictionary literal being converted to the given
8339/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008340void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
8341 ObjCDictionaryLiteral *DictionaryLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00008342 if (!S.NSDictionaryDecl)
8343 return;
8344
8345 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
8346 if (!TargetObjCPtr)
8347 return;
8348
8349 if (TargetObjCPtr->isUnspecialized() ||
8350 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
8351 != S.NSDictionaryDecl->getCanonicalDecl())
8352 return;
8353
8354 auto TypeArgs = TargetObjCPtr->getTypeArgs();
8355 if (TypeArgs.size() != 2)
8356 return;
8357
8358 QualType TargetKeyType = TypeArgs[0];
8359 QualType TargetObjectType = TypeArgs[1];
8360 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
8361 auto Element = DictionaryLiteral->getKeyValueElement(I);
8362 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
8363 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
8364 }
8365}
8366
Richard Trieufc404c72016-02-05 23:02:38 +00008367// Helper function to filter out cases for constant width constant conversion.
8368// Don't warn on char array initialization or for non-decimal values.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008369bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
8370 SourceLocation CC) {
Richard Trieufc404c72016-02-05 23:02:38 +00008371 // If initializing from a constant, and the constant starts with '0',
8372 // then it is a binary, octal, or hexadecimal. Allow these constants
8373 // to fill all the bits, even if there is a sign change.
8374 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
8375 const char FirstLiteralCharacter =
8376 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
8377 if (FirstLiteralCharacter == '0')
8378 return false;
8379 }
8380
8381 // If the CC location points to a '{', and the type is char, then assume
8382 // assume it is an array initialization.
8383 if (CC.isValid() && T->isCharType()) {
8384 const char FirstContextCharacter =
8385 S.getSourceManager().getCharacterData(CC)[0];
8386 if (FirstContextCharacter == '{')
8387 return false;
8388 }
8389
8390 return true;
8391}
8392
John McCallcc7e5bf2010-05-06 08:58:33 +00008393void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00008394 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008395 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00008396
John McCallcc7e5bf2010-05-06 08:58:33 +00008397 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
8398 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
8399 if (Source == Target) return;
8400 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00008401
Chandler Carruthc22845a2011-07-26 05:40:03 +00008402 // If the conversion context location is invalid don't complain. We also
8403 // don't want to emit a warning if the issue occurs from the expansion of
8404 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
8405 // delay this check as long as possible. Once we detect we are in that
8406 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008407 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00008408 return;
8409
Richard Trieu021baa32011-09-23 20:10:00 +00008410 // Diagnose implicit casts to bool.
8411 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
8412 if (isa<StringLiteral>(E))
8413 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00008414 // and expressions, for instance, assert(0 && "error here"), are
8415 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00008416 return DiagnoseImpCast(S, E, T, CC,
8417 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00008418 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
8419 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
8420 // This covers the literal expressions that evaluate to Objective-C
8421 // objects.
8422 return DiagnoseImpCast(S, E, T, CC,
8423 diag::warn_impcast_objective_c_literal_to_bool);
8424 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00008425 if (Source->isPointerType() || Source->canDecayToPointerType()) {
8426 // Warn on pointer to bool conversion that is always true.
8427 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
8428 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00008429 }
Richard Trieu021baa32011-09-23 20:10:00 +00008430 }
John McCall263a48b2010-01-04 23:31:57 +00008431
Douglas Gregor5054cb02015-07-07 03:58:22 +00008432 // Check implicit casts from Objective-C collection literals to specialized
8433 // collection types, e.g., NSArray<NSString *> *.
8434 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
8435 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
8436 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
8437 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
8438
John McCall263a48b2010-01-04 23:31:57 +00008439 // Strip vector types.
8440 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008441 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008442 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008443 return;
John McCallacf0ee52010-10-08 02:01:28 +00008444 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008445 }
Chris Lattneree7286f2011-06-14 04:51:15 +00008446
8447 // If the vector cast is cast between two vectors of the same size, it is
8448 // a bitcast, not a conversion.
8449 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
8450 return;
John McCall263a48b2010-01-04 23:31:57 +00008451
8452 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
8453 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
8454 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00008455 if (auto VecTy = dyn_cast<VectorType>(Target))
8456 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00008457
8458 // Strip complex types.
8459 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008460 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008461 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008462 return;
8463
John McCallacf0ee52010-10-08 02:01:28 +00008464 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008465 }
John McCall263a48b2010-01-04 23:31:57 +00008466
8467 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
8468 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
8469 }
8470
8471 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
8472 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
8473
8474 // If the source is floating point...
8475 if (SourceBT && SourceBT->isFloatingPoint()) {
8476 // ...and the target is floating point...
8477 if (TargetBT && TargetBT->isFloatingPoint()) {
8478 // ...then warn if we're dropping FP rank.
8479
8480 // Builtin FP kinds are ordered by increasing FP rank.
8481 if (SourceBT->getKind() > TargetBT->getKind()) {
8482 // Don't warn about float constants that are precisely
8483 // representable in the target type.
8484 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00008485 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00008486 // Value might be a float, a float vector, or a float complex.
8487 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00008488 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
8489 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00008490 return;
8491 }
8492
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008493 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008494 return;
8495
John McCallacf0ee52010-10-08 02:01:28 +00008496 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
George Burgess IV148e0d32015-10-29 00:28:52 +00008497 }
8498 // ... or possibly if we're increasing rank, too
8499 else if (TargetBT->getKind() > SourceBT->getKind()) {
8500 if (S.SourceMgr.isInSystemMacro(CC))
8501 return;
8502
8503 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
John McCall263a48b2010-01-04 23:31:57 +00008504 }
8505 return;
8506 }
8507
Richard Trieube234c32016-04-21 21:04:55 +00008508 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00008509 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008510 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008511 return;
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00008512
Richard Trieube234c32016-04-21 21:04:55 +00008513 DiagnoseFloatingImpCast(S, E, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00008514 }
John McCall263a48b2010-01-04 23:31:57 +00008515
Richard Smith54894fd2015-12-30 01:06:52 +00008516 // Detect the case where a call result is converted from floating-point to
8517 // to bool, and the final argument to the call is converted from bool, to
8518 // discover this typo:
8519 //
8520 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
8521 //
8522 // FIXME: This is an incredibly special case; is there some more general
8523 // way to detect this class of misplaced-parentheses bug?
8524 if (Target->isBooleanType() && isa<CallExpr>(E)) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00008525 // Check last argument of function call to see if it is an
8526 // implicit cast from a type matching the type the result
8527 // is being cast to.
8528 CallExpr *CEx = cast<CallExpr>(E);
Richard Smith54894fd2015-12-30 01:06:52 +00008529 if (unsigned NumArgs = CEx->getNumArgs()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00008530 Expr *LastA = CEx->getArg(NumArgs - 1);
8531 Expr *InnerE = LastA->IgnoreParenImpCasts();
Richard Smith54894fd2015-12-30 01:06:52 +00008532 if (isa<ImplicitCastExpr>(LastA) &&
8533 InnerE->getType()->isBooleanType()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00008534 // Warn on this floating-point to bool conversion
8535 DiagnoseImpCast(S, E, T, CC,
8536 diag::warn_impcast_floating_point_to_bool);
8537 }
8538 }
8539 }
John McCall263a48b2010-01-04 23:31:57 +00008540 return;
8541 }
8542
Richard Trieu5b993502014-10-15 03:42:06 +00008543 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +00008544
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +00008545 S.DiscardMisalignedMemberAddress(Target, E);
8546
David Blaikie9366d2b2012-06-19 21:19:06 +00008547 if (!Source->isIntegerType() || !Target->isIntegerType())
8548 return;
8549
David Blaikie7555b6a2012-05-15 16:56:36 +00008550 // TODO: remove this early return once the false positives for constant->bool
8551 // in templates, macros, etc, are reduced or removed.
8552 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
8553 return;
8554
John McCallcc7e5bf2010-05-06 08:58:33 +00008555 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00008556 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00008557
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008558 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00008559 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008560 // TODO: this should happen for bitfield stores, too.
8561 llvm::APSInt Value(32);
Richard Trieudcb55572016-01-29 23:51:16 +00008562 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008563 if (S.SourceMgr.isInSystemMacro(CC))
8564 return;
8565
John McCall18a2c2c2010-11-09 22:22:12 +00008566 std::string PrettySourceValue = Value.toString(10);
8567 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008568
Ted Kremenek33ba9952011-10-22 02:37:33 +00008569 S.DiagRuntimeBehavior(E->getExprLoc(), E,
8570 S.PDiag(diag::warn_impcast_integer_precision_constant)
8571 << PrettySourceValue << PrettyTargetValue
8572 << E->getType() << T << E->getSourceRange()
8573 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00008574 return;
8575 }
8576
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008577 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
8578 if (S.SourceMgr.isInSystemMacro(CC))
8579 return;
8580
David Blaikie9455da02012-04-12 22:40:54 +00008581 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00008582 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
8583 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00008584 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00008585 }
8586
Richard Trieudcb55572016-01-29 23:51:16 +00008587 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
8588 SourceRange.NonNegative && Source->isSignedIntegerType()) {
8589 // Warn when doing a signed to signed conversion, warn if the positive
8590 // source value is exactly the width of the target type, which will
8591 // cause a negative value to be stored.
8592
8593 llvm::APSInt Value;
Richard Trieufc404c72016-02-05 23:02:38 +00008594 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
8595 !S.SourceMgr.isInSystemMacro(CC)) {
8596 if (isSameWidthConstantConversion(S, E, T, CC)) {
8597 std::string PrettySourceValue = Value.toString(10);
8598 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Richard Trieudcb55572016-01-29 23:51:16 +00008599
Richard Trieufc404c72016-02-05 23:02:38 +00008600 S.DiagRuntimeBehavior(
8601 E->getExprLoc(), E,
8602 S.PDiag(diag::warn_impcast_integer_precision_constant)
8603 << PrettySourceValue << PrettyTargetValue << E->getType() << T
8604 << E->getSourceRange() << clang::SourceRange(CC));
8605 return;
Richard Trieudcb55572016-01-29 23:51:16 +00008606 }
8607 }
Richard Trieufc404c72016-02-05 23:02:38 +00008608
Richard Trieudcb55572016-01-29 23:51:16 +00008609 // Fall through for non-constants to give a sign conversion warning.
8610 }
8611
John McCallcc7e5bf2010-05-06 08:58:33 +00008612 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
8613 (!TargetRange.NonNegative && SourceRange.NonNegative &&
8614 SourceRange.Width == TargetRange.Width)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008615 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008616 return;
8617
John McCallcc7e5bf2010-05-06 08:58:33 +00008618 unsigned DiagID = diag::warn_impcast_integer_sign;
8619
8620 // Traditionally, gcc has warned about this under -Wsign-compare.
8621 // We also want to warn about it in -Wconversion.
8622 // So if -Wconversion is off, use a completely identical diagnostic
8623 // in the sign-compare group.
8624 // The conditional-checking code will
8625 if (ICContext) {
8626 DiagID = diag::warn_impcast_integer_sign_conditional;
8627 *ICContext = true;
8628 }
8629
John McCallacf0ee52010-10-08 02:01:28 +00008630 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00008631 }
8632
Douglas Gregora78f1932011-02-22 02:45:07 +00008633 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00008634 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
8635 // type, to give us better diagnostics.
8636 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00008637 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00008638 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
8639 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
8640 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
8641 SourceType = S.Context.getTypeDeclType(Enum);
8642 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
8643 }
8644 }
8645
Douglas Gregora78f1932011-02-22 02:45:07 +00008646 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
8647 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00008648 if (SourceEnum->getDecl()->hasNameForLinkage() &&
8649 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008650 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008651 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008652 return;
8653
Douglas Gregor364f7db2011-03-12 00:14:31 +00008654 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00008655 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008656 }
John McCall263a48b2010-01-04 23:31:57 +00008657}
8658
David Blaikie18e9ac72012-05-15 21:57:38 +00008659void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
8660 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00008661
8662void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00008663 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008664 E = E->IgnoreParenImpCasts();
8665
8666 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00008667 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00008668
John McCallacf0ee52010-10-08 02:01:28 +00008669 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008670 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00008671 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00008672}
8673
David Blaikie18e9ac72012-05-15 21:57:38 +00008674void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
8675 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00008676 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00008677
8678 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00008679 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
8680 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00008681
8682 // If -Wconversion would have warned about either of the candidates
8683 // for a signedness conversion to the context type...
8684 if (!Suspicious) return;
8685
8686 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00008687 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00008688 return;
8689
John McCallcc7e5bf2010-05-06 08:58:33 +00008690 // ...then check whether it would have warned about either of the
8691 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00008692 if (E->getType() == T) return;
8693
8694 Suspicious = false;
8695 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
8696 E->getType(), CC, &Suspicious);
8697 if (!Suspicious)
8698 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00008699 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00008700}
8701
Richard Trieu65724892014-11-15 06:37:39 +00008702/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
8703/// Input argument E is a logical expression.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008704void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
Richard Trieu65724892014-11-15 06:37:39 +00008705 if (S.getLangOpts().Bool)
8706 return;
8707 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
8708}
8709
John McCallcc7e5bf2010-05-06 08:58:33 +00008710/// AnalyzeImplicitConversions - Find and report any interesting
8711/// implicit conversions in the given expression. There are a couple
8712/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00008713void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00008714 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00008715 Expr *E = OrigE->IgnoreParenImpCasts();
8716
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00008717 if (E->isTypeDependent() || E->isValueDependent())
8718 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00008719
John McCallcc7e5bf2010-05-06 08:58:33 +00008720 // For conditional operators, we analyze the arguments as if they
8721 // were being fed directly into the output.
8722 if (isa<ConditionalOperator>(E)) {
8723 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00008724 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00008725 return;
8726 }
8727
Hans Wennborgf4ad2322012-08-28 15:44:30 +00008728 // Check implicit argument conversions for function calls.
8729 if (CallExpr *Call = dyn_cast<CallExpr>(E))
8730 CheckImplicitArgumentConversions(S, Call, CC);
8731
John McCallcc7e5bf2010-05-06 08:58:33 +00008732 // Go ahead and check any implicit conversions we might have skipped.
8733 // The non-canonical typecheck is just an optimization;
8734 // CheckImplicitConversion will filter out dead implicit conversions.
8735 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00008736 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008737
8738 // Now continue drilling into this expression.
Richard Smithd7bed4d2015-11-22 02:57:17 +00008739
8740 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
8741 // The bound subexpressions in a PseudoObjectExpr are not reachable
8742 // as transitive children.
8743 // FIXME: Use a more uniform representation for this.
8744 for (auto *SE : POE->semantics())
8745 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
8746 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00008747 }
Richard Smithd7bed4d2015-11-22 02:57:17 +00008748
John McCallcc7e5bf2010-05-06 08:58:33 +00008749 // Skip past explicit casts.
8750 if (isa<ExplicitCastExpr>(E)) {
8751 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00008752 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008753 }
8754
John McCalld2a53122010-11-09 23:24:47 +00008755 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
8756 // Do a somewhat different check with comparison operators.
8757 if (BO->isComparisonOp())
8758 return AnalyzeComparison(S, BO);
8759
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008760 // And with simple assignments.
8761 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00008762 return AnalyzeAssignment(S, BO);
8763 }
John McCallcc7e5bf2010-05-06 08:58:33 +00008764
8765 // These break the otherwise-useful invariant below. Fortunately,
8766 // we don't really need to recurse into them, because any internal
8767 // expressions should have been analyzed already when they were
8768 // built into statements.
8769 if (isa<StmtExpr>(E)) return;
8770
8771 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00008772 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00008773
8774 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00008775 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00008776 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00008777 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Benjamin Kramer642f1732015-07-02 21:03:14 +00008778 for (Stmt *SubStmt : E->children()) {
8779 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00008780 if (!ChildExpr)
8781 continue;
8782
Richard Trieu955231d2014-01-25 01:10:35 +00008783 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00008784 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00008785 // Ignore checking string literals that are in logical and operators.
8786 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00008787 continue;
8788 AnalyzeImplicitConversions(S, ChildExpr, CC);
8789 }
Richard Trieu791b86e2014-11-19 06:08:18 +00008790
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00008791 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +00008792 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
8793 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00008794 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +00008795
8796 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
8797 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00008798 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00008799 }
Richard Trieu791b86e2014-11-19 06:08:18 +00008800
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00008801 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
8802 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +00008803 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008804}
8805
8806} // end anonymous namespace
8807
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00008808static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
8809 unsigned Start, unsigned End) {
8810 bool IllegalParams = false;
8811 for (unsigned I = Start; I <= End; ++I) {
8812 QualType Ty = TheCall->getArg(I)->getType();
8813 // Taking into account implicit conversions,
8814 // allow any integer within 32 bits range
8815 if (!Ty->isIntegerType() ||
8816 S.Context.getTypeSizeInChars(Ty).getQuantity() > 4) {
8817 S.Diag(TheCall->getArg(I)->getLocStart(),
8818 diag::err_opencl_enqueue_kernel_invalid_local_size_type);
8819 IllegalParams = true;
8820 }
8821 // Potentially emit standard warnings for implicit conversions if enabled
8822 // using -Wconversion.
8823 CheckImplicitConversion(S, TheCall->getArg(I), S.Context.UnsignedIntTy,
8824 TheCall->getArg(I)->getLocStart());
8825 }
8826 return IllegalParams;
8827}
8828
Richard Trieuc1888e02014-06-28 23:25:37 +00008829// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
8830// Returns true when emitting a warning about taking the address of a reference.
8831static bool CheckForReference(Sema &SemaRef, const Expr *E,
Benjamin Kramer7320b992016-06-15 14:20:56 +00008832 const PartialDiagnostic &PD) {
Richard Trieuc1888e02014-06-28 23:25:37 +00008833 E = E->IgnoreParenImpCasts();
8834
8835 const FunctionDecl *FD = nullptr;
8836
8837 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
8838 if (!DRE->getDecl()->getType()->isReferenceType())
8839 return false;
8840 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
8841 if (!M->getMemberDecl()->getType()->isReferenceType())
8842 return false;
8843 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +00008844 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +00008845 return false;
8846 FD = Call->getDirectCallee();
8847 } else {
8848 return false;
8849 }
8850
8851 SemaRef.Diag(E->getExprLoc(), PD);
8852
8853 // If possible, point to location of function.
8854 if (FD) {
8855 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
8856 }
8857
8858 return true;
8859}
8860
Richard Trieu4cbff5c2014-08-08 22:41:43 +00008861// Returns true if the SourceLocation is expanded from any macro body.
8862// Returns false if the SourceLocation is invalid, is from not in a macro
8863// expansion, or is from expanded from a top-level macro argument.
8864static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
8865 if (Loc.isInvalid())
8866 return false;
8867
8868 while (Loc.isMacroID()) {
8869 if (SM.isMacroBodyExpansion(Loc))
8870 return true;
8871 Loc = SM.getImmediateMacroCallerLoc(Loc);
8872 }
8873
8874 return false;
8875}
8876
Richard Trieu3bb8b562014-02-26 02:36:06 +00008877/// \brief Diagnose pointers that are always non-null.
8878/// \param E the expression containing the pointer
8879/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
8880/// compared to a null pointer
8881/// \param IsEqual True when the comparison is equal to a null pointer
8882/// \param Range Extra SourceRange to highlight in the diagnostic
8883void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
8884 Expr::NullPointerConstantKind NullKind,
8885 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00008886 if (!E)
8887 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00008888
8889 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +00008890 if (E->getExprLoc().isMacroID()) {
8891 const SourceManager &SM = getSourceManager();
8892 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
8893 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +00008894 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +00008895 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00008896 E = E->IgnoreImpCasts();
8897
8898 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
8899
Richard Trieuf7432752014-06-06 21:39:26 +00008900 if (isa<CXXThisExpr>(E)) {
8901 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
8902 : diag::warn_this_bool_conversion;
8903 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
8904 return;
8905 }
8906
Richard Trieu3bb8b562014-02-26 02:36:06 +00008907 bool IsAddressOf = false;
8908
8909 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
8910 if (UO->getOpcode() != UO_AddrOf)
8911 return;
8912 IsAddressOf = true;
8913 E = UO->getSubExpr();
8914 }
8915
Richard Trieuc1888e02014-06-28 23:25:37 +00008916 if (IsAddressOf) {
8917 unsigned DiagID = IsCompare
8918 ? diag::warn_address_of_reference_null_compare
8919 : diag::warn_address_of_reference_bool_conversion;
8920 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
8921 << IsEqual;
8922 if (CheckForReference(*this, E, PD)) {
8923 return;
8924 }
8925 }
8926
Nick Lewyckybc85ec82016-06-15 05:18:39 +00008927 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
8928 bool IsParam = isa<NonNullAttr>(NonnullAttr);
George Burgess IV850269a2015-12-08 22:02:00 +00008929 std::string Str;
8930 llvm::raw_string_ostream S(Str);
8931 E->printPretty(S, nullptr, getPrintingPolicy());
8932 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
8933 : diag::warn_cast_nonnull_to_bool;
8934 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
8935 << E->getSourceRange() << Range << IsEqual;
Nick Lewyckybc85ec82016-06-15 05:18:39 +00008936 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
George Burgess IV850269a2015-12-08 22:02:00 +00008937 };
8938
8939 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
8940 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
8941 if (auto *Callee = Call->getDirectCallee()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00008942 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
8943 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +00008944 return;
8945 }
8946 }
8947 }
8948
Richard Trieu3bb8b562014-02-26 02:36:06 +00008949 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +00008950 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +00008951 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
8952 D = R->getDecl();
8953 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
8954 D = M->getMemberDecl();
8955 }
8956
8957 // Weak Decls can be null.
8958 if (!D || D->isWeak())
8959 return;
George Burgess IV850269a2015-12-08 22:02:00 +00008960
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008961 // Check for parameter decl with nonnull attribute
George Burgess IV850269a2015-12-08 22:02:00 +00008962 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
8963 if (getCurFunction() &&
8964 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00008965 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
8966 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +00008967 return;
8968 }
8969
8970 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
David Majnemera3debed2016-06-24 05:33:44 +00008971 auto ParamIter = llvm::find(FD->parameters(), PV);
George Burgess IV850269a2015-12-08 22:02:00 +00008972 assert(ParamIter != FD->param_end());
8973 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
8974
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008975 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
8976 if (!NonNull->args_size()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00008977 ComplainAboutNonnullParamOrCall(NonNull);
George Burgess IV850269a2015-12-08 22:02:00 +00008978 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008979 }
George Burgess IV850269a2015-12-08 22:02:00 +00008980
8981 for (unsigned ArgNo : NonNull->args()) {
8982 if (ArgNo == ParamNo) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00008983 ComplainAboutNonnullParamOrCall(NonNull);
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008984 return;
8985 }
George Burgess IV850269a2015-12-08 22:02:00 +00008986 }
8987 }
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008988 }
8989 }
George Burgess IV850269a2015-12-08 22:02:00 +00008990 }
8991
Richard Trieu3bb8b562014-02-26 02:36:06 +00008992 QualType T = D->getType();
8993 const bool IsArray = T->isArrayType();
8994 const bool IsFunction = T->isFunctionType();
8995
Richard Trieuc1888e02014-06-28 23:25:37 +00008996 // Address of function is used to silence the function warning.
8997 if (IsAddressOf && IsFunction) {
8998 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00008999 }
9000
9001 // Found nothing.
9002 if (!IsAddressOf && !IsFunction && !IsArray)
9003 return;
9004
9005 // Pretty print the expression for the diagnostic.
9006 std::string Str;
9007 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +00009008 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +00009009
9010 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
9011 : diag::warn_impcast_pointer_to_bool;
Craig Topperfa1340f2015-12-23 05:44:46 +00009012 enum {
9013 AddressOf,
9014 FunctionPointer,
9015 ArrayPointer
9016 } DiagType;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009017 if (IsAddressOf)
9018 DiagType = AddressOf;
9019 else if (IsFunction)
9020 DiagType = FunctionPointer;
9021 else if (IsArray)
9022 DiagType = ArrayPointer;
9023 else
9024 llvm_unreachable("Could not determine diagnostic.");
9025 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
9026 << Range << IsEqual;
9027
9028 if (!IsFunction)
9029 return;
9030
9031 // Suggest '&' to silence the function warning.
9032 Diag(E->getExprLoc(), diag::note_function_warning_silence)
9033 << FixItHint::CreateInsertion(E->getLocStart(), "&");
9034
9035 // Check to see if '()' fixit should be emitted.
9036 QualType ReturnType;
9037 UnresolvedSet<4> NonTemplateOverloads;
9038 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
9039 if (ReturnType.isNull())
9040 return;
9041
9042 if (IsCompare) {
9043 // There are two cases here. If there is null constant, the only suggest
9044 // for a pointer return type. If the null is 0, then suggest if the return
9045 // type is a pointer or an integer type.
9046 if (!ReturnType->isPointerType()) {
9047 if (NullKind == Expr::NPCK_ZeroExpression ||
9048 NullKind == Expr::NPCK_ZeroLiteral) {
9049 if (!ReturnType->isIntegerType())
9050 return;
9051 } else {
9052 return;
9053 }
9054 }
9055 } else { // !IsCompare
9056 // For function to bool, only suggest if the function pointer has bool
9057 // return type.
9058 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
9059 return;
9060 }
9061 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +00009062 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +00009063}
9064
John McCallcc7e5bf2010-05-06 08:58:33 +00009065/// Diagnoses "dangerous" implicit conversions within the given
9066/// expression (which is a full expression). Implements -Wconversion
9067/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00009068///
9069/// \param CC the "context" location of the implicit conversion, i.e.
9070/// the most location of the syntactic entity requiring the implicit
9071/// conversion
9072void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009073 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00009074 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00009075 return;
9076
9077 // Don't diagnose for value- or type-dependent expressions.
9078 if (E->isTypeDependent() || E->isValueDependent())
9079 return;
9080
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009081 // Check for array bounds violations in cases where the check isn't triggered
9082 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
9083 // ArraySubscriptExpr is on the RHS of a variable initialization.
9084 CheckArrayAccess(E);
9085
John McCallacf0ee52010-10-08 02:01:28 +00009086 // This is not the right CC for (e.g.) a variable initialization.
9087 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009088}
9089
Richard Trieu65724892014-11-15 06:37:39 +00009090/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9091/// Input argument E is a logical expression.
9092void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
9093 ::CheckBoolLikeConversion(*this, E, CC);
9094}
9095
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009096/// Diagnose when expression is an integer constant expression and its evaluation
9097/// results in integer overflow
9098void Sema::CheckForIntOverflow (Expr *E) {
Akira Hatanakadfe2156f2016-02-10 06:06:06 +00009099 // Use a work list to deal with nested struct initializers.
9100 SmallVector<Expr *, 2> Exprs(1, E);
9101
9102 do {
9103 Expr *E = Exprs.pop_back_val();
9104
9105 if (isa<BinaryOperator>(E->IgnoreParenCasts())) {
9106 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
9107 continue;
9108 }
9109
9110 if (auto InitList = dyn_cast<InitListExpr>(E))
9111 Exprs.append(InitList->inits().begin(), InitList->inits().end());
9112 } while (!Exprs.empty());
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009113}
9114
Richard Smithc406cb72013-01-17 01:17:56 +00009115namespace {
9116/// \brief Visitor for expressions which looks for unsequenced operations on the
9117/// same object.
9118class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00009119 typedef EvaluatedExprVisitor<SequenceChecker> Base;
9120
Richard Smithc406cb72013-01-17 01:17:56 +00009121 /// \brief A tree of sequenced regions within an expression. Two regions are
9122 /// unsequenced if one is an ancestor or a descendent of the other. When we
9123 /// finish processing an expression with sequencing, such as a comma
9124 /// expression, we fold its tree nodes into its parent, since they are
9125 /// unsequenced with respect to nodes we will visit later.
9126 class SequenceTree {
9127 struct Value {
9128 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
9129 unsigned Parent : 31;
Aaron Ballmanaffa1c32016-07-06 18:33:01 +00009130 unsigned Merged : 1;
Richard Smithc406cb72013-01-17 01:17:56 +00009131 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009132 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00009133
9134 public:
9135 /// \brief A region within an expression which may be sequenced with respect
9136 /// to some other region.
9137 class Seq {
9138 explicit Seq(unsigned N) : Index(N) {}
9139 unsigned Index;
9140 friend class SequenceTree;
9141 public:
9142 Seq() : Index(0) {}
9143 };
9144
9145 SequenceTree() { Values.push_back(Value(0)); }
9146 Seq root() const { return Seq(0); }
9147
9148 /// \brief Create a new sequence of operations, which is an unsequenced
9149 /// subset of \p Parent. This sequence of operations is sequenced with
9150 /// respect to other children of \p Parent.
9151 Seq allocate(Seq Parent) {
9152 Values.push_back(Value(Parent.Index));
9153 return Seq(Values.size() - 1);
9154 }
9155
9156 /// \brief Merge a sequence of operations into its parent.
9157 void merge(Seq S) {
9158 Values[S.Index].Merged = true;
9159 }
9160
9161 /// \brief Determine whether two operations are unsequenced. This operation
9162 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
9163 /// should have been merged into its parent as appropriate.
9164 bool isUnsequenced(Seq Cur, Seq Old) {
9165 unsigned C = representative(Cur.Index);
9166 unsigned Target = representative(Old.Index);
9167 while (C >= Target) {
9168 if (C == Target)
9169 return true;
9170 C = Values[C].Parent;
9171 }
9172 return false;
9173 }
9174
9175 private:
9176 /// \brief Pick a representative for a sequence.
9177 unsigned representative(unsigned K) {
9178 if (Values[K].Merged)
9179 // Perform path compression as we go.
9180 return Values[K].Parent = representative(Values[K].Parent);
9181 return K;
9182 }
9183 };
9184
9185 /// An object for which we can track unsequenced uses.
9186 typedef NamedDecl *Object;
9187
9188 /// Different flavors of object usage which we track. We only track the
9189 /// least-sequenced usage of each kind.
9190 enum UsageKind {
9191 /// A read of an object. Multiple unsequenced reads are OK.
9192 UK_Use,
9193 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00009194 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00009195 UK_ModAsValue,
9196 /// A modification of an object which is not sequenced before the value
9197 /// computation of the expression, such as n++.
9198 UK_ModAsSideEffect,
9199
9200 UK_Count = UK_ModAsSideEffect + 1
9201 };
9202
9203 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +00009204 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +00009205 Expr *Use;
9206 SequenceTree::Seq Seq;
9207 };
9208
9209 struct UsageInfo {
9210 UsageInfo() : Diagnosed(false) {}
9211 Usage Uses[UK_Count];
9212 /// Have we issued a diagnostic for this variable already?
9213 bool Diagnosed;
9214 };
9215 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
9216
9217 Sema &SemaRef;
9218 /// Sequenced regions within the expression.
9219 SequenceTree Tree;
9220 /// Declaration modifications and references which we have seen.
9221 UsageInfoMap UsageMap;
9222 /// The region we are currently within.
9223 SequenceTree::Seq Region;
9224 /// Filled in with declarations which were modified as a side-effect
9225 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009226 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00009227 /// Expressions to check later. We defer checking these to reduce
9228 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009229 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00009230
9231 /// RAII object wrapping the visitation of a sequenced subexpression of an
9232 /// expression. At the end of this process, the side-effects of the evaluation
9233 /// become sequenced with respect to the value computation of the result, so
9234 /// we downgrade any UK_ModAsSideEffect within the evaluation to
9235 /// UK_ModAsValue.
9236 struct SequencedSubexpression {
9237 SequencedSubexpression(SequenceChecker &Self)
9238 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
9239 Self.ModAsSideEffect = &ModAsSideEffect;
9240 }
9241 ~SequencedSubexpression() {
David Majnemerf7e36092016-06-23 00:15:04 +00009242 for (auto &M : llvm::reverse(ModAsSideEffect)) {
9243 UsageInfo &U = Self.UsageMap[M.first];
Richard Smithe8efd992014-12-03 01:05:50 +00009244 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
David Majnemerf7e36092016-06-23 00:15:04 +00009245 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
9246 SideEffectUsage = M.second;
Richard Smithc406cb72013-01-17 01:17:56 +00009247 }
9248 Self.ModAsSideEffect = OldModAsSideEffect;
9249 }
9250
9251 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009252 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
9253 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00009254 };
9255
Richard Smith40238f02013-06-20 22:21:56 +00009256 /// RAII object wrapping the visitation of a subexpression which we might
9257 /// choose to evaluate as a constant. If any subexpression is evaluated and
9258 /// found to be non-constant, this allows us to suppress the evaluation of
9259 /// the outer expression.
9260 class EvaluationTracker {
9261 public:
9262 EvaluationTracker(SequenceChecker &Self)
9263 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
9264 Self.EvalTracker = this;
9265 }
9266 ~EvaluationTracker() {
9267 Self.EvalTracker = Prev;
9268 if (Prev)
9269 Prev->EvalOK &= EvalOK;
9270 }
9271
9272 bool evaluate(const Expr *E, bool &Result) {
9273 if (!EvalOK || E->isValueDependent())
9274 return false;
9275 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
9276 return EvalOK;
9277 }
9278
9279 private:
9280 SequenceChecker &Self;
9281 EvaluationTracker *Prev;
9282 bool EvalOK;
9283 } *EvalTracker;
9284
Richard Smithc406cb72013-01-17 01:17:56 +00009285 /// \brief Find the object which is produced by the specified expression,
9286 /// if any.
9287 Object getObject(Expr *E, bool Mod) const {
9288 E = E->IgnoreParenCasts();
9289 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
9290 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
9291 return getObject(UO->getSubExpr(), Mod);
9292 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9293 if (BO->getOpcode() == BO_Comma)
9294 return getObject(BO->getRHS(), Mod);
9295 if (Mod && BO->isAssignmentOp())
9296 return getObject(BO->getLHS(), Mod);
9297 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
9298 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
9299 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
9300 return ME->getMemberDecl();
9301 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9302 // FIXME: If this is a reference, map through to its value.
9303 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00009304 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +00009305 }
9306
9307 /// \brief Note that an object was modified or used by an expression.
9308 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
9309 Usage &U = UI.Uses[UK];
9310 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
9311 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
9312 ModAsSideEffect->push_back(std::make_pair(O, U));
9313 U.Use = Ref;
9314 U.Seq = Region;
9315 }
9316 }
9317 /// \brief Check whether a modification or use conflicts with a prior usage.
9318 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
9319 bool IsModMod) {
9320 if (UI.Diagnosed)
9321 return;
9322
9323 const Usage &U = UI.Uses[OtherKind];
9324 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
9325 return;
9326
9327 Expr *Mod = U.Use;
9328 Expr *ModOrUse = Ref;
9329 if (OtherKind == UK_Use)
9330 std::swap(Mod, ModOrUse);
9331
9332 SemaRef.Diag(Mod->getExprLoc(),
9333 IsModMod ? diag::warn_unsequenced_mod_mod
9334 : diag::warn_unsequenced_mod_use)
9335 << O << SourceRange(ModOrUse->getExprLoc());
9336 UI.Diagnosed = true;
9337 }
9338
9339 void notePreUse(Object O, Expr *Use) {
9340 UsageInfo &U = UsageMap[O];
9341 // Uses conflict with other modifications.
9342 checkUsage(O, U, Use, UK_ModAsValue, false);
9343 }
9344 void notePostUse(Object O, Expr *Use) {
9345 UsageInfo &U = UsageMap[O];
9346 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
9347 addUsage(U, O, Use, UK_Use);
9348 }
9349
9350 void notePreMod(Object O, Expr *Mod) {
9351 UsageInfo &U = UsageMap[O];
9352 // Modifications conflict with other modifications and with uses.
9353 checkUsage(O, U, Mod, UK_ModAsValue, true);
9354 checkUsage(O, U, Mod, UK_Use, false);
9355 }
9356 void notePostMod(Object O, Expr *Use, UsageKind UK) {
9357 UsageInfo &U = UsageMap[O];
9358 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
9359 addUsage(U, O, Use, UK);
9360 }
9361
9362public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009363 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +00009364 : Base(S.Context), SemaRef(S), Region(Tree.root()),
9365 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +00009366 Visit(E);
9367 }
9368
9369 void VisitStmt(Stmt *S) {
9370 // Skip all statements which aren't expressions for now.
9371 }
9372
9373 void VisitExpr(Expr *E) {
9374 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00009375 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00009376 }
9377
9378 void VisitCastExpr(CastExpr *E) {
9379 Object O = Object();
9380 if (E->getCastKind() == CK_LValueToRValue)
9381 O = getObject(E->getSubExpr(), false);
9382
9383 if (O)
9384 notePreUse(O, E);
9385 VisitExpr(E);
9386 if (O)
9387 notePostUse(O, E);
9388 }
9389
9390 void VisitBinComma(BinaryOperator *BO) {
9391 // C++11 [expr.comma]p1:
9392 // Every value computation and side effect associated with the left
9393 // expression is sequenced before every value computation and side
9394 // effect associated with the right expression.
9395 SequenceTree::Seq LHS = Tree.allocate(Region);
9396 SequenceTree::Seq RHS = Tree.allocate(Region);
9397 SequenceTree::Seq OldRegion = Region;
9398
9399 {
9400 SequencedSubexpression SeqLHS(*this);
9401 Region = LHS;
9402 Visit(BO->getLHS());
9403 }
9404
9405 Region = RHS;
9406 Visit(BO->getRHS());
9407
9408 Region = OldRegion;
9409
9410 // Forget that LHS and RHS are sequenced. They are both unsequenced
9411 // with respect to other stuff.
9412 Tree.merge(LHS);
9413 Tree.merge(RHS);
9414 }
9415
9416 void VisitBinAssign(BinaryOperator *BO) {
9417 // The modification is sequenced after the value computation of the LHS
9418 // and RHS, so check it before inspecting the operands and update the
9419 // map afterwards.
9420 Object O = getObject(BO->getLHS(), true);
9421 if (!O)
9422 return VisitExpr(BO);
9423
9424 notePreMod(O, BO);
9425
9426 // C++11 [expr.ass]p7:
9427 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
9428 // only once.
9429 //
9430 // Therefore, for a compound assignment operator, O is considered used
9431 // everywhere except within the evaluation of E1 itself.
9432 if (isa<CompoundAssignOperator>(BO))
9433 notePreUse(O, BO);
9434
9435 Visit(BO->getLHS());
9436
9437 if (isa<CompoundAssignOperator>(BO))
9438 notePostUse(O, BO);
9439
9440 Visit(BO->getRHS());
9441
Richard Smith83e37bee2013-06-26 23:16:51 +00009442 // C++11 [expr.ass]p1:
9443 // the assignment is sequenced [...] before the value computation of the
9444 // assignment expression.
9445 // C11 6.5.16/3 has no such rule.
9446 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
9447 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00009448 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009449
Richard Smithc406cb72013-01-17 01:17:56 +00009450 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
9451 VisitBinAssign(CAO);
9452 }
9453
9454 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
9455 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
9456 void VisitUnaryPreIncDec(UnaryOperator *UO) {
9457 Object O = getObject(UO->getSubExpr(), true);
9458 if (!O)
9459 return VisitExpr(UO);
9460
9461 notePreMod(O, UO);
9462 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +00009463 // C++11 [expr.pre.incr]p1:
9464 // the expression ++x is equivalent to x+=1
9465 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
9466 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00009467 }
9468
9469 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
9470 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
9471 void VisitUnaryPostIncDec(UnaryOperator *UO) {
9472 Object O = getObject(UO->getSubExpr(), true);
9473 if (!O)
9474 return VisitExpr(UO);
9475
9476 notePreMod(O, UO);
9477 Visit(UO->getSubExpr());
9478 notePostMod(O, UO, UK_ModAsSideEffect);
9479 }
9480
9481 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
9482 void VisitBinLOr(BinaryOperator *BO) {
9483 // The side-effects of the LHS of an '&&' are sequenced before the
9484 // value computation of the RHS, and hence before the value computation
9485 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
9486 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +00009487 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00009488 {
9489 SequencedSubexpression Sequenced(*this);
9490 Visit(BO->getLHS());
9491 }
9492
9493 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00009494 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00009495 if (!Result)
9496 Visit(BO->getRHS());
9497 } else {
9498 // Check for unsequenced operations in the RHS, treating it as an
9499 // entirely separate evaluation.
9500 //
9501 // FIXME: If there are operations in the RHS which are unsequenced
9502 // with respect to operations outside the RHS, and those operations
9503 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +00009504 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00009505 }
Richard Smithc406cb72013-01-17 01:17:56 +00009506 }
9507 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +00009508 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00009509 {
9510 SequencedSubexpression Sequenced(*this);
9511 Visit(BO->getLHS());
9512 }
9513
9514 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00009515 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00009516 if (Result)
9517 Visit(BO->getRHS());
9518 } else {
Richard Smithd33f5202013-01-17 23:18:09 +00009519 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00009520 }
Richard Smithc406cb72013-01-17 01:17:56 +00009521 }
9522
9523 // Only visit the condition, unless we can be sure which subexpression will
9524 // be chosen.
9525 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +00009526 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +00009527 {
9528 SequencedSubexpression Sequenced(*this);
9529 Visit(CO->getCond());
9530 }
Richard Smithc406cb72013-01-17 01:17:56 +00009531
9532 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00009533 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +00009534 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00009535 else {
Richard Smithd33f5202013-01-17 23:18:09 +00009536 WorkList.push_back(CO->getTrueExpr());
9537 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00009538 }
Richard Smithc406cb72013-01-17 01:17:56 +00009539 }
9540
Richard Smithe3dbfe02013-06-30 10:40:20 +00009541 void VisitCallExpr(CallExpr *CE) {
9542 // C++11 [intro.execution]p15:
9543 // When calling a function [...], every value computation and side effect
9544 // associated with any argument expression, or with the postfix expression
9545 // designating the called function, is sequenced before execution of every
9546 // expression or statement in the body of the function [and thus before
9547 // the value computation of its result].
9548 SequencedSubexpression Sequenced(*this);
9549 Base::VisitCallExpr(CE);
9550
9551 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
9552 }
9553
Richard Smithc406cb72013-01-17 01:17:56 +00009554 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +00009555 // This is a call, so all subexpressions are sequenced before the result.
9556 SequencedSubexpression Sequenced(*this);
9557
Richard Smithc406cb72013-01-17 01:17:56 +00009558 if (!CCE->isListInitialization())
9559 return VisitExpr(CCE);
9560
9561 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009562 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00009563 SequenceTree::Seq Parent = Region;
9564 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
9565 E = CCE->arg_end();
9566 I != E; ++I) {
9567 Region = Tree.allocate(Parent);
9568 Elts.push_back(Region);
9569 Visit(*I);
9570 }
9571
9572 // Forget that the initializers are sequenced.
9573 Region = Parent;
9574 for (unsigned I = 0; I < Elts.size(); ++I)
9575 Tree.merge(Elts[I]);
9576 }
9577
9578 void VisitInitListExpr(InitListExpr *ILE) {
9579 if (!SemaRef.getLangOpts().CPlusPlus11)
9580 return VisitExpr(ILE);
9581
9582 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009583 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00009584 SequenceTree::Seq Parent = Region;
9585 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
9586 Expr *E = ILE->getInit(I);
9587 if (!E) continue;
9588 Region = Tree.allocate(Parent);
9589 Elts.push_back(Region);
9590 Visit(E);
9591 }
9592
9593 // Forget that the initializers are sequenced.
9594 Region = Parent;
9595 for (unsigned I = 0; I < Elts.size(); ++I)
9596 Tree.merge(Elts[I]);
9597 }
9598};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009599} // end anonymous namespace
Richard Smithc406cb72013-01-17 01:17:56 +00009600
9601void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009602 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +00009603 WorkList.push_back(E);
9604 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00009605 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +00009606 SequenceChecker(*this, Item, WorkList);
9607 }
Richard Smithc406cb72013-01-17 01:17:56 +00009608}
9609
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009610void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
9611 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +00009612 CheckImplicitConversions(E, CheckLoc);
Richard Trieu71d74d42016-08-05 21:02:34 +00009613 if (!E->isInstantiationDependent())
9614 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009615 if (!IsConstexpr && !E->isValueDependent())
9616 CheckForIntOverflow(E);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +00009617 DiagnoseMisalignedMembers();
Richard Smithc406cb72013-01-17 01:17:56 +00009618}
9619
John McCall1f425642010-11-11 03:21:53 +00009620void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
9621 FieldDecl *BitField,
9622 Expr *Init) {
9623 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
9624}
9625
David Majnemer61a5bbf2015-04-07 22:08:51 +00009626static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
9627 SourceLocation Loc) {
9628 if (!PType->isVariablyModifiedType())
9629 return;
9630 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
9631 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
9632 return;
9633 }
David Majnemerdf8f73f2015-04-09 19:53:25 +00009634 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
9635 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
9636 return;
9637 }
David Majnemer61a5bbf2015-04-07 22:08:51 +00009638 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
9639 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
9640 return;
9641 }
9642
9643 const ArrayType *AT = S.Context.getAsArrayType(PType);
9644 if (!AT)
9645 return;
9646
9647 if (AT->getSizeModifier() != ArrayType::Star) {
9648 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
9649 return;
9650 }
9651
9652 S.Diag(Loc, diag::err_array_star_in_function_definition);
9653}
9654
Mike Stump0c2ec772010-01-21 03:59:47 +00009655/// CheckParmsForFunctionDef - Check that the parameters of the given
9656/// function are appropriate for the definition of a function. This
9657/// takes care of any checks that cannot be performed on the
9658/// declaration itself, e.g., that the types of each of the function
9659/// parameters are complete.
David Majnemer59f77922016-06-24 04:05:48 +00009660bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
Douglas Gregorb524d902010-11-01 18:37:59 +00009661 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +00009662 bool HasInvalidParm = false;
David Majnemer59f77922016-06-24 04:05:48 +00009663 for (ParmVarDecl *Param : Parameters) {
Mike Stump0c2ec772010-01-21 03:59:47 +00009664 // C99 6.7.5.3p4: the parameters in a parameter type list in a
9665 // function declarator that is part of a function definition of
9666 // that function shall not have incomplete type.
9667 //
9668 // This is also C++ [dcl.fct]p6.
9669 if (!Param->isInvalidDecl() &&
9670 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00009671 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +00009672 Param->setInvalidDecl();
9673 HasInvalidParm = true;
9674 }
9675
9676 // C99 6.9.1p5: If the declarator includes a parameter type list, the
9677 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +00009678 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +00009679 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +00009680 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00009681 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +00009682 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +00009683
9684 // C99 6.7.5.3p12:
9685 // If the function declarator is not part of a definition of that
9686 // function, parameters may have incomplete type and may use the [*]
9687 // notation in their sequences of declarator specifiers to specify
9688 // variable length array types.
9689 QualType PType = Param->getOriginalType();
David Majnemer61a5bbf2015-04-07 22:08:51 +00009690 // FIXME: This diagnostic should point the '[*]' if source-location
9691 // information is added for it.
9692 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00009693
9694 // MSVC destroys objects passed by value in the callee. Therefore a
9695 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00009696 // object's destructor. However, we don't perform any direct access check
9697 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +00009698 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
9699 .getCXXABI()
9700 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +00009701 if (!Param->isInvalidDecl()) {
9702 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
9703 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
9704 if (!ClassDecl->isInvalidDecl() &&
9705 !ClassDecl->hasIrrelevantDestructor() &&
9706 !ClassDecl->isDependentContext()) {
9707 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
9708 MarkFunctionReferenced(Param->getLocation(), Destructor);
9709 DiagnoseUseOfDecl(Destructor, Param->getLocation());
9710 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00009711 }
9712 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00009713 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009714
9715 // Parameters with the pass_object_size attribute only need to be marked
9716 // constant at function definitions. Because we lack information about
9717 // whether we're on a declaration or definition when we're instantiating the
9718 // attribute, we need to check for constness here.
9719 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
9720 if (!Param->getType().isConstQualified())
9721 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
9722 << Attr->getSpelling() << 1;
Mike Stump0c2ec772010-01-21 03:59:47 +00009723 }
9724
9725 return HasInvalidParm;
9726}
John McCall2b5c1b22010-08-12 21:44:57 +00009727
9728/// CheckCastAlign - Implements -Wcast-align, which warns when a
9729/// pointer cast increases the alignment requirements.
9730void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
9731 // This is actually a lot of work to potentially be doing on every
9732 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009733 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +00009734 return;
9735
9736 // Ignore dependent types.
9737 if (T->isDependentType() || Op->getType()->isDependentType())
9738 return;
9739
9740 // Require that the destination be a pointer type.
9741 const PointerType *DestPtr = T->getAs<PointerType>();
9742 if (!DestPtr) return;
9743
9744 // If the destination has alignment 1, we're done.
9745 QualType DestPointee = DestPtr->getPointeeType();
9746 if (DestPointee->isIncompleteType()) return;
9747 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
9748 if (DestAlign.isOne()) return;
9749
9750 // Require that the source be a pointer type.
9751 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
9752 if (!SrcPtr) return;
9753 QualType SrcPointee = SrcPtr->getPointeeType();
9754
9755 // Whitelist casts from cv void*. We already implicitly
9756 // whitelisted casts to cv void*, since they have alignment 1.
9757 // Also whitelist casts involving incomplete types, which implicitly
9758 // includes 'void'.
9759 if (SrcPointee->isIncompleteType()) return;
9760
9761 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
9762 if (SrcAlign >= DestAlign) return;
9763
9764 Diag(TRange.getBegin(), diag::warn_cast_align)
9765 << Op->getType() << T
9766 << static_cast<unsigned>(SrcAlign.getQuantity())
9767 << static_cast<unsigned>(DestAlign.getQuantity())
9768 << TRange << Op->getSourceRange();
9769}
9770
Chandler Carruth28389f02011-08-05 09:10:50 +00009771/// \brief Check whether this array fits the idiom of a size-one tail padded
9772/// array member of a struct.
9773///
9774/// We avoid emitting out-of-bounds access warnings for such arrays as they are
9775/// commonly used to emulate flexible arrays in C89 code.
Benjamin Kramer7320b992016-06-15 14:20:56 +00009776static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
Chandler Carruth28389f02011-08-05 09:10:50 +00009777 const NamedDecl *ND) {
9778 if (Size != 1 || !ND) return false;
9779
9780 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
9781 if (!FD) return false;
9782
9783 // Don't consider sizes resulting from macro expansions or template argument
9784 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +00009785
9786 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00009787 while (TInfo) {
9788 TypeLoc TL = TInfo->getTypeLoc();
9789 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +00009790 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
9791 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00009792 TInfo = TDL->getTypeSourceInfo();
9793 continue;
9794 }
David Blaikie6adc78e2013-02-18 22:06:02 +00009795 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
9796 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +00009797 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
9798 return false;
9799 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +00009800 break;
Sean Callanan06a48a62012-05-04 18:22:53 +00009801 }
Chandler Carruth28389f02011-08-05 09:10:50 +00009802
9803 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +00009804 if (!RD) return false;
9805 if (RD->isUnion()) return false;
9806 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
9807 if (!CRD->isStandardLayout()) return false;
9808 }
Chandler Carruth28389f02011-08-05 09:10:50 +00009809
Benjamin Kramer8c543672011-08-06 03:04:42 +00009810 // See if this is the last field decl in the record.
9811 const Decl *D = FD;
9812 while ((D = D->getNextDeclInContext()))
9813 if (isa<FieldDecl>(D))
9814 return false;
9815 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +00009816}
9817
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009818void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009819 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +00009820 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +00009821 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009822 if (IndexExpr->isValueDependent())
9823 return;
9824
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00009825 const Type *EffectiveType =
9826 BaseExpr->getType()->getPointeeOrArrayElementType();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009827 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009828 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009829 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009830 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +00009831 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +00009832
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009833 llvm::APSInt index;
Richard Smith0c6124b2015-12-03 01:36:22 +00009834 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
Ted Kremenek64699be2011-02-16 01:57:07 +00009835 return;
Richard Smith13f67182011-12-16 19:31:14 +00009836 if (IndexNegated)
9837 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +00009838
Craig Topperc3ec1492014-05-26 06:22:03 +00009839 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +00009840 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
9841 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +00009842 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +00009843 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +00009844
Ted Kremeneke4b316c2011-02-23 23:06:04 +00009845 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00009846 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +00009847 if (!size.isStrictlyPositive())
9848 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009849
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00009850 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
Nico Weber7c299802011-09-17 22:59:41 +00009851 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009852 // Make sure we're comparing apples to apples when comparing index to size
9853 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
9854 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +00009855 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +00009856 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009857 if (ptrarith_typesize != array_typesize) {
9858 // There's a cast to a different size type involved
9859 uint64_t ratio = array_typesize / ptrarith_typesize;
9860 // TODO: Be smarter about handling cases where array_typesize is not a
9861 // multiple of ptrarith_typesize
9862 if (ptrarith_typesize * ratio == array_typesize)
9863 size *= llvm::APInt(size.getBitWidth(), ratio);
9864 }
9865 }
9866
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009867 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00009868 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00009869 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00009870 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00009871
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009872 // For array subscripting the index must be less than size, but for pointer
9873 // arithmetic also allow the index (offset) to be equal to size since
9874 // computing the next address after the end of the array is legal and
9875 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +00009876 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +00009877 return;
9878
9879 // Also don't warn for arrays of size 1 which are members of some
9880 // structure. These are often used to approximate flexible arrays in C89
9881 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009882 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +00009883 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009884
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009885 // Suppress the warning if the subscript expression (as identified by the
9886 // ']' location) and the index expression are both from macro expansions
9887 // within a system header.
9888 if (ASE) {
9889 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
9890 ASE->getRBracketLoc());
9891 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
9892 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
9893 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +00009894 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009895 return;
9896 }
9897 }
9898
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009899 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009900 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009901 DiagID = diag::warn_array_index_exceeds_bounds;
9902
9903 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
9904 PDiag(DiagID) << index.toString(10, true)
9905 << size.toString(10, true)
9906 << (unsigned)size.getLimitedValue(~0U)
9907 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009908 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009909 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009910 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009911 DiagID = diag::warn_ptr_arith_precedes_bounds;
9912 if (index.isNegative()) index = -index;
9913 }
9914
9915 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
9916 PDiag(DiagID) << index.toString(10, true)
9917 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +00009918 }
Chandler Carruth1af88f12011-02-17 21:10:52 +00009919
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +00009920 if (!ND) {
9921 // Try harder to find a NamedDecl to point at in the note.
9922 while (const ArraySubscriptExpr *ASE =
9923 dyn_cast<ArraySubscriptExpr>(BaseExpr))
9924 BaseExpr = ASE->getBase()->IgnoreParenCasts();
9925 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
9926 ND = dyn_cast<NamedDecl>(DRE->getDecl());
9927 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
9928 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
9929 }
9930
Chandler Carruth1af88f12011-02-17 21:10:52 +00009931 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009932 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
9933 PDiag(diag::note_array_index_out_of_bounds)
9934 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +00009935}
9936
Ted Kremenekdf26df72011-03-01 18:41:00 +00009937void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009938 int AllowOnePastEnd = 0;
9939 while (expr) {
9940 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +00009941 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009942 case Stmt::ArraySubscriptExprClass: {
9943 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009944 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009945 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +00009946 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009947 }
Alexey Bataev1a3320e2015-08-25 14:24:04 +00009948 case Stmt::OMPArraySectionExprClass: {
9949 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
9950 if (ASE->getLowerBound())
9951 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
9952 /*ASE=*/nullptr, AllowOnePastEnd > 0);
9953 return;
9954 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009955 case Stmt::UnaryOperatorClass: {
9956 // Only unwrap the * and & unary operators
9957 const UnaryOperator *UO = cast<UnaryOperator>(expr);
9958 expr = UO->getSubExpr();
9959 switch (UO->getOpcode()) {
9960 case UO_AddrOf:
9961 AllowOnePastEnd++;
9962 break;
9963 case UO_Deref:
9964 AllowOnePastEnd--;
9965 break;
9966 default:
9967 return;
9968 }
9969 break;
9970 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00009971 case Stmt::ConditionalOperatorClass: {
9972 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
9973 if (const Expr *lhs = cond->getLHS())
9974 CheckArrayAccess(lhs);
9975 if (const Expr *rhs = cond->getRHS())
9976 CheckArrayAccess(rhs);
9977 return;
9978 }
9979 default:
9980 return;
9981 }
Peter Collingbourne91147592011-04-15 00:35:48 +00009982 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00009983}
John McCall31168b02011-06-15 23:02:42 +00009984
9985//===--- CHECK: Objective-C retain cycles ----------------------------------//
9986
9987namespace {
9988 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +00009989 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +00009990 VarDecl *Variable;
9991 SourceRange Range;
9992 SourceLocation Loc;
9993 bool Indirect;
9994
9995 void setLocsFrom(Expr *e) {
9996 Loc = e->getExprLoc();
9997 Range = e->getSourceRange();
9998 }
9999 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010000} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +000010001
10002/// Consider whether capturing the given variable can possibly lead to
10003/// a retain cycle.
10004static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +000010005 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +000010006 // lifetime. In MRR, it's captured strongly if the variable is
10007 // __block and has an appropriate type.
10008 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
10009 return false;
10010
10011 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000010012 if (ref)
10013 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +000010014 return true;
10015}
10016
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010017static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +000010018 while (true) {
10019 e = e->IgnoreParens();
10020 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
10021 switch (cast->getCastKind()) {
10022 case CK_BitCast:
10023 case CK_LValueBitCast:
10024 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +000010025 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +000010026 e = cast->getSubExpr();
10027 continue;
10028
John McCall31168b02011-06-15 23:02:42 +000010029 default:
10030 return false;
10031 }
10032 }
10033
10034 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
10035 ObjCIvarDecl *ivar = ref->getDecl();
10036 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
10037 return false;
10038
10039 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010040 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +000010041 return false;
10042
10043 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
10044 owner.Indirect = true;
10045 return true;
10046 }
10047
10048 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
10049 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
10050 if (!var) return false;
10051 return considerVariable(var, ref, owner);
10052 }
10053
John McCall31168b02011-06-15 23:02:42 +000010054 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
10055 if (member->isArrow()) return false;
10056
10057 // Don't count this as an indirect ownership.
10058 e = member->getBase();
10059 continue;
10060 }
10061
John McCallfe96e0b2011-11-06 09:01:30 +000010062 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
10063 // Only pay attention to pseudo-objects on property references.
10064 ObjCPropertyRefExpr *pre
10065 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
10066 ->IgnoreParens());
10067 if (!pre) return false;
10068 if (pre->isImplicitProperty()) return false;
10069 ObjCPropertyDecl *property = pre->getExplicitProperty();
10070 if (!property->isRetaining() &&
10071 !(property->getPropertyIvarDecl() &&
10072 property->getPropertyIvarDecl()->getType()
10073 .getObjCLifetime() == Qualifiers::OCL_Strong))
10074 return false;
10075
10076 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010077 if (pre->isSuperReceiver()) {
10078 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
10079 if (!owner.Variable)
10080 return false;
10081 owner.Loc = pre->getLocation();
10082 owner.Range = pre->getSourceRange();
10083 return true;
10084 }
John McCallfe96e0b2011-11-06 09:01:30 +000010085 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
10086 ->getSourceExpr());
10087 continue;
10088 }
10089
John McCall31168b02011-06-15 23:02:42 +000010090 // Array ivars?
10091
10092 return false;
10093 }
10094}
10095
10096namespace {
10097 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
10098 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
10099 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000010100 Context(Context), Variable(variable), Capturer(nullptr),
10101 VarWillBeReased(false) {}
10102 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +000010103 VarDecl *Variable;
10104 Expr *Capturer;
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000010105 bool VarWillBeReased;
John McCall31168b02011-06-15 23:02:42 +000010106
10107 void VisitDeclRefExpr(DeclRefExpr *ref) {
10108 if (ref->getDecl() == Variable && !Capturer)
10109 Capturer = ref;
10110 }
10111
John McCall31168b02011-06-15 23:02:42 +000010112 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
10113 if (Capturer) return;
10114 Visit(ref->getBase());
10115 if (Capturer && ref->isFreeIvar())
10116 Capturer = ref;
10117 }
10118
10119 void VisitBlockExpr(BlockExpr *block) {
10120 // Look inside nested blocks
10121 if (block->getBlockDecl()->capturesVariable(Variable))
10122 Visit(block->getBlockDecl()->getBody());
10123 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +000010124
10125 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
10126 if (Capturer) return;
10127 if (OVE->getSourceExpr())
10128 Visit(OVE->getSourceExpr());
10129 }
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000010130 void VisitBinaryOperator(BinaryOperator *BinOp) {
10131 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
10132 return;
10133 Expr *LHS = BinOp->getLHS();
10134 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
10135 if (DRE->getDecl() != Variable)
10136 return;
10137 if (Expr *RHS = BinOp->getRHS()) {
10138 RHS = RHS->IgnoreParenCasts();
10139 llvm::APSInt Value;
10140 VarWillBeReased =
10141 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
10142 }
10143 }
10144 }
John McCall31168b02011-06-15 23:02:42 +000010145 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010146} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +000010147
10148/// Check whether the given argument is a block which captures a
10149/// variable.
10150static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
10151 assert(owner.Variable && owner.Loc.isValid());
10152
10153 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +000010154
10155 // Look through [^{...} copy] and Block_copy(^{...}).
10156 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
10157 Selector Cmd = ME->getSelector();
10158 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
10159 e = ME->getInstanceReceiver();
10160 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +000010161 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +000010162 e = e->IgnoreParenCasts();
10163 }
10164 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
10165 if (CE->getNumArgs() == 1) {
10166 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +000010167 if (Fn) {
10168 const IdentifierInfo *FnI = Fn->getIdentifier();
10169 if (FnI && FnI->isStr("_Block_copy")) {
10170 e = CE->getArg(0)->IgnoreParenCasts();
10171 }
10172 }
Jordan Rose67e887c2012-09-17 17:54:30 +000010173 }
10174 }
10175
John McCall31168b02011-06-15 23:02:42 +000010176 BlockExpr *block = dyn_cast<BlockExpr>(e);
10177 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +000010178 return nullptr;
John McCall31168b02011-06-15 23:02:42 +000010179
10180 FindCaptureVisitor visitor(S.Context, owner.Variable);
10181 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000010182 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +000010183}
10184
10185static void diagnoseRetainCycle(Sema &S, Expr *capturer,
10186 RetainCycleOwner &owner) {
10187 assert(capturer);
10188 assert(owner.Variable && owner.Loc.isValid());
10189
10190 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
10191 << owner.Variable << capturer->getSourceRange();
10192 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
10193 << owner.Indirect << owner.Range;
10194}
10195
10196/// Check for a keyword selector that starts with the word 'add' or
10197/// 'set'.
10198static bool isSetterLikeSelector(Selector sel) {
10199 if (sel.isUnarySelector()) return false;
10200
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010201 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +000010202 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +000010203 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +000010204 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +000010205 else if (str.startswith("add")) {
10206 // Specially whitelist 'addOperationWithBlock:'.
10207 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
10208 return false;
10209 str = str.substr(3);
10210 }
John McCall31168b02011-06-15 23:02:42 +000010211 else
10212 return false;
10213
10214 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +000010215 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +000010216}
10217
Benjamin Kramer3a743452015-03-09 15:03:32 +000010218static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
10219 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000010220 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
10221 Message->getReceiverInterface(),
10222 NSAPI::ClassId_NSMutableArray);
10223 if (!IsMutableArray) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010224 return None;
10225 }
10226
10227 Selector Sel = Message->getSelector();
10228
10229 Optional<NSAPI::NSArrayMethodKind> MKOpt =
10230 S.NSAPIObj->getNSArrayMethodKind(Sel);
10231 if (!MKOpt) {
10232 return None;
10233 }
10234
10235 NSAPI::NSArrayMethodKind MK = *MKOpt;
10236
10237 switch (MK) {
10238 case NSAPI::NSMutableArr_addObject:
10239 case NSAPI::NSMutableArr_insertObjectAtIndex:
10240 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
10241 return 0;
10242 case NSAPI::NSMutableArr_replaceObjectAtIndex:
10243 return 1;
10244
10245 default:
10246 return None;
10247 }
10248
10249 return None;
10250}
10251
10252static
10253Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
10254 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000010255 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
10256 Message->getReceiverInterface(),
10257 NSAPI::ClassId_NSMutableDictionary);
10258 if (!IsMutableDictionary) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010259 return None;
10260 }
10261
10262 Selector Sel = Message->getSelector();
10263
10264 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
10265 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
10266 if (!MKOpt) {
10267 return None;
10268 }
10269
10270 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
10271
10272 switch (MK) {
10273 case NSAPI::NSMutableDict_setObjectForKey:
10274 case NSAPI::NSMutableDict_setValueForKey:
10275 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
10276 return 0;
10277
10278 default:
10279 return None;
10280 }
10281
10282 return None;
10283}
10284
10285static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000010286 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
10287 Message->getReceiverInterface(),
10288 NSAPI::ClassId_NSMutableSet);
Alex Denisove1d882c2015-03-04 17:55:52 +000010289
Alex Denisov5dfac812015-08-06 04:51:14 +000010290 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
10291 Message->getReceiverInterface(),
10292 NSAPI::ClassId_NSMutableOrderedSet);
10293 if (!IsMutableSet && !IsMutableOrderedSet) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010294 return None;
10295 }
10296
10297 Selector Sel = Message->getSelector();
10298
10299 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
10300 if (!MKOpt) {
10301 return None;
10302 }
10303
10304 NSAPI::NSSetMethodKind MK = *MKOpt;
10305
10306 switch (MK) {
10307 case NSAPI::NSMutableSet_addObject:
10308 case NSAPI::NSOrderedSet_setObjectAtIndex:
10309 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
10310 case NSAPI::NSOrderedSet_insertObjectAtIndex:
10311 return 0;
10312 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
10313 return 1;
10314 }
10315
10316 return None;
10317}
10318
10319void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
10320 if (!Message->isInstanceMessage()) {
10321 return;
10322 }
10323
10324 Optional<int> ArgOpt;
10325
10326 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
10327 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
10328 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
10329 return;
10330 }
10331
10332 int ArgIndex = *ArgOpt;
10333
Alex Denisove1d882c2015-03-04 17:55:52 +000010334 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
10335 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
10336 Arg = OE->getSourceExpr()->IgnoreImpCasts();
10337 }
10338
Alex Denisov5dfac812015-08-06 04:51:14 +000010339 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010340 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
Alex Denisov5dfac812015-08-06 04:51:14 +000010341 if (ArgRE->isObjCSelfExpr()) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010342 Diag(Message->getSourceRange().getBegin(),
10343 diag::warn_objc_circular_container)
Alex Denisov5dfac812015-08-06 04:51:14 +000010344 << ArgRE->getDecl()->getName() << StringRef("super");
Alex Denisove1d882c2015-03-04 17:55:52 +000010345 }
10346 }
Alex Denisov5dfac812015-08-06 04:51:14 +000010347 } else {
10348 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
10349
10350 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
10351 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
10352 }
10353
10354 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
10355 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
10356 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
10357 ValueDecl *Decl = ReceiverRE->getDecl();
10358 Diag(Message->getSourceRange().getBegin(),
10359 diag::warn_objc_circular_container)
10360 << Decl->getName() << Decl->getName();
10361 if (!ArgRE->isObjCSelfExpr()) {
10362 Diag(Decl->getLocation(),
10363 diag::note_objc_circular_container_declared_here)
10364 << Decl->getName();
10365 }
10366 }
10367 }
10368 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
10369 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
10370 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
10371 ObjCIvarDecl *Decl = IvarRE->getDecl();
10372 Diag(Message->getSourceRange().getBegin(),
10373 diag::warn_objc_circular_container)
10374 << Decl->getName() << Decl->getName();
10375 Diag(Decl->getLocation(),
10376 diag::note_objc_circular_container_declared_here)
10377 << Decl->getName();
10378 }
Alex Denisove1d882c2015-03-04 17:55:52 +000010379 }
10380 }
10381 }
Alex Denisove1d882c2015-03-04 17:55:52 +000010382}
10383
John McCall31168b02011-06-15 23:02:42 +000010384/// Check a message send to see if it's likely to cause a retain cycle.
10385void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
10386 // Only check instance methods whose selector looks like a setter.
10387 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
10388 return;
10389
10390 // Try to find a variable that the receiver is strongly owned by.
10391 RetainCycleOwner owner;
10392 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010393 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +000010394 return;
10395 } else {
10396 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
10397 owner.Variable = getCurMethodDecl()->getSelfDecl();
10398 owner.Loc = msg->getSuperLoc();
10399 owner.Range = msg->getSuperLoc();
10400 }
10401
10402 // Check whether the receiver is captured by any of the arguments.
10403 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
10404 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
10405 return diagnoseRetainCycle(*this, capturer, owner);
10406}
10407
10408/// Check a property assign to see if it's likely to cause a retain cycle.
10409void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
10410 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010411 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +000010412 return;
10413
10414 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
10415 diagnoseRetainCycle(*this, capturer, owner);
10416}
10417
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000010418void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
10419 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +000010420 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000010421 return;
10422
10423 // Because we don't have an expression for the variable, we have to set the
10424 // location explicitly here.
10425 Owner.Loc = Var->getLocation();
10426 Owner.Range = Var->getSourceRange();
10427
10428 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
10429 diagnoseRetainCycle(*this, Capturer, Owner);
10430}
10431
Ted Kremenek9304da92012-12-21 08:04:28 +000010432static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
10433 Expr *RHS, bool isProperty) {
10434 // Check if RHS is an Objective-C object literal, which also can get
10435 // immediately zapped in a weak reference. Note that we explicitly
10436 // allow ObjCStringLiterals, since those are designed to never really die.
10437 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000010438
Ted Kremenek64873352012-12-21 22:46:35 +000010439 // This enum needs to match with the 'select' in
10440 // warn_objc_arc_literal_assign (off-by-1).
10441 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
10442 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
10443 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000010444
10445 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +000010446 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +000010447 << (isProperty ? 0 : 1)
10448 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000010449
10450 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +000010451}
10452
Ted Kremenekc1f014a2012-12-21 19:45:30 +000010453static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
10454 Qualifiers::ObjCLifetime LT,
10455 Expr *RHS, bool isProperty) {
10456 // Strip off any implicit cast added to get to the one ARC-specific.
10457 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
10458 if (cast->getCastKind() == CK_ARCConsumeObject) {
10459 S.Diag(Loc, diag::warn_arc_retained_assign)
10460 << (LT == Qualifiers::OCL_ExplicitNone)
10461 << (isProperty ? 0 : 1)
10462 << RHS->getSourceRange();
10463 return true;
10464 }
10465 RHS = cast->getSubExpr();
10466 }
10467
10468 if (LT == Qualifiers::OCL_Weak &&
10469 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
10470 return true;
10471
10472 return false;
10473}
10474
Ted Kremenekb36234d2012-12-21 08:04:20 +000010475bool Sema::checkUnsafeAssigns(SourceLocation Loc,
10476 QualType LHS, Expr *RHS) {
10477 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
10478
10479 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
10480 return false;
10481
10482 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
10483 return true;
10484
10485 return false;
10486}
10487
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010488void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
10489 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000010490 QualType LHSType;
10491 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +000010492 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000010493 ObjCPropertyRefExpr *PRE
10494 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
10495 if (PRE && !PRE->isImplicitProperty()) {
10496 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
10497 if (PD)
10498 LHSType = PD->getType();
10499 }
10500
10501 if (LHSType.isNull())
10502 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +000010503
10504 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
10505
10506 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000010507 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +000010508 getCurFunction()->markSafeWeakUse(LHS);
10509 }
10510
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010511 if (checkUnsafeAssigns(Loc, LHSType, RHS))
10512 return;
Jordan Rose657b5f42012-09-28 22:21:35 +000010513
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010514 // FIXME. Check for other life times.
10515 if (LT != Qualifiers::OCL_None)
10516 return;
10517
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000010518 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010519 if (PRE->isImplicitProperty())
10520 return;
10521 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
10522 if (!PD)
10523 return;
10524
Bill Wendling44426052012-12-20 19:22:21 +000010525 unsigned Attributes = PD->getPropertyAttributes();
10526 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000010527 // when 'assign' attribute was not explicitly specified
10528 // by user, ignore it and rely on property type itself
10529 // for lifetime info.
10530 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
10531 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
10532 LHSType->isObjCRetainableType())
10533 return;
10534
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010535 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +000010536 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010537 Diag(Loc, diag::warn_arc_retained_property_assign)
10538 << RHS->getSourceRange();
10539 return;
10540 }
10541 RHS = cast->getSubExpr();
10542 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000010543 }
Bill Wendling44426052012-12-20 19:22:21 +000010544 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +000010545 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
10546 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +000010547 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010548 }
10549}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010550
10551//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
10552
10553namespace {
10554bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
10555 SourceLocation StmtLoc,
10556 const NullStmt *Body) {
10557 // Do not warn if the body is a macro that expands to nothing, e.g:
10558 //
10559 // #define CALL(x)
10560 // if (condition)
10561 // CALL(0);
10562 //
10563 if (Body->hasLeadingEmptyMacro())
10564 return false;
10565
10566 // Get line numbers of statement and body.
10567 bool StmtLineInvalid;
Dmitri Gribenkoad80af82015-03-15 01:08:23 +000010568 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010569 &StmtLineInvalid);
10570 if (StmtLineInvalid)
10571 return false;
10572
10573 bool BodyLineInvalid;
10574 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
10575 &BodyLineInvalid);
10576 if (BodyLineInvalid)
10577 return false;
10578
10579 // Warn if null statement and body are on the same line.
10580 if (StmtLine != BodyLine)
10581 return false;
10582
10583 return true;
10584}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010585} // end anonymous namespace
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010586
10587void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
10588 const Stmt *Body,
10589 unsigned DiagID) {
10590 // Since this is a syntactic check, don't emit diagnostic for template
10591 // instantiations, this just adds noise.
10592 if (CurrentInstantiationScope)
10593 return;
10594
10595 // The body should be a null statement.
10596 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
10597 if (!NBody)
10598 return;
10599
10600 // Do the usual checks.
10601 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
10602 return;
10603
10604 Diag(NBody->getSemiLoc(), DiagID);
10605 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
10606}
10607
10608void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
10609 const Stmt *PossibleBody) {
10610 assert(!CurrentInstantiationScope); // Ensured by caller
10611
10612 SourceLocation StmtLoc;
10613 const Stmt *Body;
10614 unsigned DiagID;
10615 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
10616 StmtLoc = FS->getRParenLoc();
10617 Body = FS->getBody();
10618 DiagID = diag::warn_empty_for_body;
10619 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
10620 StmtLoc = WS->getCond()->getSourceRange().getEnd();
10621 Body = WS->getBody();
10622 DiagID = diag::warn_empty_while_body;
10623 } else
10624 return; // Neither `for' nor `while'.
10625
10626 // The body should be a null statement.
10627 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
10628 if (!NBody)
10629 return;
10630
10631 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000010632 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010633 return;
10634
10635 // Do the usual checks.
10636 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
10637 return;
10638
10639 // `for(...);' and `while(...);' are popular idioms, so in order to keep
10640 // noise level low, emit diagnostics only if for/while is followed by a
10641 // CompoundStmt, e.g.:
10642 // for (int i = 0; i < n; i++);
10643 // {
10644 // a(i);
10645 // }
10646 // or if for/while is followed by a statement with more indentation
10647 // than for/while itself:
10648 // for (int i = 0; i < n; i++);
10649 // a(i);
10650 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
10651 if (!ProbableTypo) {
10652 bool BodyColInvalid;
10653 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
10654 PossibleBody->getLocStart(),
10655 &BodyColInvalid);
10656 if (BodyColInvalid)
10657 return;
10658
10659 bool StmtColInvalid;
10660 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
10661 S->getLocStart(),
10662 &StmtColInvalid);
10663 if (StmtColInvalid)
10664 return;
10665
10666 if (BodyCol > StmtCol)
10667 ProbableTypo = true;
10668 }
10669
10670 if (ProbableTypo) {
10671 Diag(NBody->getSemiLoc(), DiagID);
10672 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
10673 }
10674}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010675
Richard Trieu36d0b2b2015-01-13 02:32:02 +000010676//===--- CHECK: Warn on self move with std::move. -------------------------===//
10677
10678/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
10679void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
10680 SourceLocation OpLoc) {
Richard Trieu36d0b2b2015-01-13 02:32:02 +000010681 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
10682 return;
10683
10684 if (!ActiveTemplateInstantiations.empty())
10685 return;
10686
10687 // Strip parens and casts away.
10688 LHSExpr = LHSExpr->IgnoreParenImpCasts();
10689 RHSExpr = RHSExpr->IgnoreParenImpCasts();
10690
10691 // Check for a call expression
10692 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
10693 if (!CE || CE->getNumArgs() != 1)
10694 return;
10695
10696 // Check for a call to std::move
10697 const FunctionDecl *FD = CE->getDirectCallee();
10698 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
10699 !FD->getIdentifier()->isStr("move"))
10700 return;
10701
10702 // Get argument from std::move
10703 RHSExpr = CE->getArg(0);
10704
10705 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
10706 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
10707
10708 // Two DeclRefExpr's, check that the decls are the same.
10709 if (LHSDeclRef && RHSDeclRef) {
10710 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
10711 return;
10712 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
10713 RHSDeclRef->getDecl()->getCanonicalDecl())
10714 return;
10715
10716 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
10717 << LHSExpr->getSourceRange()
10718 << RHSExpr->getSourceRange();
10719 return;
10720 }
10721
10722 // Member variables require a different approach to check for self moves.
10723 // MemberExpr's are the same if every nested MemberExpr refers to the same
10724 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
10725 // the base Expr's are CXXThisExpr's.
10726 const Expr *LHSBase = LHSExpr;
10727 const Expr *RHSBase = RHSExpr;
10728 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
10729 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
10730 if (!LHSME || !RHSME)
10731 return;
10732
10733 while (LHSME && RHSME) {
10734 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
10735 RHSME->getMemberDecl()->getCanonicalDecl())
10736 return;
10737
10738 LHSBase = LHSME->getBase();
10739 RHSBase = RHSME->getBase();
10740 LHSME = dyn_cast<MemberExpr>(LHSBase);
10741 RHSME = dyn_cast<MemberExpr>(RHSBase);
10742 }
10743
10744 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
10745 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
10746 if (LHSDeclRef && RHSDeclRef) {
10747 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
10748 return;
10749 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
10750 RHSDeclRef->getDecl()->getCanonicalDecl())
10751 return;
10752
10753 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
10754 << LHSExpr->getSourceRange()
10755 << RHSExpr->getSourceRange();
10756 return;
10757 }
10758
10759 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
10760 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
10761 << LHSExpr->getSourceRange()
10762 << RHSExpr->getSourceRange();
10763}
10764
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010765//===--- Layout compatibility ----------------------------------------------//
10766
10767namespace {
10768
10769bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
10770
10771/// \brief Check if two enumeration types are layout-compatible.
10772bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
10773 // C++11 [dcl.enum] p8:
10774 // Two enumeration types are layout-compatible if they have the same
10775 // underlying type.
10776 return ED1->isComplete() && ED2->isComplete() &&
10777 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
10778}
10779
10780/// \brief Check if two fields are layout-compatible.
10781bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
10782 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
10783 return false;
10784
10785 if (Field1->isBitField() != Field2->isBitField())
10786 return false;
10787
10788 if (Field1->isBitField()) {
10789 // Make sure that the bit-fields are the same length.
10790 unsigned Bits1 = Field1->getBitWidthValue(C);
10791 unsigned Bits2 = Field2->getBitWidthValue(C);
10792
10793 if (Bits1 != Bits2)
10794 return false;
10795 }
10796
10797 return true;
10798}
10799
10800/// \brief Check if two standard-layout structs are layout-compatible.
10801/// (C++11 [class.mem] p17)
10802bool isLayoutCompatibleStruct(ASTContext &C,
10803 RecordDecl *RD1,
10804 RecordDecl *RD2) {
10805 // If both records are C++ classes, check that base classes match.
10806 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
10807 // If one of records is a CXXRecordDecl we are in C++ mode,
10808 // thus the other one is a CXXRecordDecl, too.
10809 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
10810 // Check number of base classes.
10811 if (D1CXX->getNumBases() != D2CXX->getNumBases())
10812 return false;
10813
10814 // Check the base classes.
10815 for (CXXRecordDecl::base_class_const_iterator
10816 Base1 = D1CXX->bases_begin(),
10817 BaseEnd1 = D1CXX->bases_end(),
10818 Base2 = D2CXX->bases_begin();
10819 Base1 != BaseEnd1;
10820 ++Base1, ++Base2) {
10821 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
10822 return false;
10823 }
10824 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
10825 // If only RD2 is a C++ class, it should have zero base classes.
10826 if (D2CXX->getNumBases() > 0)
10827 return false;
10828 }
10829
10830 // Check the fields.
10831 RecordDecl::field_iterator Field2 = RD2->field_begin(),
10832 Field2End = RD2->field_end(),
10833 Field1 = RD1->field_begin(),
10834 Field1End = RD1->field_end();
10835 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
10836 if (!isLayoutCompatible(C, *Field1, *Field2))
10837 return false;
10838 }
10839 if (Field1 != Field1End || Field2 != Field2End)
10840 return false;
10841
10842 return true;
10843}
10844
10845/// \brief Check if two standard-layout unions are layout-compatible.
10846/// (C++11 [class.mem] p18)
10847bool isLayoutCompatibleUnion(ASTContext &C,
10848 RecordDecl *RD1,
10849 RecordDecl *RD2) {
10850 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010851 for (auto *Field2 : RD2->fields())
10852 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010853
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010854 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010855 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
10856 I = UnmatchedFields.begin(),
10857 E = UnmatchedFields.end();
10858
10859 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010860 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010861 bool Result = UnmatchedFields.erase(*I);
10862 (void) Result;
10863 assert(Result);
10864 break;
10865 }
10866 }
10867 if (I == E)
10868 return false;
10869 }
10870
10871 return UnmatchedFields.empty();
10872}
10873
10874bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
10875 if (RD1->isUnion() != RD2->isUnion())
10876 return false;
10877
10878 if (RD1->isUnion())
10879 return isLayoutCompatibleUnion(C, RD1, RD2);
10880 else
10881 return isLayoutCompatibleStruct(C, RD1, RD2);
10882}
10883
10884/// \brief Check if two types are layout-compatible in C++11 sense.
10885bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
10886 if (T1.isNull() || T2.isNull())
10887 return false;
10888
10889 // C++11 [basic.types] p11:
10890 // If two types T1 and T2 are the same type, then T1 and T2 are
10891 // layout-compatible types.
10892 if (C.hasSameType(T1, T2))
10893 return true;
10894
10895 T1 = T1.getCanonicalType().getUnqualifiedType();
10896 T2 = T2.getCanonicalType().getUnqualifiedType();
10897
10898 const Type::TypeClass TC1 = T1->getTypeClass();
10899 const Type::TypeClass TC2 = T2->getTypeClass();
10900
10901 if (TC1 != TC2)
10902 return false;
10903
10904 if (TC1 == Type::Enum) {
10905 return isLayoutCompatible(C,
10906 cast<EnumType>(T1)->getDecl(),
10907 cast<EnumType>(T2)->getDecl());
10908 } else if (TC1 == Type::Record) {
10909 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
10910 return false;
10911
10912 return isLayoutCompatible(C,
10913 cast<RecordType>(T1)->getDecl(),
10914 cast<RecordType>(T2)->getDecl());
10915 }
10916
10917 return false;
10918}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010919} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010920
10921//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
10922
10923namespace {
10924/// \brief Given a type tag expression find the type tag itself.
10925///
10926/// \param TypeExpr Type tag expression, as it appears in user's code.
10927///
10928/// \param VD Declaration of an identifier that appears in a type tag.
10929///
10930/// \param MagicValue Type tag magic value.
10931bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
10932 const ValueDecl **VD, uint64_t *MagicValue) {
10933 while(true) {
10934 if (!TypeExpr)
10935 return false;
10936
10937 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
10938
10939 switch (TypeExpr->getStmtClass()) {
10940 case Stmt::UnaryOperatorClass: {
10941 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
10942 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
10943 TypeExpr = UO->getSubExpr();
10944 continue;
10945 }
10946 return false;
10947 }
10948
10949 case Stmt::DeclRefExprClass: {
10950 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
10951 *VD = DRE->getDecl();
10952 return true;
10953 }
10954
10955 case Stmt::IntegerLiteralClass: {
10956 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
10957 llvm::APInt MagicValueAPInt = IL->getValue();
10958 if (MagicValueAPInt.getActiveBits() <= 64) {
10959 *MagicValue = MagicValueAPInt.getZExtValue();
10960 return true;
10961 } else
10962 return false;
10963 }
10964
10965 case Stmt::BinaryConditionalOperatorClass:
10966 case Stmt::ConditionalOperatorClass: {
10967 const AbstractConditionalOperator *ACO =
10968 cast<AbstractConditionalOperator>(TypeExpr);
10969 bool Result;
10970 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
10971 if (Result)
10972 TypeExpr = ACO->getTrueExpr();
10973 else
10974 TypeExpr = ACO->getFalseExpr();
10975 continue;
10976 }
10977 return false;
10978 }
10979
10980 case Stmt::BinaryOperatorClass: {
10981 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
10982 if (BO->getOpcode() == BO_Comma) {
10983 TypeExpr = BO->getRHS();
10984 continue;
10985 }
10986 return false;
10987 }
10988
10989 default:
10990 return false;
10991 }
10992 }
10993}
10994
10995/// \brief Retrieve the C type corresponding to type tag TypeExpr.
10996///
10997/// \param TypeExpr Expression that specifies a type tag.
10998///
10999/// \param MagicValues Registered magic values.
11000///
11001/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
11002/// kind.
11003///
11004/// \param TypeInfo Information about the corresponding C type.
11005///
11006/// \returns true if the corresponding C type was found.
11007bool GetMatchingCType(
11008 const IdentifierInfo *ArgumentKind,
11009 const Expr *TypeExpr, const ASTContext &Ctx,
11010 const llvm::DenseMap<Sema::TypeTagMagicValue,
11011 Sema::TypeTagData> *MagicValues,
11012 bool &FoundWrongKind,
11013 Sema::TypeTagData &TypeInfo) {
11014 FoundWrongKind = false;
11015
11016 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +000011017 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011018
11019 uint64_t MagicValue;
11020
11021 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
11022 return false;
11023
11024 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +000011025 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011026 if (I->getArgumentKind() != ArgumentKind) {
11027 FoundWrongKind = true;
11028 return false;
11029 }
11030 TypeInfo.Type = I->getMatchingCType();
11031 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
11032 TypeInfo.MustBeNull = I->getMustBeNull();
11033 return true;
11034 }
11035 return false;
11036 }
11037
11038 if (!MagicValues)
11039 return false;
11040
11041 llvm::DenseMap<Sema::TypeTagMagicValue,
11042 Sema::TypeTagData>::const_iterator I =
11043 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
11044 if (I == MagicValues->end())
11045 return false;
11046
11047 TypeInfo = I->second;
11048 return true;
11049}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011050} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011051
11052void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
11053 uint64_t MagicValue, QualType Type,
11054 bool LayoutCompatible,
11055 bool MustBeNull) {
11056 if (!TypeTagForDatatypeMagicValues)
11057 TypeTagForDatatypeMagicValues.reset(
11058 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
11059
11060 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
11061 (*TypeTagForDatatypeMagicValues)[Magic] =
11062 TypeTagData(Type, LayoutCompatible, MustBeNull);
11063}
11064
11065namespace {
11066bool IsSameCharType(QualType T1, QualType T2) {
11067 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
11068 if (!BT1)
11069 return false;
11070
11071 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
11072 if (!BT2)
11073 return false;
11074
11075 BuiltinType::Kind T1Kind = BT1->getKind();
11076 BuiltinType::Kind T2Kind = BT2->getKind();
11077
11078 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
11079 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
11080 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
11081 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
11082}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011083} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011084
11085void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
11086 const Expr * const *ExprArgs) {
11087 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
11088 bool IsPointerAttr = Attr->getIsPointer();
11089
11090 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
11091 bool FoundWrongKind;
11092 TypeTagData TypeInfo;
11093 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
11094 TypeTagForDatatypeMagicValues.get(),
11095 FoundWrongKind, TypeInfo)) {
11096 if (FoundWrongKind)
11097 Diag(TypeTagExpr->getExprLoc(),
11098 diag::warn_type_tag_for_datatype_wrong_kind)
11099 << TypeTagExpr->getSourceRange();
11100 return;
11101 }
11102
11103 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
11104 if (IsPointerAttr) {
11105 // Skip implicit cast of pointer to `void *' (as a function argument).
11106 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +000011107 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +000011108 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011109 ArgumentExpr = ICE->getSubExpr();
11110 }
11111 QualType ArgumentType = ArgumentExpr->getType();
11112
11113 // Passing a `void*' pointer shouldn't trigger a warning.
11114 if (IsPointerAttr && ArgumentType->isVoidPointerType())
11115 return;
11116
11117 if (TypeInfo.MustBeNull) {
11118 // Type tag with matching void type requires a null pointer.
11119 if (!ArgumentExpr->isNullPointerConstant(Context,
11120 Expr::NPC_ValueDependentIsNotNull)) {
11121 Diag(ArgumentExpr->getExprLoc(),
11122 diag::warn_type_safety_null_pointer_required)
11123 << ArgumentKind->getName()
11124 << ArgumentExpr->getSourceRange()
11125 << TypeTagExpr->getSourceRange();
11126 }
11127 return;
11128 }
11129
11130 QualType RequiredType = TypeInfo.Type;
11131 if (IsPointerAttr)
11132 RequiredType = Context.getPointerType(RequiredType);
11133
11134 bool mismatch = false;
11135 if (!TypeInfo.LayoutCompatible) {
11136 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
11137
11138 // C++11 [basic.fundamental] p1:
11139 // Plain char, signed char, and unsigned char are three distinct types.
11140 //
11141 // But we treat plain `char' as equivalent to `signed char' or `unsigned
11142 // char' depending on the current char signedness mode.
11143 if (mismatch)
11144 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
11145 RequiredType->getPointeeType())) ||
11146 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
11147 mismatch = false;
11148 } else
11149 if (IsPointerAttr)
11150 mismatch = !isLayoutCompatible(Context,
11151 ArgumentType->getPointeeType(),
11152 RequiredType->getPointeeType());
11153 else
11154 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
11155
11156 if (mismatch)
11157 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +000011158 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011159 << TypeInfo.LayoutCompatible << RequiredType
11160 << ArgumentExpr->getSourceRange()
11161 << TypeTagExpr->getSourceRange();
11162}
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011163
11164void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
11165 CharUnits Alignment) {
11166 MisalignedMembers.emplace_back(E, RD, MD, Alignment);
11167}
11168
11169void Sema::DiagnoseMisalignedMembers() {
11170 for (MisalignedMember &m : MisalignedMembers) {
11171 Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member)
11172 << m.MD << m.RD << m.E->getSourceRange();
11173 }
11174 MisalignedMembers.clear();
11175}
11176
11177void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
11178 if (!T->isPointerType())
11179 return;
11180 if (isa<UnaryOperator>(E) &&
11181 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
11182 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
11183 if (isa<MemberExpr>(Op)) {
11184 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
11185 MisalignedMember(Op));
11186 if (MA != MisalignedMembers.end() &&
11187 Context.getTypeAlignInChars(T->getPointeeType()) <= MA->Alignment)
11188 MisalignedMembers.erase(MA);
11189 }
11190 }
11191}
11192
11193void Sema::RefersToMemberWithReducedAlignment(
11194 Expr *E,
11195 std::function<void(Expr *, RecordDecl *, ValueDecl *, CharUnits)> Action) {
11196 const auto *ME = dyn_cast<MemberExpr>(E);
11197 while (ME && isa<FieldDecl>(ME->getMemberDecl())) {
11198 QualType BaseType = ME->getBase()->getType();
11199 if (ME->isArrow())
11200 BaseType = BaseType->getPointeeType();
11201 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
11202
11203 ValueDecl *MD = ME->getMemberDecl();
11204 bool ByteAligned = Context.getTypeAlignInChars(MD->getType()).isOne();
11205 if (ByteAligned) // Attribute packed does not have any effect.
11206 break;
11207
11208 if (!ByteAligned &&
11209 (RD->hasAttr<PackedAttr>() || (MD->hasAttr<PackedAttr>()))) {
11210 CharUnits Alignment = std::min(Context.getTypeAlignInChars(MD->getType()),
11211 Context.getTypeAlignInChars(BaseType));
11212 // Notify that this expression designates a member with reduced alignment
11213 Action(E, RD, MD, Alignment);
11214 break;
11215 }
11216 ME = dyn_cast<MemberExpr>(ME->getBase());
11217 }
11218}
11219
11220void Sema::CheckAddressOfPackedMember(Expr *rhs) {
11221 using namespace std::placeholders;
11222 RefersToMemberWithReducedAlignment(
11223 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
11224 _2, _3, _4));
11225}
11226