blob: c7487e28d3d2d3cfcb29b4cdd977b974b98bd25d [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.
Richard Smith51ec0cf2017-02-21 01:17:38 +0000247 if (SemaRef.inTemplateInstantiation())
Reid Kleckner1d59f992015-01-22 01:36:17 +0000248 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(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000312 diag::err_opencl_builtin_expected_type)
313 << TheCall->getDirectCallee() << "block";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000314 return true;
315 }
316 return checkOpenCLBlockArgs(S, BlockArg);
317}
318
Simon Pilgrim2c518802017-03-30 14:13:19 +0000319/// Diagnose integer type and any valid implicit conversion to it.
Anastasia Stulova0df4ac32016-11-14 17:39:58 +0000320static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
321 const QualType &IntType);
322
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000323static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
Anastasia Stulova0df4ac32016-11-14 17:39:58 +0000324 unsigned Start, unsigned End) {
325 bool IllegalParams = false;
326 for (unsigned I = Start; I <= End; ++I)
327 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
328 S.Context.getSizeType());
329 return IllegalParams;
330}
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000331
332/// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
333/// 'local void*' parameter of passed block.
334static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
335 Expr *BlockArg,
336 unsigned NumNonVarArgs) {
337 const BlockPointerType *BPT =
338 cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
339 unsigned NumBlockParams =
340 BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams();
341 unsigned TotalNumArgs = TheCall->getNumArgs();
342
343 // For each argument passed to the block, a corresponding uint needs to
344 // be passed to describe the size of the local memory.
345 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
346 S.Diag(TheCall->getLocStart(),
347 diag::err_opencl_enqueue_kernel_local_size_args);
348 return true;
349 }
350
351 // Check that the sizes of the local memory are specified by integers.
352 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
353 TotalNumArgs - 1);
354}
355
356/// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
357/// overload formats specified in Table 6.13.17.1.
358/// int enqueue_kernel(queue_t queue,
359/// kernel_enqueue_flags_t flags,
360/// const ndrange_t ndrange,
361/// void (^block)(void))
362/// int enqueue_kernel(queue_t queue,
363/// kernel_enqueue_flags_t flags,
364/// const ndrange_t ndrange,
365/// uint num_events_in_wait_list,
366/// clk_event_t *event_wait_list,
367/// clk_event_t *event_ret,
368/// void (^block)(void))
369/// int enqueue_kernel(queue_t queue,
370/// kernel_enqueue_flags_t flags,
371/// const ndrange_t ndrange,
372/// void (^block)(local void*, ...),
373/// uint size0, ...)
374/// int enqueue_kernel(queue_t queue,
375/// kernel_enqueue_flags_t flags,
376/// const ndrange_t ndrange,
377/// uint num_events_in_wait_list,
378/// clk_event_t *event_wait_list,
379/// clk_event_t *event_ret,
380/// void (^block)(local void*, ...),
381/// uint size0, ...)
382static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
383 unsigned NumArgs = TheCall->getNumArgs();
384
385 if (NumArgs < 4) {
386 S.Diag(TheCall->getLocStart(), diag::err_typecheck_call_too_few_args);
387 return true;
388 }
389
390 Expr *Arg0 = TheCall->getArg(0);
391 Expr *Arg1 = TheCall->getArg(1);
392 Expr *Arg2 = TheCall->getArg(2);
393 Expr *Arg3 = TheCall->getArg(3);
394
395 // First argument always needs to be a queue_t type.
396 if (!Arg0->getType()->isQueueT()) {
397 S.Diag(TheCall->getArg(0)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000398 diag::err_opencl_builtin_expected_type)
399 << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000400 return true;
401 }
402
403 // Second argument always needs to be a kernel_enqueue_flags_t enum value.
404 if (!Arg1->getType()->isIntegerType()) {
405 S.Diag(TheCall->getArg(1)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000406 diag::err_opencl_builtin_expected_type)
407 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000408 return true;
409 }
410
411 // Third argument is always an ndrange_t type.
Anastasia Stulovab42f3c02017-04-21 15:13:24 +0000412 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000413 S.Diag(TheCall->getArg(2)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000414 diag::err_opencl_builtin_expected_type)
415 << TheCall->getDirectCallee() << "'ndrange_t'";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000416 return true;
417 }
418
419 // With four arguments, there is only one form that the function could be
420 // called in: no events and no variable arguments.
421 if (NumArgs == 4) {
422 // check that the last argument is the right block type.
423 if (!isBlockPointer(Arg3)) {
Joey Gouly6b03d952017-07-04 11:50:23 +0000424 S.Diag(Arg3->getLocStart(), diag::err_opencl_builtin_expected_type)
425 << TheCall->getDirectCallee() << "block";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000426 return true;
427 }
428 // we have a block type, check the prototype
429 const BlockPointerType *BPT =
430 cast<BlockPointerType>(Arg3->getType().getCanonicalType());
431 if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) {
432 S.Diag(Arg3->getLocStart(),
433 diag::err_opencl_enqueue_kernel_blocks_no_args);
434 return true;
435 }
436 return false;
437 }
438 // we can have block + varargs.
439 if (isBlockPointer(Arg3))
440 return (checkOpenCLBlockArgs(S, Arg3) ||
441 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
442 // last two cases with either exactly 7 args or 7 args and varargs.
443 if (NumArgs >= 7) {
444 // check common block argument.
445 Expr *Arg6 = TheCall->getArg(6);
446 if (!isBlockPointer(Arg6)) {
Joey Gouly6b03d952017-07-04 11:50:23 +0000447 S.Diag(Arg6->getLocStart(), diag::err_opencl_builtin_expected_type)
448 << TheCall->getDirectCallee() << "block";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000449 return true;
450 }
451 if (checkOpenCLBlockArgs(S, Arg6))
452 return true;
453
454 // Forth argument has to be any integer type.
455 if (!Arg3->getType()->isIntegerType()) {
456 S.Diag(TheCall->getArg(3)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000457 diag::err_opencl_builtin_expected_type)
458 << TheCall->getDirectCallee() << "integer";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000459 return true;
460 }
461 // check remaining common arguments.
462 Expr *Arg4 = TheCall->getArg(4);
463 Expr *Arg5 = TheCall->getArg(5);
464
Anastasia Stulova2b461202016-11-14 15:34:01 +0000465 // Fifth argument is always passed as a pointer to clk_event_t.
466 if (!Arg4->isNullPointerConstant(S.Context,
467 Expr::NPC_ValueDependentIsNotNull) &&
468 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000469 S.Diag(TheCall->getArg(4)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000470 diag::err_opencl_builtin_expected_type)
471 << TheCall->getDirectCallee()
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000472 << S.Context.getPointerType(S.Context.OCLClkEventTy);
473 return true;
474 }
475
Anastasia Stulova2b461202016-11-14 15:34:01 +0000476 // Sixth argument is always passed as a pointer to clk_event_t.
477 if (!Arg5->isNullPointerConstant(S.Context,
478 Expr::NPC_ValueDependentIsNotNull) &&
479 !(Arg5->getType()->isPointerType() &&
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000480 Arg5->getType()->getPointeeType()->isClkEventT())) {
481 S.Diag(TheCall->getArg(5)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000482 diag::err_opencl_builtin_expected_type)
483 << TheCall->getDirectCallee()
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000484 << S.Context.getPointerType(S.Context.OCLClkEventTy);
485 return true;
486 }
487
488 if (NumArgs == 7)
489 return false;
490
491 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
492 }
493
494 // None of the specific case has been detected, give generic error
495 S.Diag(TheCall->getLocStart(),
496 diag::err_opencl_enqueue_kernel_incorrect_args);
497 return true;
498}
499
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000500/// Returns OpenCL access qual.
Xiuli Pan11e13f62016-02-26 03:13:03 +0000501static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
Xiuli Pan11e13f62016-02-26 03:13:03 +0000502 return D->getAttr<OpenCLAccessAttr>();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000503}
504
505/// Returns true if pipe element type is different from the pointer.
506static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
507 const Expr *Arg0 = Call->getArg(0);
508 // First argument type should always be pipe.
509 if (!Arg0->getType()->isPipeType()) {
510 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000511 << Call->getDirectCallee() << Arg0->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000512 return true;
513 }
Xiuli Pan11e13f62016-02-26 03:13:03 +0000514 OpenCLAccessAttr *AccessQual =
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000515 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
516 // Validates the access qualifier is compatible with the call.
517 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
518 // read_only and write_only, and assumed to be read_only if no qualifier is
519 // specified.
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000520 switch (Call->getDirectCallee()->getBuiltinID()) {
521 case Builtin::BIread_pipe:
522 case Builtin::BIreserve_read_pipe:
523 case Builtin::BIcommit_read_pipe:
524 case Builtin::BIwork_group_reserve_read_pipe:
525 case Builtin::BIsub_group_reserve_read_pipe:
526 case Builtin::BIwork_group_commit_read_pipe:
527 case Builtin::BIsub_group_commit_read_pipe:
528 if (!(!AccessQual || AccessQual->isReadOnly())) {
529 S.Diag(Arg0->getLocStart(),
530 diag::err_opencl_builtin_pipe_invalid_access_modifier)
531 << "read_only" << Arg0->getSourceRange();
532 return true;
533 }
534 break;
535 case Builtin::BIwrite_pipe:
536 case Builtin::BIreserve_write_pipe:
537 case Builtin::BIcommit_write_pipe:
538 case Builtin::BIwork_group_reserve_write_pipe:
539 case Builtin::BIsub_group_reserve_write_pipe:
540 case Builtin::BIwork_group_commit_write_pipe:
541 case Builtin::BIsub_group_commit_write_pipe:
542 if (!(AccessQual && AccessQual->isWriteOnly())) {
543 S.Diag(Arg0->getLocStart(),
544 diag::err_opencl_builtin_pipe_invalid_access_modifier)
545 << "write_only" << Arg0->getSourceRange();
546 return true;
547 }
548 break;
549 default:
550 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000551 }
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000552 return false;
553}
554
555/// Returns true if pipe element type is different from the pointer.
556static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
557 const Expr *Arg0 = Call->getArg(0);
558 const Expr *ArgIdx = Call->getArg(Idx);
559 const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000560 const QualType EltTy = PipeTy->getElementType();
561 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000562 // The Idx argument should be a pointer and the type of the pointer and
563 // the type of pipe element should also be the same.
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000564 if (!ArgTy ||
565 !S.Context.hasSameType(
566 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000567 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000568 << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000569 << ArgIdx->getType() << ArgIdx->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000570 return true;
571 }
572 return false;
573}
574
575// \brief Performs semantic analysis for the read/write_pipe call.
576// \param S Reference to the semantic analyzer.
577// \param Call A pointer to the builtin call.
578// \return True if a semantic error has been found, false otherwise.
579static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000580 // OpenCL v2.0 s6.13.16.2 - The built-in read/write
581 // functions have two forms.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000582 switch (Call->getNumArgs()) {
583 case 2: {
584 if (checkOpenCLPipeArg(S, Call))
585 return true;
586 // The call with 2 arguments should be
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000587 // read/write_pipe(pipe T, T*).
588 // Check packet type T.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000589 if (checkOpenCLPipePacketType(S, Call, 1))
590 return true;
591 } break;
592
593 case 4: {
594 if (checkOpenCLPipeArg(S, Call))
595 return true;
596 // The call with 4 arguments should be
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000597 // read/write_pipe(pipe T, reserve_id_t, uint, T*).
598 // Check reserve_id_t.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000599 if (!Call->getArg(1)->getType()->isReserveIDT()) {
600 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000601 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000602 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000603 return true;
604 }
605
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000606 // Check the index.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000607 const Expr *Arg2 = Call->getArg(2);
608 if (!Arg2->getType()->isIntegerType() &&
609 !Arg2->getType()->isUnsignedIntegerType()) {
610 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000611 << Call->getDirectCallee() << S.Context.UnsignedIntTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000612 << Arg2->getType() << Arg2->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000613 return true;
614 }
615
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000616 // Check packet type T.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000617 if (checkOpenCLPipePacketType(S, Call, 3))
618 return true;
619 } break;
620 default:
621 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000622 << Call->getDirectCallee() << Call->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000623 return true;
624 }
625
626 return false;
627}
628
629// \brief Performs a semantic analysis on the {work_group_/sub_group_
630// /_}reserve_{read/write}_pipe
631// \param S Reference to the semantic analyzer.
632// \param Call The call to the builtin function to be analyzed.
633// \return True if a semantic error was found, false otherwise.
634static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
635 if (checkArgCount(S, Call, 2))
636 return true;
637
638 if (checkOpenCLPipeArg(S, Call))
639 return true;
640
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000641 // Check the reserve size.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000642 if (!Call->getArg(1)->getType()->isIntegerType() &&
643 !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
644 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000645 << Call->getDirectCallee() << S.Context.UnsignedIntTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000646 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000647 return true;
648 }
649
650 return false;
651}
652
653// \brief Performs a semantic analysis on {work_group_/sub_group_
654// /_}commit_{read/write}_pipe
655// \param S Reference to the semantic analyzer.
656// \param Call The call to the builtin function to be analyzed.
657// \return True if a semantic error was found, false otherwise.
658static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
659 if (checkArgCount(S, Call, 2))
660 return true;
661
662 if (checkOpenCLPipeArg(S, Call))
663 return true;
664
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000665 // Check reserve_id_t.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000666 if (!Call->getArg(1)->getType()->isReserveIDT()) {
667 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000668 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000669 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000670 return true;
671 }
672
673 return false;
674}
675
676// \brief Performs a semantic analysis on the call to built-in Pipe
677// Query Functions.
678// \param S Reference to the semantic analyzer.
679// \param Call The call to the builtin function to be analyzed.
680// \return True if a semantic error was found, false otherwise.
681static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
682 if (checkArgCount(S, Call, 1))
683 return true;
684
685 if (!Call->getArg(0)->getType()->isPipeType()) {
686 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000687 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000688 return true;
689 }
690
691 return false;
692}
Anastasia Stulova7f8d6dc2016-07-04 16:07:18 +0000693// \brief OpenCL v2.0 s6.13.9 - Address space qualifier functions.
Yaxun Liuf7449a12016-05-20 19:54:38 +0000694// \brief Performs semantic analysis for the to_global/local/private call.
695// \param S Reference to the semantic analyzer.
696// \param BuiltinID ID of the builtin function.
697// \param Call A pointer to the builtin call.
698// \return True if a semantic error has been found, false otherwise.
699static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
700 CallExpr *Call) {
Yaxun Liuf7449a12016-05-20 19:54:38 +0000701 if (Call->getNumArgs() != 1) {
702 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_arg_num)
703 << Call->getDirectCallee() << Call->getSourceRange();
704 return true;
705 }
706
707 auto RT = Call->getArg(0)->getType();
708 if (!RT->isPointerType() || RT->getPointeeType()
709 .getAddressSpace() == LangAS::opencl_constant) {
710 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg)
711 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
712 return true;
713 }
714
715 RT = RT->getPointeeType();
716 auto Qual = RT.getQualifiers();
717 switch (BuiltinID) {
718 case Builtin::BIto_global:
719 Qual.setAddressSpace(LangAS::opencl_global);
720 break;
721 case Builtin::BIto_local:
722 Qual.setAddressSpace(LangAS::opencl_local);
723 break;
724 default:
725 Qual.removeAddressSpace();
726 }
727 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
728 RT.getUnqualifiedType(), Qual)));
729
730 return false;
731}
732
John McCalldadc5752010-08-24 06:29:42 +0000733ExprResult
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000734Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
735 CallExpr *TheCall) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000736 ExprResult TheCallResult(TheCall);
Douglas Gregorae2fbad2008-11-17 20:34:05 +0000737
Chris Lattner3be167f2010-10-01 23:23:24 +0000738 // Find out if any arguments are required to be integer constant expressions.
739 unsigned ICEArguments = 0;
740 ASTContext::GetBuiltinTypeError Error;
741 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
742 if (Error != ASTContext::GE_None)
743 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
744
745 // If any arguments are required to be ICE's, check and diagnose.
746 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
747 // Skip arguments not required to be ICE's.
748 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
749
750 llvm::APSInt Result;
751 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
752 return true;
753 ICEArguments &= ~(1 << ArgNo);
754 }
755
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000756 switch (BuiltinID) {
Chris Lattner43be2e62007-12-19 23:59:04 +0000757 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner08464942007-12-28 05:29:59 +0000758 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner2da14fb2007-12-20 00:26:33 +0000759 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner6436fb62009-02-18 06:01:06 +0000760 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000761 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000762 break;
Ted Kremeneka174c522008-07-09 17:58:53 +0000763 case Builtin::BI__builtin_stdarg_start:
Chris Lattner43be2e62007-12-19 23:59:04 +0000764 case Builtin::BI__builtin_va_start:
Reid Kleckner2b0fa122017-05-02 20:10:03 +0000765 if (SemaBuiltinVAStart(BuiltinID, TheCall))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000766 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000767 break;
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000768 case Builtin::BI__va_start: {
769 switch (Context.getTargetInfo().getTriple().getArch()) {
770 case llvm::Triple::arm:
771 case llvm::Triple::thumb:
772 if (SemaBuiltinVAStartARM(TheCall))
773 return ExprError();
774 break;
775 default:
Reid Kleckner2b0fa122017-05-02 20:10:03 +0000776 if (SemaBuiltinVAStart(BuiltinID, TheCall))
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000777 return ExprError();
778 break;
779 }
780 break;
781 }
Chris Lattner2da14fb2007-12-20 00:26:33 +0000782 case Builtin::BI__builtin_isgreater:
783 case Builtin::BI__builtin_isgreaterequal:
784 case Builtin::BI__builtin_isless:
785 case Builtin::BI__builtin_islessequal:
786 case Builtin::BI__builtin_islessgreater:
787 case Builtin::BI__builtin_isunordered:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000788 if (SemaBuiltinUnorderedCompare(TheCall))
789 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000790 break;
Benjamin Kramer634fc102010-02-15 22:42:31 +0000791 case Builtin::BI__builtin_fpclassify:
792 if (SemaBuiltinFPClassification(TheCall, 6))
793 return ExprError();
794 break;
Eli Friedman7e4faac2009-08-31 20:06:00 +0000795 case Builtin::BI__builtin_isfinite:
796 case Builtin::BI__builtin_isinf:
797 case Builtin::BI__builtin_isinf_sign:
798 case Builtin::BI__builtin_isnan:
799 case Builtin::BI__builtin_isnormal:
Benjamin Kramer64aae502010-02-16 10:07:31 +0000800 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman7e4faac2009-08-31 20:06:00 +0000801 return ExprError();
802 break;
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000803 case Builtin::BI__builtin_shufflevector:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000804 return SemaBuiltinShuffleVector(TheCall);
805 // TheCall will be freed by the smart pointer here, but that's fine, since
806 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbarb7257262008-07-21 22:59:13 +0000807 case Builtin::BI__builtin_prefetch:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000808 if (SemaBuiltinPrefetch(TheCall))
809 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000810 break;
David Majnemer51169932016-10-31 05:37:48 +0000811 case Builtin::BI__builtin_alloca_with_align:
812 if (SemaBuiltinAllocaWithAlign(TheCall))
813 return ExprError();
814 break;
Hal Finkelf0417332014-07-17 14:25:55 +0000815 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +0000816 case Builtin::BI__builtin_assume:
Hal Finkelf0417332014-07-17 14:25:55 +0000817 if (SemaBuiltinAssume(TheCall))
818 return ExprError();
819 break;
Hal Finkelbcc06082014-09-07 22:58:14 +0000820 case Builtin::BI__builtin_assume_aligned:
821 if (SemaBuiltinAssumeAligned(TheCall))
822 return ExprError();
823 break;
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000824 case Builtin::BI__builtin_object_size:
Richard Sandiford28940af2014-04-16 08:47:51 +0000825 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000826 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000827 break;
Eli Friedmaneed8ad22009-05-03 04:46:36 +0000828 case Builtin::BI__builtin_longjmp:
829 if (SemaBuiltinLongjmp(TheCall))
830 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000831 break;
Joerg Sonnenberger27173282015-03-11 23:46:32 +0000832 case Builtin::BI__builtin_setjmp:
833 if (SemaBuiltinSetjmp(TheCall))
834 return ExprError();
835 break;
David Majnemerc403a1c2015-03-20 17:03:35 +0000836 case Builtin::BI_setjmp:
837 case Builtin::BI_setjmpex:
838 if (checkArgCount(*this, TheCall, 1))
839 return true;
840 break;
John McCallbebede42011-02-26 05:39:39 +0000841
842 case Builtin::BI__builtin_classify_type:
843 if (checkArgCount(*this, TheCall, 1)) return true;
844 TheCall->setType(Context.IntTy);
845 break;
Chris Lattner17c0eac2010-10-12 17:47:42 +0000846 case Builtin::BI__builtin_constant_p:
John McCallbebede42011-02-26 05:39:39 +0000847 if (checkArgCount(*this, TheCall, 1)) return true;
848 TheCall->setType(Context.IntTy);
Chris Lattner17c0eac2010-10-12 17:47:42 +0000849 break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000850 case Builtin::BI__sync_fetch_and_add:
Douglas Gregor73722482011-11-28 16:30:08 +0000851 case Builtin::BI__sync_fetch_and_add_1:
852 case Builtin::BI__sync_fetch_and_add_2:
853 case Builtin::BI__sync_fetch_and_add_4:
854 case Builtin::BI__sync_fetch_and_add_8:
855 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000856 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregor73722482011-11-28 16:30:08 +0000857 case Builtin::BI__sync_fetch_and_sub_1:
858 case Builtin::BI__sync_fetch_and_sub_2:
859 case Builtin::BI__sync_fetch_and_sub_4:
860 case Builtin::BI__sync_fetch_and_sub_8:
861 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000862 case Builtin::BI__sync_fetch_and_or:
Douglas Gregor73722482011-11-28 16:30:08 +0000863 case Builtin::BI__sync_fetch_and_or_1:
864 case Builtin::BI__sync_fetch_and_or_2:
865 case Builtin::BI__sync_fetch_and_or_4:
866 case Builtin::BI__sync_fetch_and_or_8:
867 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000868 case Builtin::BI__sync_fetch_and_and:
Douglas Gregor73722482011-11-28 16:30:08 +0000869 case Builtin::BI__sync_fetch_and_and_1:
870 case Builtin::BI__sync_fetch_and_and_2:
871 case Builtin::BI__sync_fetch_and_and_4:
872 case Builtin::BI__sync_fetch_and_and_8:
873 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000874 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregor73722482011-11-28 16:30:08 +0000875 case Builtin::BI__sync_fetch_and_xor_1:
876 case Builtin::BI__sync_fetch_and_xor_2:
877 case Builtin::BI__sync_fetch_and_xor_4:
878 case Builtin::BI__sync_fetch_and_xor_8:
879 case Builtin::BI__sync_fetch_and_xor_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000880 case Builtin::BI__sync_fetch_and_nand:
881 case Builtin::BI__sync_fetch_and_nand_1:
882 case Builtin::BI__sync_fetch_and_nand_2:
883 case Builtin::BI__sync_fetch_and_nand_4:
884 case Builtin::BI__sync_fetch_and_nand_8:
885 case Builtin::BI__sync_fetch_and_nand_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000886 case Builtin::BI__sync_add_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000887 case Builtin::BI__sync_add_and_fetch_1:
888 case Builtin::BI__sync_add_and_fetch_2:
889 case Builtin::BI__sync_add_and_fetch_4:
890 case Builtin::BI__sync_add_and_fetch_8:
891 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000892 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000893 case Builtin::BI__sync_sub_and_fetch_1:
894 case Builtin::BI__sync_sub_and_fetch_2:
895 case Builtin::BI__sync_sub_and_fetch_4:
896 case Builtin::BI__sync_sub_and_fetch_8:
897 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000898 case Builtin::BI__sync_and_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000899 case Builtin::BI__sync_and_and_fetch_1:
900 case Builtin::BI__sync_and_and_fetch_2:
901 case Builtin::BI__sync_and_and_fetch_4:
902 case Builtin::BI__sync_and_and_fetch_8:
903 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000904 case Builtin::BI__sync_or_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000905 case Builtin::BI__sync_or_and_fetch_1:
906 case Builtin::BI__sync_or_and_fetch_2:
907 case Builtin::BI__sync_or_and_fetch_4:
908 case Builtin::BI__sync_or_and_fetch_8:
909 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000910 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000911 case Builtin::BI__sync_xor_and_fetch_1:
912 case Builtin::BI__sync_xor_and_fetch_2:
913 case Builtin::BI__sync_xor_and_fetch_4:
914 case Builtin::BI__sync_xor_and_fetch_8:
915 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000916 case Builtin::BI__sync_nand_and_fetch:
917 case Builtin::BI__sync_nand_and_fetch_1:
918 case Builtin::BI__sync_nand_and_fetch_2:
919 case Builtin::BI__sync_nand_and_fetch_4:
920 case Builtin::BI__sync_nand_and_fetch_8:
921 case Builtin::BI__sync_nand_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000922 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000923 case Builtin::BI__sync_val_compare_and_swap_1:
924 case Builtin::BI__sync_val_compare_and_swap_2:
925 case Builtin::BI__sync_val_compare_and_swap_4:
926 case Builtin::BI__sync_val_compare_and_swap_8:
927 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000928 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000929 case Builtin::BI__sync_bool_compare_and_swap_1:
930 case Builtin::BI__sync_bool_compare_and_swap_2:
931 case Builtin::BI__sync_bool_compare_and_swap_4:
932 case Builtin::BI__sync_bool_compare_and_swap_8:
933 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000934 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +0000935 case Builtin::BI__sync_lock_test_and_set_1:
936 case Builtin::BI__sync_lock_test_and_set_2:
937 case Builtin::BI__sync_lock_test_and_set_4:
938 case Builtin::BI__sync_lock_test_and_set_8:
939 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000940 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +0000941 case Builtin::BI__sync_lock_release_1:
942 case Builtin::BI__sync_lock_release_2:
943 case Builtin::BI__sync_lock_release_4:
944 case Builtin::BI__sync_lock_release_8:
945 case Builtin::BI__sync_lock_release_16:
Chris Lattner9cb59fa2011-04-09 03:57:26 +0000946 case Builtin::BI__sync_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000947 case Builtin::BI__sync_swap_1:
948 case Builtin::BI__sync_swap_2:
949 case Builtin::BI__sync_swap_4:
950 case Builtin::BI__sync_swap_8:
951 case Builtin::BI__sync_swap_16:
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000952 return SemaBuiltinAtomicOverloaded(TheCallResult);
Michael Zolotukhin84df1232015-09-08 23:52:33 +0000953 case Builtin::BI__builtin_nontemporal_load:
954 case Builtin::BI__builtin_nontemporal_store:
955 return SemaBuiltinNontemporalOverloaded(TheCallResult);
Richard Smithfeea8832012-04-12 05:08:17 +0000956#define BUILTIN(ID, TYPE, ATTRS)
957#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
958 case Builtin::BI##ID: \
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000959 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithfeea8832012-04-12 05:08:17 +0000960#include "clang/Basic/Builtins.def"
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000961 case Builtin::BI__builtin_annotation:
Julien Lerouge4a5b4442012-04-28 17:39:16 +0000962 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000963 return ExprError();
964 break;
Richard Smith6cbd65d2013-07-11 02:27:57 +0000965 case Builtin::BI__builtin_addressof:
966 if (SemaBuiltinAddressof(*this, TheCall))
967 return ExprError();
968 break;
John McCall03107a42015-10-29 20:48:01 +0000969 case Builtin::BI__builtin_add_overflow:
970 case Builtin::BI__builtin_sub_overflow:
971 case Builtin::BI__builtin_mul_overflow:
Craig Toppera86e70d2015-11-07 06:16:14 +0000972 if (SemaBuiltinOverflow(*this, TheCall))
973 return ExprError();
974 break;
Richard Smith760520b2014-06-03 23:27:44 +0000975 case Builtin::BI__builtin_operator_new:
976 case Builtin::BI__builtin_operator_delete:
977 if (!getLangOpts().CPlusPlus) {
978 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
979 << (BuiltinID == Builtin::BI__builtin_operator_new
980 ? "__builtin_operator_new"
981 : "__builtin_operator_delete")
982 << "C++";
983 return ExprError();
984 }
985 // CodeGen assumes it can find the global new and delete to call,
986 // so ensure that they are declared.
987 DeclareGlobalNewDelete();
988 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000989
990 // check secure string manipulation functions where overflows
991 // are detectable at compile time
992 case Builtin::BI__builtin___memcpy_chk:
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000993 case Builtin::BI__builtin___memmove_chk:
994 case Builtin::BI__builtin___memset_chk:
995 case Builtin::BI__builtin___strlcat_chk:
996 case Builtin::BI__builtin___strlcpy_chk:
997 case Builtin::BI__builtin___strncat_chk:
998 case Builtin::BI__builtin___strncpy_chk:
999 case Builtin::BI__builtin___stpncpy_chk:
1000 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
1001 break;
Steven Wu566c14e2014-09-24 04:37:33 +00001002 case Builtin::BI__builtin___memccpy_chk:
1003 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
1004 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001005 case Builtin::BI__builtin___snprintf_chk:
1006 case Builtin::BI__builtin___vsnprintf_chk:
1007 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
1008 break;
Peter Collingbournef7706832014-12-12 23:41:25 +00001009 case Builtin::BI__builtin_call_with_static_chain:
1010 if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1011 return ExprError();
1012 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001013 case Builtin::BI__exception_code:
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001014 case Builtin::BI_exception_code:
Reid Kleckner1d59f992015-01-22 01:36:17 +00001015 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1016 diag::err_seh___except_block))
1017 return ExprError();
1018 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001019 case Builtin::BI__exception_info:
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001020 case Builtin::BI_exception_info:
Reid Kleckner1d59f992015-01-22 01:36:17 +00001021 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1022 diag::err_seh___except_filter))
1023 return ExprError();
1024 break;
David Majnemerba3e5ec2015-03-13 18:26:17 +00001025 case Builtin::BI__GetExceptionInfo:
1026 if (checkArgCount(*this, TheCall, 1))
1027 return ExprError();
1028
1029 if (CheckCXXThrowOperand(
1030 TheCall->getLocStart(),
1031 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1032 TheCall))
1033 return ExprError();
1034
1035 TheCall->setType(Context.VoidPtrTy);
1036 break;
Anastasia Stulova7f8d6dc2016-07-04 16:07:18 +00001037 // OpenCL v2.0, s6.13.16 - Pipe functions
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001038 case Builtin::BIread_pipe:
1039 case Builtin::BIwrite_pipe:
1040 // Since those two functions are declared with var args, we need a semantic
1041 // check for the argument.
1042 if (SemaBuiltinRWPipe(*this, TheCall))
1043 return ExprError();
Alexey Baderaf17c792016-09-07 10:32:03 +00001044 TheCall->setType(Context.IntTy);
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001045 break;
1046 case Builtin::BIreserve_read_pipe:
1047 case Builtin::BIreserve_write_pipe:
1048 case Builtin::BIwork_group_reserve_read_pipe:
1049 case Builtin::BIwork_group_reserve_write_pipe:
1050 case Builtin::BIsub_group_reserve_read_pipe:
1051 case Builtin::BIsub_group_reserve_write_pipe:
1052 if (SemaBuiltinReserveRWPipe(*this, TheCall))
1053 return ExprError();
1054 // Since return type of reserve_read/write_pipe built-in function is
1055 // reserve_id_t, which is not defined in the builtin def file , we used int
1056 // as return type and need to override the return type of these functions.
1057 TheCall->setType(Context.OCLReserveIDTy);
1058 break;
1059 case Builtin::BIcommit_read_pipe:
1060 case Builtin::BIcommit_write_pipe:
1061 case Builtin::BIwork_group_commit_read_pipe:
1062 case Builtin::BIwork_group_commit_write_pipe:
1063 case Builtin::BIsub_group_commit_read_pipe:
1064 case Builtin::BIsub_group_commit_write_pipe:
1065 if (SemaBuiltinCommitRWPipe(*this, TheCall))
1066 return ExprError();
1067 break;
1068 case Builtin::BIget_pipe_num_packets:
1069 case Builtin::BIget_pipe_max_packets:
1070 if (SemaBuiltinPipePackets(*this, TheCall))
1071 return ExprError();
Alexey Baderaf17c792016-09-07 10:32:03 +00001072 TheCall->setType(Context.UnsignedIntTy);
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001073 break;
Yaxun Liuf7449a12016-05-20 19:54:38 +00001074 case Builtin::BIto_global:
1075 case Builtin::BIto_local:
1076 case Builtin::BIto_private:
1077 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1078 return ExprError();
1079 break;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00001080 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1081 case Builtin::BIenqueue_kernel:
1082 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1083 return ExprError();
1084 break;
1085 case Builtin::BIget_kernel_work_group_size:
1086 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1087 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1088 return ExprError();
Mehdi Amini06d367c2016-10-24 20:39:34 +00001089 break;
1090 case Builtin::BI__builtin_os_log_format:
1091 case Builtin::BI__builtin_os_log_format_buffer_size:
1092 if (SemaBuiltinOSLogFormat(TheCall)) {
1093 return ExprError();
1094 }
1095 break;
Nate Begeman4904e322010-06-08 02:47:44 +00001096 }
Richard Smith760520b2014-06-03 23:27:44 +00001097
Nate Begeman4904e322010-06-08 02:47:44 +00001098 // Since the target specific builtins for each arch overlap, only check those
1099 // of the arch we are compiling for.
Artem Belevich9674a642015-09-22 17:23:05 +00001100 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001101 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +00001102 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00001103 case llvm::Triple::armeb:
Nate Begeman4904e322010-06-08 02:47:44 +00001104 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00001105 case llvm::Triple::thumbeb:
Nate Begeman4904e322010-06-08 02:47:44 +00001106 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1107 return ExprError();
1108 break;
Tim Northover25e8a672014-05-24 12:51:25 +00001109 case llvm::Triple::aarch64:
1110 case llvm::Triple::aarch64_be:
Tim Northover573cbee2014-05-24 12:52:07 +00001111 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
Tim Northovera2ee4332014-03-29 15:09:45 +00001112 return ExprError();
1113 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001114 case llvm::Triple::mips:
1115 case llvm::Triple::mipsel:
1116 case llvm::Triple::mips64:
1117 case llvm::Triple::mips64el:
1118 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1119 return ExprError();
1120 break;
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001121 case llvm::Triple::systemz:
1122 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1123 return ExprError();
1124 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001125 case llvm::Triple::x86:
1126 case llvm::Triple::x86_64:
1127 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1128 return ExprError();
1129 break;
Kit Bartone50adcb2015-03-30 19:40:59 +00001130 case llvm::Triple::ppc:
1131 case llvm::Triple::ppc64:
1132 case llvm::Triple::ppc64le:
1133 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1134 return ExprError();
1135 break;
Nate Begeman4904e322010-06-08 02:47:44 +00001136 default:
1137 break;
1138 }
1139 }
1140
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001141 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +00001142}
1143
Nate Begeman91e1fea2010-06-14 05:21:25 +00001144// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +00001145static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +00001146 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +00001147 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +00001148 switch (Type.getEltType()) {
1149 case NeonTypeFlags::Int8:
1150 case NeonTypeFlags::Poly8:
1151 return shift ? 7 : (8 << IsQuad) - 1;
1152 case NeonTypeFlags::Int16:
1153 case NeonTypeFlags::Poly16:
1154 return shift ? 15 : (4 << IsQuad) - 1;
1155 case NeonTypeFlags::Int32:
1156 return shift ? 31 : (2 << IsQuad) - 1;
1157 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +00001158 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +00001159 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +00001160 case NeonTypeFlags::Poly128:
1161 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +00001162 case NeonTypeFlags::Float16:
1163 assert(!shift && "cannot shift float types!");
1164 return (4 << IsQuad) - 1;
1165 case NeonTypeFlags::Float32:
1166 assert(!shift && "cannot shift float types!");
1167 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +00001168 case NeonTypeFlags::Float64:
1169 assert(!shift && "cannot shift float types!");
1170 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +00001171 }
David Blaikie8a40f702012-01-17 06:56:22 +00001172 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +00001173}
1174
Bob Wilsone4d77232011-11-08 05:04:11 +00001175/// getNeonEltType - Return the QualType corresponding to the elements of
1176/// the vector type specified by the NeonTypeFlags. This is used to check
1177/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +00001178static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Tim Northovera2ee4332014-03-29 15:09:45 +00001179 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilsone4d77232011-11-08 05:04:11 +00001180 switch (Flags.getEltType()) {
1181 case NeonTypeFlags::Int8:
1182 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1183 case NeonTypeFlags::Int16:
1184 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1185 case NeonTypeFlags::Int32:
1186 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1187 case NeonTypeFlags::Int64:
Tim Northovera2ee4332014-03-29 15:09:45 +00001188 if (IsInt64Long)
Kevin Qinad64f6d2014-02-24 02:45:03 +00001189 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1190 else
1191 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1192 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001193 case NeonTypeFlags::Poly8:
Tim Northovera2ee4332014-03-29 15:09:45 +00001194 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001195 case NeonTypeFlags::Poly16:
Tim Northovera2ee4332014-03-29 15:09:45 +00001196 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qincaac85e2013-11-14 03:29:16 +00001197 case NeonTypeFlags::Poly64:
Kevin Qin78b86532015-05-14 08:18:05 +00001198 if (IsInt64Long)
1199 return Context.UnsignedLongTy;
1200 else
1201 return Context.UnsignedLongLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +00001202 case NeonTypeFlags::Poly128:
1203 break;
Bob Wilsone4d77232011-11-08 05:04:11 +00001204 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +00001205 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001206 case NeonTypeFlags::Float32:
1207 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +00001208 case NeonTypeFlags::Float64:
1209 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001210 }
David Blaikie8a40f702012-01-17 06:56:22 +00001211 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +00001212}
1213
Tim Northover12670412014-02-19 10:37:05 +00001214bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +00001215 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +00001216 uint64_t mask = 0;
1217 unsigned TV = 0;
1218 int PtrArgNum = -1;
1219 bool HasConstPtr = false;
1220 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +00001221#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001222#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +00001223#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001224 }
1225
1226 // For NEON intrinsics which are overloaded on vector element type, validate
1227 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +00001228 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +00001229 if (mask) {
1230 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1231 return true;
1232
1233 TV = Result.getLimitedValue(64);
1234 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1235 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Tim Northover12670412014-02-19 10:37:05 +00001236 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +00001237 }
1238
1239 if (PtrArgNum >= 0) {
1240 // Check that pointer arguments have the specified type.
1241 Expr *Arg = TheCall->getArg(PtrArgNum);
1242 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1243 Arg = ICE->getSubExpr();
1244 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1245 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +00001246
Tim Northovera2ee4332014-03-29 15:09:45 +00001247 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Joerg Sonnenberger47006c52017-01-09 11:40:41 +00001248 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
1249 Arch == llvm::Triple::aarch64_be;
Tim Northovera2ee4332014-03-29 15:09:45 +00001250 bool IsInt64Long =
1251 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1252 QualType EltTy =
1253 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northover2fe823a2013-08-01 09:23:19 +00001254 if (HasConstPtr)
1255 EltTy = EltTy.withConst();
1256 QualType LHSTy = Context.getPointerType(EltTy);
1257 AssignConvertType ConvTy;
1258 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1259 if (RHS.isInvalid())
1260 return true;
1261 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
1262 RHS.get(), AA_Assigning))
1263 return true;
1264 }
1265
1266 // For NEON intrinsics which take an immediate value as part of the
1267 // instruction, range check them here.
1268 unsigned i = 0, l = 0, u = 0;
1269 switch (BuiltinID) {
1270 default:
1271 return false;
Tim Northover12670412014-02-19 10:37:05 +00001272#define GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001273#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +00001274#undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001275 }
Tim Northover2fe823a2013-08-01 09:23:19 +00001276
Richard Sandiford28940af2014-04-16 08:47:51 +00001277 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northover2fe823a2013-08-01 09:23:19 +00001278}
1279
Tim Northovera2ee4332014-03-29 15:09:45 +00001280bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1281 unsigned MaxWidth) {
Tim Northover6aacd492013-07-16 09:47:53 +00001282 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001283 BuiltinID == ARM::BI__builtin_arm_ldaex ||
Tim Northovera2ee4332014-03-29 15:09:45 +00001284 BuiltinID == ARM::BI__builtin_arm_strex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001285 BuiltinID == ARM::BI__builtin_arm_stlex ||
Tim Northover573cbee2014-05-24 12:52:07 +00001286 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001287 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1288 BuiltinID == AArch64::BI__builtin_arm_strex ||
1289 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
Tim Northover6aacd492013-07-16 09:47:53 +00001290 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +00001291 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001292 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1293 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1294 BuiltinID == AArch64::BI__builtin_arm_ldaex;
Tim Northover6aacd492013-07-16 09:47:53 +00001295
1296 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1297
1298 // Ensure that we have the proper number of arguments.
1299 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1300 return true;
1301
1302 // Inspect the pointer argument of the atomic builtin. This should always be
1303 // a pointer type, whose element is an integral scalar or pointer type.
1304 // Because it is a pointer type, we don't have to worry about any implicit
1305 // casts here.
1306 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1307 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1308 if (PointerArgRes.isInvalid())
1309 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001310 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001311
1312 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1313 if (!pointerType) {
1314 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1315 << PointerArg->getType() << PointerArg->getSourceRange();
1316 return true;
1317 }
1318
1319 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1320 // task is to insert the appropriate casts into the AST. First work out just
1321 // what the appropriate type is.
1322 QualType ValType = pointerType->getPointeeType();
1323 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1324 if (IsLdrex)
1325 AddrType.addConst();
1326
1327 // Issue a warning if the cast is dodgy.
1328 CastKind CastNeeded = CK_NoOp;
1329 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1330 CastNeeded = CK_BitCast;
1331 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
1332 << PointerArg->getType()
1333 << Context.getPointerType(AddrType)
1334 << AA_Passing << PointerArg->getSourceRange();
1335 }
1336
1337 // Finally, do the cast and replace the argument with the corrected version.
1338 AddrType = Context.getPointerType(AddrType);
1339 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1340 if (PointerArgRes.isInvalid())
1341 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001342 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001343
1344 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1345
1346 // In general, we allow ints, floats and pointers to be loaded and stored.
1347 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1348 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1349 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1350 << PointerArg->getType() << PointerArg->getSourceRange();
1351 return true;
1352 }
1353
1354 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +00001355 if (Context.getTypeSize(ValType) > MaxWidth) {
1356 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover6aacd492013-07-16 09:47:53 +00001357 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
1358 << PointerArg->getType() << PointerArg->getSourceRange();
1359 return true;
1360 }
1361
1362 switch (ValType.getObjCLifetime()) {
1363 case Qualifiers::OCL_None:
1364 case Qualifiers::OCL_ExplicitNone:
1365 // okay
1366 break;
1367
1368 case Qualifiers::OCL_Weak:
1369 case Qualifiers::OCL_Strong:
1370 case Qualifiers::OCL_Autoreleasing:
1371 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1372 << ValType << PointerArg->getSourceRange();
1373 return true;
1374 }
1375
Tim Northover6aacd492013-07-16 09:47:53 +00001376 if (IsLdrex) {
1377 TheCall->setType(ValType);
1378 return false;
1379 }
1380
1381 // Initialize the argument to be stored.
1382 ExprResult ValArg = TheCall->getArg(0);
1383 InitializedEntity Entity = InitializedEntity::InitializeParameter(
1384 Context, ValType, /*consume*/ false);
1385 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1386 if (ValArg.isInvalid())
1387 return true;
Tim Northover6aacd492013-07-16 09:47:53 +00001388 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +00001389
1390 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1391 // but the custom checker bypasses all default analysis.
1392 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +00001393 return false;
1394}
1395
Nate Begeman4904e322010-06-08 02:47:44 +00001396bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover6aacd492013-07-16 09:47:53 +00001397 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001398 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1399 BuiltinID == ARM::BI__builtin_arm_strex ||
1400 BuiltinID == ARM::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001401 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +00001402 }
1403
Yi Kong26d104a2014-08-13 19:18:14 +00001404 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1405 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1406 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1407 }
1408
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001409 if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1410 BuiltinID == ARM::BI__builtin_arm_wsr64)
1411 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1412
1413 if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1414 BuiltinID == ARM::BI__builtin_arm_rsrp ||
1415 BuiltinID == ARM::BI__builtin_arm_wsr ||
1416 BuiltinID == ARM::BI__builtin_arm_wsrp)
1417 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1418
Tim Northover12670412014-02-19 10:37:05 +00001419 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1420 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +00001421
Yi Kong4efadfb2014-07-03 16:01:25 +00001422 // For intrinsics which take an immediate value as part of the instruction,
1423 // range check them here.
Nate Begeman91e1fea2010-06-14 05:21:25 +00001424 unsigned i = 0, l = 0, u = 0;
Nate Begemand773fe62010-06-13 04:47:52 +00001425 switch (BuiltinID) {
1426 default: return false;
Nate Begeman1194bd22010-07-29 22:48:34 +00001427 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
1428 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begemanf568b072010-08-03 21:32:34 +00001429 case ARM::BI__builtin_arm_vcvtr_f:
1430 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Weiming Zhao87bb4922013-11-12 21:42:50 +00001431 case ARM::BI__builtin_arm_dmb:
Yi Kong4efadfb2014-07-03 16:01:25 +00001432 case ARM::BI__builtin_arm_dsb:
Yi Kong1d268af2014-08-26 12:48:06 +00001433 case ARM::BI__builtin_arm_isb:
1434 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00001435 }
Nate Begemand773fe62010-06-13 04:47:52 +00001436
Nate Begemanf568b072010-08-03 21:32:34 +00001437 // FIXME: VFP Intrinsics should error if VFP not present.
Richard Sandiford28940af2014-04-16 08:47:51 +00001438 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001439}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001440
Tim Northover573cbee2014-05-24 12:52:07 +00001441bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +00001442 CallExpr *TheCall) {
Tim Northover573cbee2014-05-24 12:52:07 +00001443 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001444 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1445 BuiltinID == AArch64::BI__builtin_arm_strex ||
1446 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001447 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1448 }
1449
Yi Konga5548432014-08-13 19:18:20 +00001450 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1451 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1452 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1453 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1454 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1455 }
1456
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001457 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1458 BuiltinID == AArch64::BI__builtin_arm_wsr64)
Tim Northover54e50002016-04-13 17:08:55 +00001459 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001460
1461 if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1462 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1463 BuiltinID == AArch64::BI__builtin_arm_wsr ||
1464 BuiltinID == AArch64::BI__builtin_arm_wsrp)
1465 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1466
Tim Northovera2ee4332014-03-29 15:09:45 +00001467 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1468 return true;
1469
Yi Kong19a29ac2014-07-17 10:52:06 +00001470 // For intrinsics which take an immediate value as part of the instruction,
1471 // range check them here.
1472 unsigned i = 0, l = 0, u = 0;
1473 switch (BuiltinID) {
1474 default: return false;
1475 case AArch64::BI__builtin_arm_dmb:
1476 case AArch64::BI__builtin_arm_dsb:
1477 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1478 }
1479
Yi Kong19a29ac2014-07-17 10:52:06 +00001480 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northovera2ee4332014-03-29 15:09:45 +00001481}
1482
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001483// CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
1484// intrinsic is correct. The switch statement is ordered by DSP, MSA. The
1485// ordering for DSP is unspecified. MSA is ordered by the data format used
1486// by the underlying instruction i.e., df/m, df/n and then by size.
1487//
1488// FIXME: The size tests here should instead be tablegen'd along with the
1489// definitions from include/clang/Basic/BuiltinsMips.def.
1490// FIXME: GCC is strict on signedness for some of these intrinsics, we should
1491// be too.
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001492bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001493 unsigned i = 0, l = 0, u = 0, m = 0;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001494 switch (BuiltinID) {
1495 default: return false;
1496 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
1497 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +00001498 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
1499 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
1500 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
1501 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
1502 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001503 // MSA instrinsics. Instructions (which the intrinsics maps to) which use the
1504 // df/m field.
1505 // These intrinsics take an unsigned 3 bit immediate.
1506 case Mips::BI__builtin_msa_bclri_b:
1507 case Mips::BI__builtin_msa_bnegi_b:
1508 case Mips::BI__builtin_msa_bseti_b:
1509 case Mips::BI__builtin_msa_sat_s_b:
1510 case Mips::BI__builtin_msa_sat_u_b:
1511 case Mips::BI__builtin_msa_slli_b:
1512 case Mips::BI__builtin_msa_srai_b:
1513 case Mips::BI__builtin_msa_srari_b:
1514 case Mips::BI__builtin_msa_srli_b:
1515 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
1516 case Mips::BI__builtin_msa_binsli_b:
1517 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
1518 // These intrinsics take an unsigned 4 bit immediate.
1519 case Mips::BI__builtin_msa_bclri_h:
1520 case Mips::BI__builtin_msa_bnegi_h:
1521 case Mips::BI__builtin_msa_bseti_h:
1522 case Mips::BI__builtin_msa_sat_s_h:
1523 case Mips::BI__builtin_msa_sat_u_h:
1524 case Mips::BI__builtin_msa_slli_h:
1525 case Mips::BI__builtin_msa_srai_h:
1526 case Mips::BI__builtin_msa_srari_h:
1527 case Mips::BI__builtin_msa_srli_h:
1528 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
1529 case Mips::BI__builtin_msa_binsli_h:
1530 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
1531 // These intrinsics take an unsigned 5 bit immedate.
1532 // The first block of intrinsics actually have an unsigned 5 bit field,
1533 // not a df/n field.
1534 case Mips::BI__builtin_msa_clei_u_b:
1535 case Mips::BI__builtin_msa_clei_u_h:
1536 case Mips::BI__builtin_msa_clei_u_w:
1537 case Mips::BI__builtin_msa_clei_u_d:
1538 case Mips::BI__builtin_msa_clti_u_b:
1539 case Mips::BI__builtin_msa_clti_u_h:
1540 case Mips::BI__builtin_msa_clti_u_w:
1541 case Mips::BI__builtin_msa_clti_u_d:
1542 case Mips::BI__builtin_msa_maxi_u_b:
1543 case Mips::BI__builtin_msa_maxi_u_h:
1544 case Mips::BI__builtin_msa_maxi_u_w:
1545 case Mips::BI__builtin_msa_maxi_u_d:
1546 case Mips::BI__builtin_msa_mini_u_b:
1547 case Mips::BI__builtin_msa_mini_u_h:
1548 case Mips::BI__builtin_msa_mini_u_w:
1549 case Mips::BI__builtin_msa_mini_u_d:
1550 case Mips::BI__builtin_msa_addvi_b:
1551 case Mips::BI__builtin_msa_addvi_h:
1552 case Mips::BI__builtin_msa_addvi_w:
1553 case Mips::BI__builtin_msa_addvi_d:
1554 case Mips::BI__builtin_msa_bclri_w:
1555 case Mips::BI__builtin_msa_bnegi_w:
1556 case Mips::BI__builtin_msa_bseti_w:
1557 case Mips::BI__builtin_msa_sat_s_w:
1558 case Mips::BI__builtin_msa_sat_u_w:
1559 case Mips::BI__builtin_msa_slli_w:
1560 case Mips::BI__builtin_msa_srai_w:
1561 case Mips::BI__builtin_msa_srari_w:
1562 case Mips::BI__builtin_msa_srli_w:
1563 case Mips::BI__builtin_msa_srlri_w:
1564 case Mips::BI__builtin_msa_subvi_b:
1565 case Mips::BI__builtin_msa_subvi_h:
1566 case Mips::BI__builtin_msa_subvi_w:
1567 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
1568 case Mips::BI__builtin_msa_binsli_w:
1569 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
1570 // These intrinsics take an unsigned 6 bit immediate.
1571 case Mips::BI__builtin_msa_bclri_d:
1572 case Mips::BI__builtin_msa_bnegi_d:
1573 case Mips::BI__builtin_msa_bseti_d:
1574 case Mips::BI__builtin_msa_sat_s_d:
1575 case Mips::BI__builtin_msa_sat_u_d:
1576 case Mips::BI__builtin_msa_slli_d:
1577 case Mips::BI__builtin_msa_srai_d:
1578 case Mips::BI__builtin_msa_srari_d:
1579 case Mips::BI__builtin_msa_srli_d:
1580 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
1581 case Mips::BI__builtin_msa_binsli_d:
1582 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
1583 // These intrinsics take a signed 5 bit immediate.
1584 case Mips::BI__builtin_msa_ceqi_b:
1585 case Mips::BI__builtin_msa_ceqi_h:
1586 case Mips::BI__builtin_msa_ceqi_w:
1587 case Mips::BI__builtin_msa_ceqi_d:
1588 case Mips::BI__builtin_msa_clti_s_b:
1589 case Mips::BI__builtin_msa_clti_s_h:
1590 case Mips::BI__builtin_msa_clti_s_w:
1591 case Mips::BI__builtin_msa_clti_s_d:
1592 case Mips::BI__builtin_msa_clei_s_b:
1593 case Mips::BI__builtin_msa_clei_s_h:
1594 case Mips::BI__builtin_msa_clei_s_w:
1595 case Mips::BI__builtin_msa_clei_s_d:
1596 case Mips::BI__builtin_msa_maxi_s_b:
1597 case Mips::BI__builtin_msa_maxi_s_h:
1598 case Mips::BI__builtin_msa_maxi_s_w:
1599 case Mips::BI__builtin_msa_maxi_s_d:
1600 case Mips::BI__builtin_msa_mini_s_b:
1601 case Mips::BI__builtin_msa_mini_s_h:
1602 case Mips::BI__builtin_msa_mini_s_w:
1603 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
1604 // These intrinsics take an unsigned 8 bit immediate.
1605 case Mips::BI__builtin_msa_andi_b:
1606 case Mips::BI__builtin_msa_nori_b:
1607 case Mips::BI__builtin_msa_ori_b:
1608 case Mips::BI__builtin_msa_shf_b:
1609 case Mips::BI__builtin_msa_shf_h:
1610 case Mips::BI__builtin_msa_shf_w:
1611 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
1612 case Mips::BI__builtin_msa_bseli_b:
1613 case Mips::BI__builtin_msa_bmnzi_b:
1614 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
1615 // df/n format
1616 // These intrinsics take an unsigned 4 bit immediate.
1617 case Mips::BI__builtin_msa_copy_s_b:
1618 case Mips::BI__builtin_msa_copy_u_b:
1619 case Mips::BI__builtin_msa_insve_b:
1620 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001621 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
1622 // These intrinsics take an unsigned 3 bit immediate.
1623 case Mips::BI__builtin_msa_copy_s_h:
1624 case Mips::BI__builtin_msa_copy_u_h:
1625 case Mips::BI__builtin_msa_insve_h:
1626 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001627 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
1628 // These intrinsics take an unsigned 2 bit immediate.
1629 case Mips::BI__builtin_msa_copy_s_w:
1630 case Mips::BI__builtin_msa_copy_u_w:
1631 case Mips::BI__builtin_msa_insve_w:
1632 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001633 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
1634 // These intrinsics take an unsigned 1 bit immediate.
1635 case Mips::BI__builtin_msa_copy_s_d:
1636 case Mips::BI__builtin_msa_copy_u_d:
1637 case Mips::BI__builtin_msa_insve_d:
1638 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001639 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
1640 // Memory offsets and immediate loads.
1641 // These intrinsics take a signed 10 bit immediate.
Petar Jovanovic9b8b9e82017-03-31 16:16:43 +00001642 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001643 case Mips::BI__builtin_msa_ldi_h:
1644 case Mips::BI__builtin_msa_ldi_w:
1645 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
1646 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break;
1647 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break;
1648 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break;
1649 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break;
1650 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break;
1651 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break;
1652 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break;
1653 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00001654 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001655
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001656 if (!m)
1657 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1658
1659 return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
1660 SemaBuiltinConstantArgMultiple(TheCall, i, m);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001661}
1662
Kit Bartone50adcb2015-03-30 19:40:59 +00001663bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1664 unsigned i = 0, l = 0, u = 0;
Nemanja Ivanovic239eec72015-04-09 23:58:16 +00001665 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
1666 BuiltinID == PPC::BI__builtin_divdeu ||
1667 BuiltinID == PPC::BI__builtin_bpermd;
1668 bool IsTarget64Bit = Context.getTargetInfo()
1669 .getTypeWidth(Context
1670 .getTargetInfo()
1671 .getIntPtrType()) == 64;
1672 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
1673 BuiltinID == PPC::BI__builtin_divweu ||
1674 BuiltinID == PPC::BI__builtin_divde ||
1675 BuiltinID == PPC::BI__builtin_divdeu;
1676
1677 if (Is64BitBltin && !IsTarget64Bit)
1678 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
1679 << TheCall->getSourceRange();
1680
1681 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
1682 (BuiltinID == PPC::BI__builtin_bpermd &&
1683 !Context.getTargetInfo().hasFeature("bpermd")))
1684 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
1685 << TheCall->getSourceRange();
1686
Kit Bartone50adcb2015-03-30 19:40:59 +00001687 switch (BuiltinID) {
1688 default: return false;
1689 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
1690 case PPC::BI__builtin_altivec_crypto_vshasigmad:
1691 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1692 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1693 case PPC::BI__builtin_tbegin:
1694 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
1695 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
1696 case PPC::BI__builtin_tabortwc:
1697 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
1698 case PPC::BI__builtin_tabortwci:
1699 case PPC::BI__builtin_tabortdci:
1700 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
1701 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
Tony Jiangbbc48e92017-05-24 15:13:32 +00001702 case PPC::BI__builtin_vsx_xxpermdi:
Tony Jiang9aa2c032017-05-24 15:54:13 +00001703 case PPC::BI__builtin_vsx_xxsldwi:
Tony Jiangbbc48e92017-05-24 15:13:32 +00001704 return SemaBuiltinVSX(TheCall);
Kit Bartone50adcb2015-03-30 19:40:59 +00001705 }
1706 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1707}
1708
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001709bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
1710 CallExpr *TheCall) {
1711 if (BuiltinID == SystemZ::BI__builtin_tabort) {
1712 Expr *Arg = TheCall->getArg(0);
1713 llvm::APSInt AbortCode(32);
1714 if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
1715 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
1716 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
1717 << Arg->getSourceRange();
1718 }
1719
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001720 // For intrinsics which take an immediate value as part of the instruction,
1721 // range check them here.
1722 unsigned i = 0, l = 0, u = 0;
1723 switch (BuiltinID) {
1724 default: return false;
1725 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
1726 case SystemZ::BI__builtin_s390_verimb:
1727 case SystemZ::BI__builtin_s390_verimh:
1728 case SystemZ::BI__builtin_s390_verimf:
1729 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
1730 case SystemZ::BI__builtin_s390_vfaeb:
1731 case SystemZ::BI__builtin_s390_vfaeh:
1732 case SystemZ::BI__builtin_s390_vfaef:
1733 case SystemZ::BI__builtin_s390_vfaebs:
1734 case SystemZ::BI__builtin_s390_vfaehs:
1735 case SystemZ::BI__builtin_s390_vfaefs:
1736 case SystemZ::BI__builtin_s390_vfaezb:
1737 case SystemZ::BI__builtin_s390_vfaezh:
1738 case SystemZ::BI__builtin_s390_vfaezf:
1739 case SystemZ::BI__builtin_s390_vfaezbs:
1740 case SystemZ::BI__builtin_s390_vfaezhs:
1741 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
Ulrich Weigandcac24ab2017-07-17 17:45:57 +00001742 case SystemZ::BI__builtin_s390_vfisb:
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001743 case SystemZ::BI__builtin_s390_vfidb:
1744 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1745 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
Ulrich Weigandcac24ab2017-07-17 17:45:57 +00001746 case SystemZ::BI__builtin_s390_vftcisb:
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001747 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
1748 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
1749 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
1750 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
1751 case SystemZ::BI__builtin_s390_vstrcb:
1752 case SystemZ::BI__builtin_s390_vstrch:
1753 case SystemZ::BI__builtin_s390_vstrcf:
1754 case SystemZ::BI__builtin_s390_vstrczb:
1755 case SystemZ::BI__builtin_s390_vstrczh:
1756 case SystemZ::BI__builtin_s390_vstrczf:
1757 case SystemZ::BI__builtin_s390_vstrcbs:
1758 case SystemZ::BI__builtin_s390_vstrchs:
1759 case SystemZ::BI__builtin_s390_vstrcfs:
1760 case SystemZ::BI__builtin_s390_vstrczbs:
1761 case SystemZ::BI__builtin_s390_vstrczhs:
1762 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
Ulrich Weigandcac24ab2017-07-17 17:45:57 +00001763 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
1764 case SystemZ::BI__builtin_s390_vfminsb:
1765 case SystemZ::BI__builtin_s390_vfmaxsb:
1766 case SystemZ::BI__builtin_s390_vfmindb:
1767 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001768 }
1769 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001770}
1771
Craig Topper5ba2c502015-11-07 08:08:31 +00001772/// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
1773/// This checks that the target supports __builtin_cpu_supports and
1774/// that the string argument is constant and valid.
1775static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
1776 Expr *Arg = TheCall->getArg(0);
1777
1778 // Check if the argument is a string literal.
1779 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1780 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1781 << Arg->getSourceRange();
1782
1783 // Check the contents of the string.
1784 StringRef Feature =
1785 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1786 if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
1787 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
1788 << Arg->getSourceRange();
1789 return false;
1790}
1791
Craig Toppera7e253e2016-09-23 04:48:31 +00001792// Check if the rounding mode is legal.
1793bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
1794 // Indicates if this instruction has rounding control or just SAE.
1795 bool HasRC = false;
1796
1797 unsigned ArgNum = 0;
1798 switch (BuiltinID) {
1799 default:
1800 return false;
1801 case X86::BI__builtin_ia32_vcvttsd2si32:
1802 case X86::BI__builtin_ia32_vcvttsd2si64:
1803 case X86::BI__builtin_ia32_vcvttsd2usi32:
1804 case X86::BI__builtin_ia32_vcvttsd2usi64:
1805 case X86::BI__builtin_ia32_vcvttss2si32:
1806 case X86::BI__builtin_ia32_vcvttss2si64:
1807 case X86::BI__builtin_ia32_vcvttss2usi32:
1808 case X86::BI__builtin_ia32_vcvttss2usi64:
1809 ArgNum = 1;
1810 break;
1811 case X86::BI__builtin_ia32_cvtps2pd512_mask:
1812 case X86::BI__builtin_ia32_cvttpd2dq512_mask:
1813 case X86::BI__builtin_ia32_cvttpd2qq512_mask:
1814 case X86::BI__builtin_ia32_cvttpd2udq512_mask:
1815 case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
1816 case X86::BI__builtin_ia32_cvttps2dq512_mask:
1817 case X86::BI__builtin_ia32_cvttps2qq512_mask:
1818 case X86::BI__builtin_ia32_cvttps2udq512_mask:
1819 case X86::BI__builtin_ia32_cvttps2uqq512_mask:
1820 case X86::BI__builtin_ia32_exp2pd_mask:
1821 case X86::BI__builtin_ia32_exp2ps_mask:
1822 case X86::BI__builtin_ia32_getexppd512_mask:
1823 case X86::BI__builtin_ia32_getexpps512_mask:
1824 case X86::BI__builtin_ia32_rcp28pd_mask:
1825 case X86::BI__builtin_ia32_rcp28ps_mask:
1826 case X86::BI__builtin_ia32_rsqrt28pd_mask:
1827 case X86::BI__builtin_ia32_rsqrt28ps_mask:
1828 case X86::BI__builtin_ia32_vcomisd:
1829 case X86::BI__builtin_ia32_vcomiss:
1830 case X86::BI__builtin_ia32_vcvtph2ps512_mask:
1831 ArgNum = 3;
1832 break;
1833 case X86::BI__builtin_ia32_cmppd512_mask:
1834 case X86::BI__builtin_ia32_cmpps512_mask:
1835 case X86::BI__builtin_ia32_cmpsd_mask:
1836 case X86::BI__builtin_ia32_cmpss_mask:
Craig Topper8e066312016-11-07 07:01:09 +00001837 case X86::BI__builtin_ia32_cvtss2sd_round_mask:
Craig Toppera7e253e2016-09-23 04:48:31 +00001838 case X86::BI__builtin_ia32_getexpsd128_round_mask:
1839 case X86::BI__builtin_ia32_getexpss128_round_mask:
Craig Topper8e066312016-11-07 07:01:09 +00001840 case X86::BI__builtin_ia32_maxpd512_mask:
1841 case X86::BI__builtin_ia32_maxps512_mask:
1842 case X86::BI__builtin_ia32_maxsd_round_mask:
1843 case X86::BI__builtin_ia32_maxss_round_mask:
1844 case X86::BI__builtin_ia32_minpd512_mask:
1845 case X86::BI__builtin_ia32_minps512_mask:
1846 case X86::BI__builtin_ia32_minsd_round_mask:
1847 case X86::BI__builtin_ia32_minss_round_mask:
Craig Toppera7e253e2016-09-23 04:48:31 +00001848 case X86::BI__builtin_ia32_rcp28sd_round_mask:
1849 case X86::BI__builtin_ia32_rcp28ss_round_mask:
1850 case X86::BI__builtin_ia32_reducepd512_mask:
1851 case X86::BI__builtin_ia32_reduceps512_mask:
1852 case X86::BI__builtin_ia32_rndscalepd_mask:
1853 case X86::BI__builtin_ia32_rndscaleps_mask:
1854 case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
1855 case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
1856 ArgNum = 4;
1857 break;
1858 case X86::BI__builtin_ia32_fixupimmpd512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001859 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001860 case X86::BI__builtin_ia32_fixupimmps512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001861 case X86::BI__builtin_ia32_fixupimmps512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001862 case X86::BI__builtin_ia32_fixupimmsd_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001863 case X86::BI__builtin_ia32_fixupimmsd_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001864 case X86::BI__builtin_ia32_fixupimmss_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001865 case X86::BI__builtin_ia32_fixupimmss_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001866 case X86::BI__builtin_ia32_rangepd512_mask:
1867 case X86::BI__builtin_ia32_rangeps512_mask:
1868 case X86::BI__builtin_ia32_rangesd128_round_mask:
1869 case X86::BI__builtin_ia32_rangess128_round_mask:
1870 case X86::BI__builtin_ia32_reducesd_mask:
1871 case X86::BI__builtin_ia32_reducess_mask:
1872 case X86::BI__builtin_ia32_rndscalesd_round_mask:
1873 case X86::BI__builtin_ia32_rndscaless_round_mask:
1874 ArgNum = 5;
1875 break;
Craig Topper7609f1c2016-10-01 21:03:50 +00001876 case X86::BI__builtin_ia32_vcvtsd2si64:
1877 case X86::BI__builtin_ia32_vcvtsd2si32:
1878 case X86::BI__builtin_ia32_vcvtsd2usi32:
1879 case X86::BI__builtin_ia32_vcvtsd2usi64:
1880 case X86::BI__builtin_ia32_vcvtss2si32:
1881 case X86::BI__builtin_ia32_vcvtss2si64:
1882 case X86::BI__builtin_ia32_vcvtss2usi32:
1883 case X86::BI__builtin_ia32_vcvtss2usi64:
1884 ArgNum = 1;
1885 HasRC = true;
1886 break;
Craig Topper8e066312016-11-07 07:01:09 +00001887 case X86::BI__builtin_ia32_cvtsi2sd64:
1888 case X86::BI__builtin_ia32_cvtsi2ss32:
1889 case X86::BI__builtin_ia32_cvtsi2ss64:
Craig Topper7609f1c2016-10-01 21:03:50 +00001890 case X86::BI__builtin_ia32_cvtusi2sd64:
1891 case X86::BI__builtin_ia32_cvtusi2ss32:
1892 case X86::BI__builtin_ia32_cvtusi2ss64:
1893 ArgNum = 2;
1894 HasRC = true;
1895 break;
1896 case X86::BI__builtin_ia32_cvtdq2ps512_mask:
1897 case X86::BI__builtin_ia32_cvtudq2ps512_mask:
1898 case X86::BI__builtin_ia32_cvtpd2ps512_mask:
1899 case X86::BI__builtin_ia32_cvtpd2qq512_mask:
1900 case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
1901 case X86::BI__builtin_ia32_cvtps2qq512_mask:
1902 case X86::BI__builtin_ia32_cvtps2uqq512_mask:
1903 case X86::BI__builtin_ia32_cvtqq2pd512_mask:
1904 case X86::BI__builtin_ia32_cvtqq2ps512_mask:
1905 case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
1906 case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
Craig Topper8e066312016-11-07 07:01:09 +00001907 case X86::BI__builtin_ia32_sqrtpd512_mask:
1908 case X86::BI__builtin_ia32_sqrtps512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001909 ArgNum = 3;
1910 HasRC = true;
1911 break;
1912 case X86::BI__builtin_ia32_addpd512_mask:
1913 case X86::BI__builtin_ia32_addps512_mask:
1914 case X86::BI__builtin_ia32_divpd512_mask:
1915 case X86::BI__builtin_ia32_divps512_mask:
1916 case X86::BI__builtin_ia32_mulpd512_mask:
1917 case X86::BI__builtin_ia32_mulps512_mask:
1918 case X86::BI__builtin_ia32_subpd512_mask:
1919 case X86::BI__builtin_ia32_subps512_mask:
1920 case X86::BI__builtin_ia32_addss_round_mask:
1921 case X86::BI__builtin_ia32_addsd_round_mask:
1922 case X86::BI__builtin_ia32_divss_round_mask:
1923 case X86::BI__builtin_ia32_divsd_round_mask:
1924 case X86::BI__builtin_ia32_mulss_round_mask:
1925 case X86::BI__builtin_ia32_mulsd_round_mask:
1926 case X86::BI__builtin_ia32_subss_round_mask:
1927 case X86::BI__builtin_ia32_subsd_round_mask:
1928 case X86::BI__builtin_ia32_scalefpd512_mask:
1929 case X86::BI__builtin_ia32_scalefps512_mask:
1930 case X86::BI__builtin_ia32_scalefsd_round_mask:
1931 case X86::BI__builtin_ia32_scalefss_round_mask:
1932 case X86::BI__builtin_ia32_getmantpd512_mask:
1933 case X86::BI__builtin_ia32_getmantps512_mask:
Craig Topper8e066312016-11-07 07:01:09 +00001934 case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
1935 case X86::BI__builtin_ia32_sqrtsd_round_mask:
1936 case X86::BI__builtin_ia32_sqrtss_round_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001937 case X86::BI__builtin_ia32_vfmaddpd512_mask:
1938 case X86::BI__builtin_ia32_vfmaddpd512_mask3:
1939 case X86::BI__builtin_ia32_vfmaddpd512_maskz:
1940 case X86::BI__builtin_ia32_vfmaddps512_mask:
1941 case X86::BI__builtin_ia32_vfmaddps512_mask3:
1942 case X86::BI__builtin_ia32_vfmaddps512_maskz:
1943 case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
1944 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
1945 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
1946 case X86::BI__builtin_ia32_vfmaddsubps512_mask:
1947 case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
1948 case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
1949 case X86::BI__builtin_ia32_vfmsubpd512_mask3:
1950 case X86::BI__builtin_ia32_vfmsubps512_mask3:
1951 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
1952 case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
1953 case X86::BI__builtin_ia32_vfnmaddpd512_mask:
1954 case X86::BI__builtin_ia32_vfnmaddps512_mask:
1955 case X86::BI__builtin_ia32_vfnmsubpd512_mask:
1956 case X86::BI__builtin_ia32_vfnmsubpd512_mask3:
1957 case X86::BI__builtin_ia32_vfnmsubps512_mask:
1958 case X86::BI__builtin_ia32_vfnmsubps512_mask3:
1959 case X86::BI__builtin_ia32_vfmaddsd3_mask:
1960 case X86::BI__builtin_ia32_vfmaddsd3_maskz:
1961 case X86::BI__builtin_ia32_vfmaddsd3_mask3:
1962 case X86::BI__builtin_ia32_vfmaddss3_mask:
1963 case X86::BI__builtin_ia32_vfmaddss3_maskz:
1964 case X86::BI__builtin_ia32_vfmaddss3_mask3:
1965 ArgNum = 4;
1966 HasRC = true;
1967 break;
1968 case X86::BI__builtin_ia32_getmantsd_round_mask:
1969 case X86::BI__builtin_ia32_getmantss_round_mask:
1970 ArgNum = 5;
1971 HasRC = true;
1972 break;
Craig Toppera7e253e2016-09-23 04:48:31 +00001973 }
1974
1975 llvm::APSInt Result;
1976
1977 // We can't check the value of a dependent argument.
1978 Expr *Arg = TheCall->getArg(ArgNum);
1979 if (Arg->isTypeDependent() || Arg->isValueDependent())
1980 return false;
1981
1982 // Check constant-ness first.
1983 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
1984 return true;
1985
1986 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
1987 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
1988 // combined with ROUND_NO_EXC.
1989 if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
1990 Result == 8/*ROUND_NO_EXC*/ ||
1991 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
1992 return false;
1993
1994 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding)
1995 << Arg->getSourceRange();
1996}
1997
Craig Topperdf5beb22017-03-13 17:16:50 +00001998// Check if the gather/scatter scale is legal.
1999bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
2000 CallExpr *TheCall) {
2001 unsigned ArgNum = 0;
2002 switch (BuiltinID) {
2003 default:
2004 return false;
2005 case X86::BI__builtin_ia32_gatherpfdpd:
2006 case X86::BI__builtin_ia32_gatherpfdps:
2007 case X86::BI__builtin_ia32_gatherpfqpd:
2008 case X86::BI__builtin_ia32_gatherpfqps:
2009 case X86::BI__builtin_ia32_scatterpfdpd:
2010 case X86::BI__builtin_ia32_scatterpfdps:
2011 case X86::BI__builtin_ia32_scatterpfqpd:
2012 case X86::BI__builtin_ia32_scatterpfqps:
2013 ArgNum = 3;
2014 break;
2015 case X86::BI__builtin_ia32_gatherd_pd:
2016 case X86::BI__builtin_ia32_gatherd_pd256:
2017 case X86::BI__builtin_ia32_gatherq_pd:
2018 case X86::BI__builtin_ia32_gatherq_pd256:
2019 case X86::BI__builtin_ia32_gatherd_ps:
2020 case X86::BI__builtin_ia32_gatherd_ps256:
2021 case X86::BI__builtin_ia32_gatherq_ps:
2022 case X86::BI__builtin_ia32_gatherq_ps256:
2023 case X86::BI__builtin_ia32_gatherd_q:
2024 case X86::BI__builtin_ia32_gatherd_q256:
2025 case X86::BI__builtin_ia32_gatherq_q:
2026 case X86::BI__builtin_ia32_gatherq_q256:
2027 case X86::BI__builtin_ia32_gatherd_d:
2028 case X86::BI__builtin_ia32_gatherd_d256:
2029 case X86::BI__builtin_ia32_gatherq_d:
2030 case X86::BI__builtin_ia32_gatherq_d256:
2031 case X86::BI__builtin_ia32_gather3div2df:
2032 case X86::BI__builtin_ia32_gather3div2di:
2033 case X86::BI__builtin_ia32_gather3div4df:
2034 case X86::BI__builtin_ia32_gather3div4di:
2035 case X86::BI__builtin_ia32_gather3div4sf:
2036 case X86::BI__builtin_ia32_gather3div4si:
2037 case X86::BI__builtin_ia32_gather3div8sf:
2038 case X86::BI__builtin_ia32_gather3div8si:
2039 case X86::BI__builtin_ia32_gather3siv2df:
2040 case X86::BI__builtin_ia32_gather3siv2di:
2041 case X86::BI__builtin_ia32_gather3siv4df:
2042 case X86::BI__builtin_ia32_gather3siv4di:
2043 case X86::BI__builtin_ia32_gather3siv4sf:
2044 case X86::BI__builtin_ia32_gather3siv4si:
2045 case X86::BI__builtin_ia32_gather3siv8sf:
2046 case X86::BI__builtin_ia32_gather3siv8si:
2047 case X86::BI__builtin_ia32_gathersiv8df:
2048 case X86::BI__builtin_ia32_gathersiv16sf:
2049 case X86::BI__builtin_ia32_gatherdiv8df:
2050 case X86::BI__builtin_ia32_gatherdiv16sf:
2051 case X86::BI__builtin_ia32_gathersiv8di:
2052 case X86::BI__builtin_ia32_gathersiv16si:
2053 case X86::BI__builtin_ia32_gatherdiv8di:
2054 case X86::BI__builtin_ia32_gatherdiv16si:
2055 case X86::BI__builtin_ia32_scatterdiv2df:
2056 case X86::BI__builtin_ia32_scatterdiv2di:
2057 case X86::BI__builtin_ia32_scatterdiv4df:
2058 case X86::BI__builtin_ia32_scatterdiv4di:
2059 case X86::BI__builtin_ia32_scatterdiv4sf:
2060 case X86::BI__builtin_ia32_scatterdiv4si:
2061 case X86::BI__builtin_ia32_scatterdiv8sf:
2062 case X86::BI__builtin_ia32_scatterdiv8si:
2063 case X86::BI__builtin_ia32_scattersiv2df:
2064 case X86::BI__builtin_ia32_scattersiv2di:
2065 case X86::BI__builtin_ia32_scattersiv4df:
2066 case X86::BI__builtin_ia32_scattersiv4di:
2067 case X86::BI__builtin_ia32_scattersiv4sf:
2068 case X86::BI__builtin_ia32_scattersiv4si:
2069 case X86::BI__builtin_ia32_scattersiv8sf:
2070 case X86::BI__builtin_ia32_scattersiv8si:
2071 case X86::BI__builtin_ia32_scattersiv8df:
2072 case X86::BI__builtin_ia32_scattersiv16sf:
2073 case X86::BI__builtin_ia32_scatterdiv8df:
2074 case X86::BI__builtin_ia32_scatterdiv16sf:
2075 case X86::BI__builtin_ia32_scattersiv8di:
2076 case X86::BI__builtin_ia32_scattersiv16si:
2077 case X86::BI__builtin_ia32_scatterdiv8di:
2078 case X86::BI__builtin_ia32_scatterdiv16si:
2079 ArgNum = 4;
2080 break;
2081 }
2082
2083 llvm::APSInt Result;
2084
2085 // We can't check the value of a dependent argument.
2086 Expr *Arg = TheCall->getArg(ArgNum);
2087 if (Arg->isTypeDependent() || Arg->isValueDependent())
2088 return false;
2089
2090 // Check constant-ness first.
2091 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2092 return true;
2093
2094 if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
2095 return false;
2096
2097 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_scale)
2098 << Arg->getSourceRange();
2099}
2100
Craig Topperf0ddc892016-09-23 04:48:27 +00002101bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2102 if (BuiltinID == X86::BI__builtin_cpu_supports)
2103 return SemaBuiltinCpuSupports(*this, TheCall);
2104
2105 if (BuiltinID == X86::BI__builtin_ms_va_start)
Reid Kleckner2b0fa122017-05-02 20:10:03 +00002106 return SemaBuiltinVAStart(BuiltinID, TheCall);
Craig Topperf0ddc892016-09-23 04:48:27 +00002107
Craig Toppera7e253e2016-09-23 04:48:31 +00002108 // If the intrinsic has rounding or SAE make sure its valid.
2109 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
2110 return true;
2111
Craig Topperdf5beb22017-03-13 17:16:50 +00002112 // If the intrinsic has a gather/scatter scale immediate make sure its valid.
2113 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
2114 return true;
2115
Craig Topperf0ddc892016-09-23 04:48:27 +00002116 // For intrinsics which take an immediate value as part of the instruction,
2117 // range check them here.
2118 int i = 0, l = 0, u = 0;
2119 switch (BuiltinID) {
2120 default:
2121 return false;
Richard Trieucc3949d2016-02-18 22:34:54 +00002122 case X86::BI_mm_prefetch:
Craig Topper39c87102016-05-18 03:18:12 +00002123 i = 1; l = 0; u = 3;
2124 break;
Richard Trieucc3949d2016-02-18 22:34:54 +00002125 case X86::BI__builtin_ia32_sha1rnds4:
Craig Topper39c87102016-05-18 03:18:12 +00002126 case X86::BI__builtin_ia32_shuf_f32x4_256_mask:
2127 case X86::BI__builtin_ia32_shuf_f64x2_256_mask:
2128 case X86::BI__builtin_ia32_shuf_i32x4_256_mask:
2129 case X86::BI__builtin_ia32_shuf_i64x2_256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002130 i = 2; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00002131 break;
Craig Topper1a8b0472015-01-31 08:57:52 +00002132 case X86::BI__builtin_ia32_vpermil2pd:
2133 case X86::BI__builtin_ia32_vpermil2pd256:
2134 case X86::BI__builtin_ia32_vpermil2ps:
Richard Trieucc3949d2016-02-18 22:34:54 +00002135 case X86::BI__builtin_ia32_vpermil2ps256:
Craig Topper39c87102016-05-18 03:18:12 +00002136 i = 3; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00002137 break;
Craig Topper95b0d732015-01-25 23:30:05 +00002138 case X86::BI__builtin_ia32_cmpb128_mask:
2139 case X86::BI__builtin_ia32_cmpw128_mask:
2140 case X86::BI__builtin_ia32_cmpd128_mask:
2141 case X86::BI__builtin_ia32_cmpq128_mask:
2142 case X86::BI__builtin_ia32_cmpb256_mask:
2143 case X86::BI__builtin_ia32_cmpw256_mask:
2144 case X86::BI__builtin_ia32_cmpd256_mask:
2145 case X86::BI__builtin_ia32_cmpq256_mask:
2146 case X86::BI__builtin_ia32_cmpb512_mask:
2147 case X86::BI__builtin_ia32_cmpw512_mask:
2148 case X86::BI__builtin_ia32_cmpd512_mask:
2149 case X86::BI__builtin_ia32_cmpq512_mask:
2150 case X86::BI__builtin_ia32_ucmpb128_mask:
2151 case X86::BI__builtin_ia32_ucmpw128_mask:
2152 case X86::BI__builtin_ia32_ucmpd128_mask:
2153 case X86::BI__builtin_ia32_ucmpq128_mask:
2154 case X86::BI__builtin_ia32_ucmpb256_mask:
2155 case X86::BI__builtin_ia32_ucmpw256_mask:
2156 case X86::BI__builtin_ia32_ucmpd256_mask:
2157 case X86::BI__builtin_ia32_ucmpq256_mask:
2158 case X86::BI__builtin_ia32_ucmpb512_mask:
2159 case X86::BI__builtin_ia32_ucmpw512_mask:
2160 case X86::BI__builtin_ia32_ucmpd512_mask:
Richard Trieucc3949d2016-02-18 22:34:54 +00002161 case X86::BI__builtin_ia32_ucmpq512_mask:
Craig Topper8dd7d0d2015-02-13 06:04:48 +00002162 case X86::BI__builtin_ia32_vpcomub:
2163 case X86::BI__builtin_ia32_vpcomuw:
2164 case X86::BI__builtin_ia32_vpcomud:
2165 case X86::BI__builtin_ia32_vpcomuq:
2166 case X86::BI__builtin_ia32_vpcomb:
2167 case X86::BI__builtin_ia32_vpcomw:
2168 case X86::BI__builtin_ia32_vpcomd:
Richard Trieucc3949d2016-02-18 22:34:54 +00002169 case X86::BI__builtin_ia32_vpcomq:
Craig Topper39c87102016-05-18 03:18:12 +00002170 i = 2; l = 0; u = 7;
2171 break;
2172 case X86::BI__builtin_ia32_roundps:
2173 case X86::BI__builtin_ia32_roundpd:
2174 case X86::BI__builtin_ia32_roundps256:
2175 case X86::BI__builtin_ia32_roundpd256:
Craig Topper39c87102016-05-18 03:18:12 +00002176 i = 1; l = 0; u = 15;
2177 break;
2178 case X86::BI__builtin_ia32_roundss:
2179 case X86::BI__builtin_ia32_roundsd:
2180 case X86::BI__builtin_ia32_rangepd128_mask:
2181 case X86::BI__builtin_ia32_rangepd256_mask:
2182 case X86::BI__builtin_ia32_rangepd512_mask:
2183 case X86::BI__builtin_ia32_rangeps128_mask:
2184 case X86::BI__builtin_ia32_rangeps256_mask:
2185 case X86::BI__builtin_ia32_rangeps512_mask:
2186 case X86::BI__builtin_ia32_getmantsd_round_mask:
2187 case X86::BI__builtin_ia32_getmantss_round_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002188 i = 2; l = 0; u = 15;
2189 break;
2190 case X86::BI__builtin_ia32_cmpps:
2191 case X86::BI__builtin_ia32_cmpss:
2192 case X86::BI__builtin_ia32_cmppd:
2193 case X86::BI__builtin_ia32_cmpsd:
2194 case X86::BI__builtin_ia32_cmpps256:
2195 case X86::BI__builtin_ia32_cmppd256:
2196 case X86::BI__builtin_ia32_cmpps128_mask:
2197 case X86::BI__builtin_ia32_cmppd128_mask:
2198 case X86::BI__builtin_ia32_cmpps256_mask:
2199 case X86::BI__builtin_ia32_cmppd256_mask:
2200 case X86::BI__builtin_ia32_cmpps512_mask:
2201 case X86::BI__builtin_ia32_cmppd512_mask:
2202 case X86::BI__builtin_ia32_cmpsd_mask:
2203 case X86::BI__builtin_ia32_cmpss_mask:
2204 i = 2; l = 0; u = 31;
2205 break;
2206 case X86::BI__builtin_ia32_xabort:
2207 i = 0; l = -128; u = 255;
2208 break;
2209 case X86::BI__builtin_ia32_pshufw:
2210 case X86::BI__builtin_ia32_aeskeygenassist128:
2211 i = 1; l = -128; u = 255;
2212 break;
2213 case X86::BI__builtin_ia32_vcvtps2ph:
2214 case X86::BI__builtin_ia32_vcvtps2ph256:
Craig Topper39c87102016-05-18 03:18:12 +00002215 case X86::BI__builtin_ia32_rndscaleps_128_mask:
2216 case X86::BI__builtin_ia32_rndscalepd_128_mask:
2217 case X86::BI__builtin_ia32_rndscaleps_256_mask:
2218 case X86::BI__builtin_ia32_rndscalepd_256_mask:
2219 case X86::BI__builtin_ia32_rndscaleps_mask:
2220 case X86::BI__builtin_ia32_rndscalepd_mask:
2221 case X86::BI__builtin_ia32_reducepd128_mask:
2222 case X86::BI__builtin_ia32_reducepd256_mask:
2223 case X86::BI__builtin_ia32_reducepd512_mask:
2224 case X86::BI__builtin_ia32_reduceps128_mask:
2225 case X86::BI__builtin_ia32_reduceps256_mask:
2226 case X86::BI__builtin_ia32_reduceps512_mask:
2227 case X86::BI__builtin_ia32_prold512_mask:
2228 case X86::BI__builtin_ia32_prolq512_mask:
2229 case X86::BI__builtin_ia32_prold128_mask:
2230 case X86::BI__builtin_ia32_prold256_mask:
2231 case X86::BI__builtin_ia32_prolq128_mask:
2232 case X86::BI__builtin_ia32_prolq256_mask:
2233 case X86::BI__builtin_ia32_prord128_mask:
2234 case X86::BI__builtin_ia32_prord256_mask:
2235 case X86::BI__builtin_ia32_prorq128_mask:
2236 case X86::BI__builtin_ia32_prorq256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002237 case X86::BI__builtin_ia32_fpclasspd128_mask:
2238 case X86::BI__builtin_ia32_fpclasspd256_mask:
2239 case X86::BI__builtin_ia32_fpclassps128_mask:
2240 case X86::BI__builtin_ia32_fpclassps256_mask:
2241 case X86::BI__builtin_ia32_fpclassps512_mask:
2242 case X86::BI__builtin_ia32_fpclasspd512_mask:
2243 case X86::BI__builtin_ia32_fpclasssd_mask:
2244 case X86::BI__builtin_ia32_fpclassss_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002245 i = 1; l = 0; u = 255;
2246 break;
2247 case X86::BI__builtin_ia32_palignr:
2248 case X86::BI__builtin_ia32_insertps128:
2249 case X86::BI__builtin_ia32_dpps:
2250 case X86::BI__builtin_ia32_dppd:
2251 case X86::BI__builtin_ia32_dpps256:
2252 case X86::BI__builtin_ia32_mpsadbw128:
2253 case X86::BI__builtin_ia32_mpsadbw256:
2254 case X86::BI__builtin_ia32_pcmpistrm128:
2255 case X86::BI__builtin_ia32_pcmpistri128:
2256 case X86::BI__builtin_ia32_pcmpistria128:
2257 case X86::BI__builtin_ia32_pcmpistric128:
2258 case X86::BI__builtin_ia32_pcmpistrio128:
2259 case X86::BI__builtin_ia32_pcmpistris128:
2260 case X86::BI__builtin_ia32_pcmpistriz128:
2261 case X86::BI__builtin_ia32_pclmulqdq128:
2262 case X86::BI__builtin_ia32_vperm2f128_pd256:
2263 case X86::BI__builtin_ia32_vperm2f128_ps256:
2264 case X86::BI__builtin_ia32_vperm2f128_si256:
2265 case X86::BI__builtin_ia32_permti256:
2266 i = 2; l = -128; u = 255;
2267 break;
2268 case X86::BI__builtin_ia32_palignr128:
2269 case X86::BI__builtin_ia32_palignr256:
Craig Topper39c87102016-05-18 03:18:12 +00002270 case X86::BI__builtin_ia32_palignr512_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002271 case X86::BI__builtin_ia32_vcomisd:
2272 case X86::BI__builtin_ia32_vcomiss:
2273 case X86::BI__builtin_ia32_shuf_f32x4_mask:
2274 case X86::BI__builtin_ia32_shuf_f64x2_mask:
2275 case X86::BI__builtin_ia32_shuf_i32x4_mask:
2276 case X86::BI__builtin_ia32_shuf_i64x2_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002277 case X86::BI__builtin_ia32_dbpsadbw128_mask:
2278 case X86::BI__builtin_ia32_dbpsadbw256_mask:
2279 case X86::BI__builtin_ia32_dbpsadbw512_mask:
2280 i = 2; l = 0; u = 255;
2281 break;
2282 case X86::BI__builtin_ia32_fixupimmpd512_mask:
2283 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
2284 case X86::BI__builtin_ia32_fixupimmps512_mask:
2285 case X86::BI__builtin_ia32_fixupimmps512_maskz:
2286 case X86::BI__builtin_ia32_fixupimmsd_mask:
2287 case X86::BI__builtin_ia32_fixupimmsd_maskz:
2288 case X86::BI__builtin_ia32_fixupimmss_mask:
2289 case X86::BI__builtin_ia32_fixupimmss_maskz:
2290 case X86::BI__builtin_ia32_fixupimmpd128_mask:
2291 case X86::BI__builtin_ia32_fixupimmpd128_maskz:
2292 case X86::BI__builtin_ia32_fixupimmpd256_mask:
2293 case X86::BI__builtin_ia32_fixupimmpd256_maskz:
2294 case X86::BI__builtin_ia32_fixupimmps128_mask:
2295 case X86::BI__builtin_ia32_fixupimmps128_maskz:
2296 case X86::BI__builtin_ia32_fixupimmps256_mask:
2297 case X86::BI__builtin_ia32_fixupimmps256_maskz:
2298 case X86::BI__builtin_ia32_pternlogd512_mask:
2299 case X86::BI__builtin_ia32_pternlogd512_maskz:
2300 case X86::BI__builtin_ia32_pternlogq512_mask:
2301 case X86::BI__builtin_ia32_pternlogq512_maskz:
2302 case X86::BI__builtin_ia32_pternlogd128_mask:
2303 case X86::BI__builtin_ia32_pternlogd128_maskz:
2304 case X86::BI__builtin_ia32_pternlogd256_mask:
2305 case X86::BI__builtin_ia32_pternlogd256_maskz:
2306 case X86::BI__builtin_ia32_pternlogq128_mask:
2307 case X86::BI__builtin_ia32_pternlogq128_maskz:
2308 case X86::BI__builtin_ia32_pternlogq256_mask:
2309 case X86::BI__builtin_ia32_pternlogq256_maskz:
2310 i = 3; l = 0; u = 255;
2311 break;
Craig Topper9625db02017-03-12 22:19:10 +00002312 case X86::BI__builtin_ia32_gatherpfdpd:
2313 case X86::BI__builtin_ia32_gatherpfdps:
2314 case X86::BI__builtin_ia32_gatherpfqpd:
2315 case X86::BI__builtin_ia32_gatherpfqps:
2316 case X86::BI__builtin_ia32_scatterpfdpd:
2317 case X86::BI__builtin_ia32_scatterpfdps:
2318 case X86::BI__builtin_ia32_scatterpfqpd:
2319 case X86::BI__builtin_ia32_scatterpfqps:
Craig Topperf771f79b2017-03-31 17:22:30 +00002320 i = 4; l = 2; u = 3;
Craig Topper9625db02017-03-12 22:19:10 +00002321 break;
Craig Topper39c87102016-05-18 03:18:12 +00002322 case X86::BI__builtin_ia32_pcmpestrm128:
2323 case X86::BI__builtin_ia32_pcmpestri128:
2324 case X86::BI__builtin_ia32_pcmpestria128:
2325 case X86::BI__builtin_ia32_pcmpestric128:
2326 case X86::BI__builtin_ia32_pcmpestrio128:
2327 case X86::BI__builtin_ia32_pcmpestris128:
2328 case X86::BI__builtin_ia32_pcmpestriz128:
2329 i = 4; l = -128; u = 255;
2330 break;
2331 case X86::BI__builtin_ia32_rndscalesd_round_mask:
2332 case X86::BI__builtin_ia32_rndscaless_round_mask:
2333 i = 4; l = 0; u = 255;
Richard Trieucc3949d2016-02-18 22:34:54 +00002334 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002335 }
Craig Topperdd84ec52014-12-27 07:00:08 +00002336 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002337}
2338
Richard Smith55ce3522012-06-25 20:30:08 +00002339/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
2340/// parameter with the FormatAttr's correct format_idx and firstDataArg.
2341/// Returns true when the format fits the function and the FormatStringInfo has
2342/// been populated.
2343bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
2344 FormatStringInfo *FSI) {
2345 FSI->HasVAListArg = Format->getFirstArg() == 0;
2346 FSI->FormatIdx = Format->getFormatIdx() - 1;
2347 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002348
Richard Smith55ce3522012-06-25 20:30:08 +00002349 // The way the format attribute works in GCC, the implicit this argument
2350 // of member functions is counted. However, it doesn't appear in our own
2351 // lists, so decrement format_idx in that case.
2352 if (IsCXXMember) {
2353 if(FSI->FormatIdx == 0)
2354 return false;
2355 --FSI->FormatIdx;
2356 if (FSI->FirstDataArg != 0)
2357 --FSI->FirstDataArg;
2358 }
2359 return true;
2360}
Mike Stump11289f42009-09-09 15:08:12 +00002361
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002362/// Checks if a the given expression evaluates to null.
2363///
2364/// \brief Returns true if the value evaluates to null.
George Burgess IV850269a2015-12-08 22:02:00 +00002365static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002366 // If the expression has non-null type, it doesn't evaluate to null.
2367 if (auto nullability
2368 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
2369 if (*nullability == NullabilityKind::NonNull)
2370 return false;
2371 }
2372
Ted Kremeneka146db32014-01-17 06:24:47 +00002373 // As a special case, transparent unions initialized with zero are
2374 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002375 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +00002376 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2377 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002378 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +00002379 if (const InitListExpr *ILE =
2380 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002381 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +00002382 }
2383
2384 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +00002385 return (!Expr->isValueDependent() &&
2386 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
2387 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002388}
2389
2390static void CheckNonNullArgument(Sema &S,
2391 const Expr *ArgExpr,
2392 SourceLocation CallSiteLoc) {
2393 if (CheckNonNullExpr(S, ArgExpr))
Eric Fiselier18677d52015-10-09 00:17:57 +00002394 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
2395 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
Ted Kremeneka146db32014-01-17 06:24:47 +00002396}
2397
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002398bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
2399 FormatStringInfo FSI;
2400 if ((GetFormatStringType(Format) == FST_NSString) &&
2401 getFormatStringInfo(Format, false, &FSI)) {
2402 Idx = FSI.FormatIdx;
2403 return true;
2404 }
2405 return false;
2406}
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002407/// \brief Diagnose use of %s directive in an NSString which is being passed
2408/// as formatting string to formatting method.
2409static void
2410DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
2411 const NamedDecl *FDecl,
2412 Expr **Args,
2413 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002414 unsigned Idx = 0;
2415 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002416 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
2417 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002418 Idx = 2;
2419 Format = true;
2420 }
2421 else
2422 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2423 if (S.GetFormatNSStringIdx(I, Idx)) {
2424 Format = true;
2425 break;
2426 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002427 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002428 if (!Format || NumArgs <= Idx)
2429 return;
2430 const Expr *FormatExpr = Args[Idx];
2431 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
2432 FormatExpr = CSCE->getSubExpr();
2433 const StringLiteral *FormatString;
2434 if (const ObjCStringLiteral *OSL =
2435 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
2436 FormatString = OSL->getString();
2437 else
2438 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
2439 if (!FormatString)
2440 return;
2441 if (S.FormatStringHasSArg(FormatString)) {
2442 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2443 << "%s" << 1 << 1;
2444 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
2445 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002446 }
2447}
2448
Douglas Gregorb4866e82015-06-19 18:13:19 +00002449/// Determine whether the given type has a non-null nullability annotation.
2450static bool isNonNullType(ASTContext &ctx, QualType type) {
2451 if (auto nullability = type->getNullability(ctx))
2452 return *nullability == NullabilityKind::NonNull;
2453
2454 return false;
2455}
2456
Ted Kremenek2bc73332014-01-17 06:24:43 +00002457static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00002458 const NamedDecl *FDecl,
Douglas Gregorb4866e82015-06-19 18:13:19 +00002459 const FunctionProtoType *Proto,
Richard Smith588bd9b2014-08-27 04:59:42 +00002460 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00002461 SourceLocation CallSiteLoc) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002462 assert((FDecl || Proto) && "Need a function declaration or prototype");
2463
Ted Kremenek9aedc152014-01-17 06:24:56 +00002464 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00002465 llvm::SmallBitVector NonNullArgs;
Douglas Gregorb4866e82015-06-19 18:13:19 +00002466 if (FDecl) {
2467 // Handle the nonnull attribute on the function/method declaration itself.
2468 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
2469 if (!NonNull->args_size()) {
2470 // Easy case: all pointer arguments are nonnull.
2471 for (const auto *Arg : Args)
2472 if (S.isValidPointerAttrType(Arg->getType()))
2473 CheckNonNullArgument(S, Arg, CallSiteLoc);
2474 return;
2475 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002476
Douglas Gregorb4866e82015-06-19 18:13:19 +00002477 for (unsigned Val : NonNull->args()) {
2478 if (Val >= Args.size())
2479 continue;
2480 if (NonNullArgs.empty())
2481 NonNullArgs.resize(Args.size());
2482 NonNullArgs.set(Val);
2483 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002484 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00002485 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00002486
Douglas Gregorb4866e82015-06-19 18:13:19 +00002487 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
2488 // Handle the nonnull attribute on the parameters of the
2489 // function/method.
2490 ArrayRef<ParmVarDecl*> parms;
2491 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
2492 parms = FD->parameters();
2493 else
2494 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
2495
2496 unsigned ParamIndex = 0;
2497 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
2498 I != E; ++I, ++ParamIndex) {
2499 const ParmVarDecl *PVD = *I;
2500 if (PVD->hasAttr<NonNullAttr>() ||
2501 isNonNullType(S.Context, PVD->getType())) {
2502 if (NonNullArgs.empty())
2503 NonNullArgs.resize(Args.size());
Ted Kremenek9aedc152014-01-17 06:24:56 +00002504
Douglas Gregorb4866e82015-06-19 18:13:19 +00002505 NonNullArgs.set(ParamIndex);
2506 }
2507 }
2508 } else {
2509 // If we have a non-function, non-method declaration but no
2510 // function prototype, try to dig out the function prototype.
2511 if (!Proto) {
2512 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
2513 QualType type = VD->getType().getNonReferenceType();
2514 if (auto pointerType = type->getAs<PointerType>())
2515 type = pointerType->getPointeeType();
2516 else if (auto blockType = type->getAs<BlockPointerType>())
2517 type = blockType->getPointeeType();
2518 // FIXME: data member pointers?
2519
2520 // Dig out the function prototype, if there is one.
2521 Proto = type->getAs<FunctionProtoType>();
2522 }
2523 }
2524
2525 // Fill in non-null argument information from the nullability
2526 // information on the parameter types (if we have them).
2527 if (Proto) {
2528 unsigned Index = 0;
2529 for (auto paramType : Proto->getParamTypes()) {
2530 if (isNonNullType(S.Context, paramType)) {
2531 if (NonNullArgs.empty())
2532 NonNullArgs.resize(Args.size());
2533
2534 NonNullArgs.set(Index);
2535 }
2536
2537 ++Index;
2538 }
2539 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00002540 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002541
Douglas Gregorb4866e82015-06-19 18:13:19 +00002542 // Check for non-null arguments.
2543 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
2544 ArgIndex != ArgIndexEnd; ++ArgIndex) {
Richard Smith588bd9b2014-08-27 04:59:42 +00002545 if (NonNullArgs[ArgIndex])
2546 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00002547 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00002548}
2549
Richard Smith55ce3522012-06-25 20:30:08 +00002550/// Handles the checks for format strings, non-POD arguments to vararg
George Burgess IVce6284b2017-01-28 02:19:40 +00002551/// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
2552/// attributes.
Douglas Gregorb4866e82015-06-19 18:13:19 +00002553void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
George Burgess IVce6284b2017-01-28 02:19:40 +00002554 const Expr *ThisArg, ArrayRef<const Expr *> Args,
2555 bool IsMemberFunction, SourceLocation Loc,
2556 SourceRange Range, VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00002557 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00002558 if (CurContext->isDependentContext())
2559 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00002560
Ted Kremenekb8176da2010-09-09 04:33:05 +00002561 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00002562 llvm::SmallBitVector CheckedVarArgs;
2563 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002564 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00002565 // Only create vector if there are format attributes.
2566 CheckedVarArgs.resize(Args.size());
2567
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002568 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00002569 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00002570 }
Richard Smithd7293d72013-08-05 18:49:43 +00002571 }
Richard Smith55ce3522012-06-25 20:30:08 +00002572
2573 // Refuse POD arguments that weren't caught by the format string
2574 // checks above.
Richard Smith836de6b2016-12-19 23:59:34 +00002575 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
2576 if (CallType != VariadicDoesNotApply &&
2577 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002578 unsigned NumParams = Proto ? Proto->getNumParams()
2579 : FDecl && isa<FunctionDecl>(FDecl)
2580 ? cast<FunctionDecl>(FDecl)->getNumParams()
2581 : FDecl && isa<ObjCMethodDecl>(FDecl)
2582 ? cast<ObjCMethodDecl>(FDecl)->param_size()
2583 : 0;
2584
Alp Toker9cacbab2014-01-20 20:26:09 +00002585 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00002586 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00002587 if (const Expr *Arg = Args[ArgIdx]) {
2588 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
2589 checkVariadicArgument(Arg, CallType);
2590 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00002591 }
Richard Smithd7293d72013-08-05 18:49:43 +00002592 }
Mike Stump11289f42009-09-09 15:08:12 +00002593
Douglas Gregorb4866e82015-06-19 18:13:19 +00002594 if (FDecl || Proto) {
2595 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00002596
Richard Trieu41bc0992013-06-22 00:20:41 +00002597 // Type safety checking.
Douglas Gregorb4866e82015-06-19 18:13:19 +00002598 if (FDecl) {
2599 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
2600 CheckArgumentWithTypeTag(I, Args.data());
2601 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00002602 }
George Burgess IVce6284b2017-01-28 02:19:40 +00002603
2604 if (FD)
2605 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
Richard Smith55ce3522012-06-25 20:30:08 +00002606}
2607
2608/// CheckConstructorCall - Check a constructor call for correctness and safety
2609/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002610void Sema::CheckConstructorCall(FunctionDecl *FDecl,
2611 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002612 const FunctionProtoType *Proto,
2613 SourceLocation Loc) {
2614 VariadicCallType CallType =
2615 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
George Burgess IVce6284b2017-01-28 02:19:40 +00002616 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
2617 Loc, SourceRange(), CallType);
Richard Smith55ce3522012-06-25 20:30:08 +00002618}
2619
2620/// CheckFunctionCall - Check a direct function call for various correctness
2621/// and safety properties not strictly enforced by the C type system.
2622bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
2623 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00002624 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
2625 isa<CXXMethodDecl>(FDecl);
2626 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
2627 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00002628 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
2629 TheCall->getCallee());
Eli Friedman726d11c2012-10-11 00:30:58 +00002630 Expr** Args = TheCall->getArgs();
2631 unsigned NumArgs = TheCall->getNumArgs();
George Burgess IVce6284b2017-01-28 02:19:40 +00002632
2633 Expr *ImplicitThis = nullptr;
Eli Friedmanadf42182012-10-11 00:34:15 +00002634 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00002635 // If this is a call to a member operator, hide the first argument
2636 // from checkCall.
2637 // FIXME: Our choice of AST representation here is less than ideal.
George Burgess IVce6284b2017-01-28 02:19:40 +00002638 ImplicitThis = Args[0];
Eli Friedman726d11c2012-10-11 00:30:58 +00002639 ++Args;
2640 --NumArgs;
George Burgess IVce6284b2017-01-28 02:19:40 +00002641 } else if (IsMemberFunction)
2642 ImplicitThis =
2643 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
2644
2645 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
Richard Smith55ce3522012-06-25 20:30:08 +00002646 IsMemberFunction, TheCall->getRParenLoc(),
2647 TheCall->getCallee()->getSourceRange(), CallType);
2648
2649 IdentifierInfo *FnInfo = FDecl->getIdentifier();
2650 // None of the checks below are needed for functions that don't have
2651 // simple names (e.g., C++ conversion functions).
2652 if (!FnInfo)
2653 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002654
Richard Trieua7f30b12016-12-06 01:42:28 +00002655 CheckAbsoluteValueFunction(TheCall, FDecl);
2656 CheckMaxUnsignedZero(TheCall, FDecl);
Richard Trieu67c00712016-12-05 23:41:46 +00002657
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002658 if (getLangOpts().ObjC1)
2659 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00002660
Anna Zaks22122702012-01-17 00:37:07 +00002661 unsigned CMId = FDecl->getMemoryFunctionKind();
2662 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00002663 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00002664
Anna Zaks201d4892012-01-13 21:52:01 +00002665 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00002666 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00002667 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00002668 else if (CMId == Builtin::BIstrncat)
2669 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00002670 else
Anna Zaks22122702012-01-17 00:37:07 +00002671 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00002672
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002673 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00002674}
2675
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002676bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00002677 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00002678 VariadicCallType CallType =
2679 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002680
George Burgess IVce6284b2017-01-28 02:19:40 +00002681 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
2682 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
Douglas Gregorb4866e82015-06-19 18:13:19 +00002683 CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002684
2685 return false;
2686}
2687
Richard Trieu664c4c62013-06-20 21:03:13 +00002688bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
2689 const FunctionProtoType *Proto) {
Aaron Ballmanb673c652015-04-23 16:14:19 +00002690 QualType Ty;
2691 if (const auto *V = dyn_cast<VarDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00002692 Ty = V->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00002693 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00002694 Ty = F->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00002695 else
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002696 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002697
Douglas Gregorb4866e82015-06-19 18:13:19 +00002698 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
2699 !Ty->isFunctionProtoType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002700 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002701
Richard Trieu664c4c62013-06-20 21:03:13 +00002702 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00002703 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00002704 CallType = VariadicDoesNotApply;
2705 } else if (Ty->isBlockPointerType()) {
2706 CallType = VariadicBlock;
2707 } else { // Ty->isFunctionPointerType()
2708 CallType = VariadicFunction;
2709 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002710
George Burgess IVce6284b2017-01-28 02:19:40 +00002711 checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
Douglas Gregorb4866e82015-06-19 18:13:19 +00002712 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2713 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00002714 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00002715
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002716 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00002717}
2718
Richard Trieu41bc0992013-06-22 00:20:41 +00002719/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
2720/// such as function pointers returned from functions.
2721bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002722 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00002723 TheCall->getCallee());
George Burgess IVce6284b2017-01-28 02:19:40 +00002724 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
Craig Topper8c2a2a02014-08-30 16:55:39 +00002725 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Douglas Gregorb4866e82015-06-19 18:13:19 +00002726 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00002727 TheCall->getCallee()->getSourceRange(), CallType);
2728
2729 return false;
2730}
2731
Tim Northovere94a34c2014-03-11 10:49:14 +00002732static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
JF Bastiendda2cb12016-04-18 18:01:49 +00002733 if (!llvm::isValidAtomicOrderingCABI(Ordering))
Tim Northovere94a34c2014-03-11 10:49:14 +00002734 return false;
2735
JF Bastiendda2cb12016-04-18 18:01:49 +00002736 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
Tim Northovere94a34c2014-03-11 10:49:14 +00002737 switch (Op) {
2738 case AtomicExpr::AO__c11_atomic_init:
2739 llvm_unreachable("There is no ordering argument for an init");
2740
2741 case AtomicExpr::AO__c11_atomic_load:
2742 case AtomicExpr::AO__atomic_load_n:
2743 case AtomicExpr::AO__atomic_load:
JF Bastiendda2cb12016-04-18 18:01:49 +00002744 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
2745 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00002746
2747 case AtomicExpr::AO__c11_atomic_store:
2748 case AtomicExpr::AO__atomic_store:
2749 case AtomicExpr::AO__atomic_store_n:
JF Bastiendda2cb12016-04-18 18:01:49 +00002750 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
2751 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
2752 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00002753
2754 default:
2755 return true;
2756 }
2757}
2758
Richard Smithfeea8832012-04-12 05:08:17 +00002759ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
2760 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002761 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
2762 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002763
Richard Smithfeea8832012-04-12 05:08:17 +00002764 // All these operations take one of the following forms:
2765 enum {
2766 // C __c11_atomic_init(A *, C)
2767 Init,
2768 // C __c11_atomic_load(A *, int)
2769 Load,
2770 // void __atomic_load(A *, CP, int)
Eric Fiselier8d662442016-03-30 23:39:56 +00002771 LoadCopy,
2772 // void __atomic_store(A *, CP, int)
Richard Smithfeea8832012-04-12 05:08:17 +00002773 Copy,
2774 // C __c11_atomic_add(A *, M, int)
2775 Arithmetic,
2776 // C __atomic_exchange_n(A *, CP, int)
2777 Xchg,
2778 // void __atomic_exchange(A *, C *, CP, int)
2779 GNUXchg,
2780 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
2781 C11CmpXchg,
2782 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
2783 GNUCmpXchg
2784 } Form = Init;
Eric Fiselier8d662442016-03-30 23:39:56 +00002785 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
2786 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
Richard Smithfeea8832012-04-12 05:08:17 +00002787 // where:
2788 // C is an appropriate type,
2789 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
2790 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
2791 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
2792 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002793
Gabor Horvath98bd0982015-03-16 09:59:54 +00002794 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
2795 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
2796 AtomicExpr::AO__atomic_load,
2797 "need to update code for modified C11 atomics");
Richard Smithfeea8832012-04-12 05:08:17 +00002798 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
2799 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
2800 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
2801 Op == AtomicExpr::AO__atomic_store_n ||
2802 Op == AtomicExpr::AO__atomic_exchange_n ||
2803 Op == AtomicExpr::AO__atomic_compare_exchange_n;
2804 bool IsAddSub = false;
2805
2806 switch (Op) {
2807 case AtomicExpr::AO__c11_atomic_init:
2808 Form = Init;
2809 break;
2810
2811 case AtomicExpr::AO__c11_atomic_load:
2812 case AtomicExpr::AO__atomic_load_n:
2813 Form = Load;
2814 break;
2815
Richard Smithfeea8832012-04-12 05:08:17 +00002816 case AtomicExpr::AO__atomic_load:
Eric Fiselier8d662442016-03-30 23:39:56 +00002817 Form = LoadCopy;
2818 break;
2819
2820 case AtomicExpr::AO__c11_atomic_store:
Richard Smithfeea8832012-04-12 05:08:17 +00002821 case AtomicExpr::AO__atomic_store:
2822 case AtomicExpr::AO__atomic_store_n:
2823 Form = Copy;
2824 break;
2825
2826 case AtomicExpr::AO__c11_atomic_fetch_add:
2827 case AtomicExpr::AO__c11_atomic_fetch_sub:
2828 case AtomicExpr::AO__atomic_fetch_add:
2829 case AtomicExpr::AO__atomic_fetch_sub:
2830 case AtomicExpr::AO__atomic_add_fetch:
2831 case AtomicExpr::AO__atomic_sub_fetch:
2832 IsAddSub = true;
2833 // Fall through.
2834 case AtomicExpr::AO__c11_atomic_fetch_and:
2835 case AtomicExpr::AO__c11_atomic_fetch_or:
2836 case AtomicExpr::AO__c11_atomic_fetch_xor:
2837 case AtomicExpr::AO__atomic_fetch_and:
2838 case AtomicExpr::AO__atomic_fetch_or:
2839 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00002840 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00002841 case AtomicExpr::AO__atomic_and_fetch:
2842 case AtomicExpr::AO__atomic_or_fetch:
2843 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00002844 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00002845 Form = Arithmetic;
2846 break;
2847
2848 case AtomicExpr::AO__c11_atomic_exchange:
2849 case AtomicExpr::AO__atomic_exchange_n:
2850 Form = Xchg;
2851 break;
2852
2853 case AtomicExpr::AO__atomic_exchange:
2854 Form = GNUXchg;
2855 break;
2856
2857 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
2858 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
2859 Form = C11CmpXchg;
2860 break;
2861
2862 case AtomicExpr::AO__atomic_compare_exchange:
2863 case AtomicExpr::AO__atomic_compare_exchange_n:
2864 Form = GNUCmpXchg;
2865 break;
2866 }
2867
2868 // Check we have the right number of arguments.
2869 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002870 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithfeea8832012-04-12 05:08:17 +00002871 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002872 << TheCall->getCallee()->getSourceRange();
2873 return ExprError();
Richard Smithfeea8832012-04-12 05:08:17 +00002874 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
2875 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002876 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00002877 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002878 << TheCall->getCallee()->getSourceRange();
2879 return ExprError();
2880 }
2881
Richard Smithfeea8832012-04-12 05:08:17 +00002882 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002883 Expr *Ptr = TheCall->getArg(0);
George Burgess IV92b43a42016-07-21 03:28:13 +00002884 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
2885 if (ConvertedPtr.isInvalid())
2886 return ExprError();
2887
2888 Ptr = ConvertedPtr.get();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002889 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
2890 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00002891 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002892 << Ptr->getType() << Ptr->getSourceRange();
2893 return ExprError();
2894 }
2895
Richard Smithfeea8832012-04-12 05:08:17 +00002896 // For a __c11 builtin, this should be a pointer to an _Atomic type.
2897 QualType AtomTy = pointerType->getPointeeType(); // 'A'
2898 QualType ValType = AtomTy; // 'C'
2899 if (IsC11) {
2900 if (!AtomTy->isAtomicType()) {
2901 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
2902 << Ptr->getType() << Ptr->getSourceRange();
2903 return ExprError();
2904 }
Richard Smithe00921a2012-09-15 06:09:58 +00002905 if (AtomTy.isConstQualified()) {
2906 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
2907 << Ptr->getType() << Ptr->getSourceRange();
2908 return ExprError();
2909 }
Richard Smithfeea8832012-04-12 05:08:17 +00002910 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eric Fiselier8d662442016-03-30 23:39:56 +00002911 } else if (Form != Load && Form != LoadCopy) {
Eric Fiseliera3a7c562015-10-04 00:11:02 +00002912 if (ValType.isConstQualified()) {
2913 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
2914 << Ptr->getType() << Ptr->getSourceRange();
2915 return ExprError();
2916 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002917 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002918
Richard Smithfeea8832012-04-12 05:08:17 +00002919 // For an arithmetic operation, the implied arithmetic must be well-formed.
2920 if (Form == Arithmetic) {
2921 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
2922 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
2923 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
2924 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2925 return ExprError();
2926 }
2927 if (!IsAddSub && !ValType->isIntegerType()) {
2928 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
2929 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2930 return ExprError();
2931 }
David Majnemere85cff82015-01-28 05:48:06 +00002932 if (IsC11 && ValType->isPointerType() &&
2933 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
2934 diag::err_incomplete_type)) {
2935 return ExprError();
2936 }
Richard Smithfeea8832012-04-12 05:08:17 +00002937 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
2938 // For __atomic_*_n operations, the value type must be a scalar integral or
2939 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002940 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00002941 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2942 return ExprError();
2943 }
2944
Eli Friedmanaa769812013-09-11 03:49:34 +00002945 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
2946 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00002947 // For GNU atomics, require a trivially-copyable type. This is not part of
2948 // the GNU atomics specification, but we enforce it for sanity.
2949 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002950 << Ptr->getType() << Ptr->getSourceRange();
2951 return ExprError();
2952 }
2953
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002954 switch (ValType.getObjCLifetime()) {
2955 case Qualifiers::OCL_None:
2956 case Qualifiers::OCL_ExplicitNone:
2957 // okay
2958 break;
2959
2960 case Qualifiers::OCL_Weak:
2961 case Qualifiers::OCL_Strong:
2962 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00002963 // FIXME: Can this happen? By this point, ValType should be known
2964 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002965 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
2966 << ValType << Ptr->getSourceRange();
2967 return ExprError();
2968 }
2969
David Majnemerc6eb6502015-06-03 00:26:35 +00002970 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the
2971 // volatile-ness of the pointee-type inject itself into the result or the
Eric Fiselier8d662442016-03-30 23:39:56 +00002972 // other operands. Similarly atomic_load can take a pointer to a const 'A'.
David Majnemerc6eb6502015-06-03 00:26:35 +00002973 ValType.removeLocalVolatile();
Eric Fiselier8d662442016-03-30 23:39:56 +00002974 ValType.removeLocalConst();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002975 QualType ResultType = ValType;
Eric Fiselier8d662442016-03-30 23:39:56 +00002976 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002977 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00002978 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002979 ResultType = Context.BoolTy;
2980
Richard Smithfeea8832012-04-12 05:08:17 +00002981 // The type of a parameter passed 'by value'. In the GNU atomics, such
2982 // arguments are actually passed as pointers.
2983 QualType ByValType = ValType; // 'CP'
2984 if (!IsC11 && !IsN)
2985 ByValType = Ptr->getType();
2986
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002987 // The first argument --- the pointer --- has a fixed type; we
2988 // deduce the types of the rest of the arguments accordingly. Walk
2989 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00002990 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002991 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00002992 if (i < NumVals[Form] + 1) {
2993 switch (i) {
2994 case 1:
2995 // The second argument is the non-atomic operand. For arithmetic, this
2996 // is always passed by value, and for a compare_exchange it is always
2997 // passed by address. For the rest, GNU uses by-address and C11 uses
2998 // by-value.
2999 assert(Form != Load);
3000 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
3001 Ty = ValType;
3002 else if (Form == Copy || Form == Xchg)
3003 Ty = ByValType;
3004 else if (Form == Arithmetic)
3005 Ty = Context.getPointerDiffType();
Anastasia Stulova76fd1052015-12-22 15:14:54 +00003006 else {
3007 Expr *ValArg = TheCall->getArg(i);
Alex Lorenz67522152016-11-23 16:57:03 +00003008 // Treat this argument as _Nonnull as we want to show a warning if
3009 // NULL is passed into it.
3010 CheckNonNullArgument(*this, ValArg, DRE->getLocStart());
Anastasia Stulova76fd1052015-12-22 15:14:54 +00003011 unsigned AS = 0;
3012 // Keep address space of non-atomic pointer type.
3013 if (const PointerType *PtrTy =
3014 ValArg->getType()->getAs<PointerType>()) {
3015 AS = PtrTy->getPointeeType().getAddressSpace();
3016 }
3017 Ty = Context.getPointerType(
3018 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
3019 }
Richard Smithfeea8832012-04-12 05:08:17 +00003020 break;
3021 case 2:
3022 // The third argument to compare_exchange / GNU exchange is a
3023 // (pointer to a) desired value.
3024 Ty = ByValType;
3025 break;
3026 case 3:
3027 // The fourth argument to GNU compare_exchange is a 'weak' flag.
3028 Ty = Context.BoolTy;
3029 break;
3030 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003031 } else {
3032 // The order(s) are always converted to int.
3033 Ty = Context.IntTy;
3034 }
Richard Smithfeea8832012-04-12 05:08:17 +00003035
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003036 InitializedEntity Entity =
3037 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00003038 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003039 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3040 if (Arg.isInvalid())
3041 return true;
3042 TheCall->setArg(i, Arg.get());
3043 }
3044
Richard Smithfeea8832012-04-12 05:08:17 +00003045 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003046 SmallVector<Expr*, 5> SubExprs;
3047 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00003048 switch (Form) {
3049 case Init:
3050 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00003051 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00003052 break;
3053 case Load:
3054 SubExprs.push_back(TheCall->getArg(1)); // Order
3055 break;
Eric Fiselier8d662442016-03-30 23:39:56 +00003056 case LoadCopy:
Richard Smithfeea8832012-04-12 05:08:17 +00003057 case Copy:
3058 case Arithmetic:
3059 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003060 SubExprs.push_back(TheCall->getArg(2)); // Order
3061 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00003062 break;
3063 case GNUXchg:
3064 // Note, AtomicExpr::getVal2() has a special case for this atomic.
3065 SubExprs.push_back(TheCall->getArg(3)); // Order
3066 SubExprs.push_back(TheCall->getArg(1)); // Val1
3067 SubExprs.push_back(TheCall->getArg(2)); // Val2
3068 break;
3069 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003070 SubExprs.push_back(TheCall->getArg(3)); // Order
3071 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003072 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00003073 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00003074 break;
3075 case GNUCmpXchg:
3076 SubExprs.push_back(TheCall->getArg(4)); // Order
3077 SubExprs.push_back(TheCall->getArg(1)); // Val1
3078 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
3079 SubExprs.push_back(TheCall->getArg(2)); // Val2
3080 SubExprs.push_back(TheCall->getArg(3)); // Weak
3081 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003082 }
Tim Northovere94a34c2014-03-11 10:49:14 +00003083
3084 if (SubExprs.size() >= 2 && Form != Init) {
3085 llvm::APSInt Result(32);
3086 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
3087 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00003088 Diag(SubExprs[1]->getLocStart(),
3089 diag::warn_atomic_op_has_invalid_memory_order)
3090 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00003091 }
3092
Fariborz Jahanian615de762013-05-28 17:37:39 +00003093 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
3094 SubExprs, ResultType, Op,
3095 TheCall->getRParenLoc());
3096
3097 if ((Op == AtomicExpr::AO__c11_atomic_load ||
3098 (Op == AtomicExpr::AO__c11_atomic_store)) &&
3099 Context.AtomicUsesUnsupportedLibcall(AE))
3100 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
3101 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003102
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003103 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003104}
3105
John McCall29ad95b2011-08-27 01:09:30 +00003106/// checkBuiltinArgument - Given a call to a builtin function, perform
3107/// normal type-checking on the given argument, updating the call in
3108/// place. This is useful when a builtin function requires custom
3109/// type-checking for some of its arguments but not necessarily all of
3110/// them.
3111///
3112/// Returns true on error.
3113static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
3114 FunctionDecl *Fn = E->getDirectCallee();
3115 assert(Fn && "builtin call without direct callee!");
3116
3117 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
3118 InitializedEntity Entity =
3119 InitializedEntity::InitializeParameter(S.Context, Param);
3120
3121 ExprResult Arg = E->getArg(0);
3122 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
3123 if (Arg.isInvalid())
3124 return true;
3125
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003126 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00003127 return false;
3128}
3129
Chris Lattnerdc046542009-05-08 06:58:22 +00003130/// SemaBuiltinAtomicOverloaded - We have a call to a function like
3131/// __sync_fetch_and_add, which is an overloaded function based on the pointer
3132/// type of its first argument. The main ActOnCallExpr routines have already
3133/// promoted the types of arguments because all of these calls are prototyped as
3134/// void(...).
3135///
3136/// This function goes through and does final semantic checking for these
3137/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00003138ExprResult
3139Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003140 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00003141 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3142 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3143
3144 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003145 if (TheCall->getNumArgs() < 1) {
3146 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3147 << 0 << 1 << TheCall->getNumArgs()
3148 << TheCall->getCallee()->getSourceRange();
3149 return ExprError();
3150 }
Mike Stump11289f42009-09-09 15:08:12 +00003151
Chris Lattnerdc046542009-05-08 06:58:22 +00003152 // Inspect the first argument of the atomic builtin. This should always be
3153 // a pointer type, whose element is an integral scalar or pointer type.
3154 // Because it is a pointer type, we don't have to worry about any implicit
3155 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003156 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00003157 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00003158 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
3159 if (FirstArgResult.isInvalid())
3160 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003161 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00003162 TheCall->setArg(0, FirstArg);
3163
John McCall31168b02011-06-15 23:02:42 +00003164 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
3165 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003166 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3167 << FirstArg->getType() << FirstArg->getSourceRange();
3168 return ExprError();
3169 }
Mike Stump11289f42009-09-09 15:08:12 +00003170
John McCall31168b02011-06-15 23:02:42 +00003171 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00003172 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003173 !ValType->isBlockPointerType()) {
3174 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
3175 << FirstArg->getType() << FirstArg->getSourceRange();
3176 return ExprError();
3177 }
Chris Lattnerdc046542009-05-08 06:58:22 +00003178
John McCall31168b02011-06-15 23:02:42 +00003179 switch (ValType.getObjCLifetime()) {
3180 case Qualifiers::OCL_None:
3181 case Qualifiers::OCL_ExplicitNone:
3182 // okay
3183 break;
3184
3185 case Qualifiers::OCL_Weak:
3186 case Qualifiers::OCL_Strong:
3187 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00003188 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00003189 << ValType << FirstArg->getSourceRange();
3190 return ExprError();
3191 }
3192
John McCallb50451a2011-10-05 07:41:44 +00003193 // Strip any qualifiers off ValType.
3194 ValType = ValType.getUnqualifiedType();
3195
Chandler Carruth3973af72010-07-18 20:54:12 +00003196 // The majority of builtins return a value, but a few have special return
3197 // types, so allow them to override appropriately below.
3198 QualType ResultType = ValType;
3199
Chris Lattnerdc046542009-05-08 06:58:22 +00003200 // We need to figure out which concrete builtin this maps onto. For example,
3201 // __sync_fetch_and_add with a 2 byte object turns into
3202 // __sync_fetch_and_add_2.
3203#define BUILTIN_ROW(x) \
3204 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
3205 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00003206
Chris Lattnerdc046542009-05-08 06:58:22 +00003207 static const unsigned BuiltinIndices[][5] = {
3208 BUILTIN_ROW(__sync_fetch_and_add),
3209 BUILTIN_ROW(__sync_fetch_and_sub),
3210 BUILTIN_ROW(__sync_fetch_and_or),
3211 BUILTIN_ROW(__sync_fetch_and_and),
3212 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00003213 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00003214
Chris Lattnerdc046542009-05-08 06:58:22 +00003215 BUILTIN_ROW(__sync_add_and_fetch),
3216 BUILTIN_ROW(__sync_sub_and_fetch),
3217 BUILTIN_ROW(__sync_and_and_fetch),
3218 BUILTIN_ROW(__sync_or_and_fetch),
3219 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00003220 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00003221
Chris Lattnerdc046542009-05-08 06:58:22 +00003222 BUILTIN_ROW(__sync_val_compare_and_swap),
3223 BUILTIN_ROW(__sync_bool_compare_and_swap),
3224 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00003225 BUILTIN_ROW(__sync_lock_release),
3226 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00003227 };
Mike Stump11289f42009-09-09 15:08:12 +00003228#undef BUILTIN_ROW
3229
Chris Lattnerdc046542009-05-08 06:58:22 +00003230 // Determine the index of the size.
3231 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00003232 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00003233 case 1: SizeIndex = 0; break;
3234 case 2: SizeIndex = 1; break;
3235 case 4: SizeIndex = 2; break;
3236 case 8: SizeIndex = 3; break;
3237 case 16: SizeIndex = 4; break;
3238 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003239 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
3240 << FirstArg->getType() << FirstArg->getSourceRange();
3241 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00003242 }
Mike Stump11289f42009-09-09 15:08:12 +00003243
Chris Lattnerdc046542009-05-08 06:58:22 +00003244 // Each of these builtins has one pointer argument, followed by some number of
3245 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
3246 // that we ignore. Find out which row of BuiltinIndices to read from as well
3247 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00003248 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00003249 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00003250 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00003251 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00003252 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00003253 case Builtin::BI__sync_fetch_and_add:
3254 case Builtin::BI__sync_fetch_and_add_1:
3255 case Builtin::BI__sync_fetch_and_add_2:
3256 case Builtin::BI__sync_fetch_and_add_4:
3257 case Builtin::BI__sync_fetch_and_add_8:
3258 case Builtin::BI__sync_fetch_and_add_16:
3259 BuiltinIndex = 0;
3260 break;
3261
3262 case Builtin::BI__sync_fetch_and_sub:
3263 case Builtin::BI__sync_fetch_and_sub_1:
3264 case Builtin::BI__sync_fetch_and_sub_2:
3265 case Builtin::BI__sync_fetch_and_sub_4:
3266 case Builtin::BI__sync_fetch_and_sub_8:
3267 case Builtin::BI__sync_fetch_and_sub_16:
3268 BuiltinIndex = 1;
3269 break;
3270
3271 case Builtin::BI__sync_fetch_and_or:
3272 case Builtin::BI__sync_fetch_and_or_1:
3273 case Builtin::BI__sync_fetch_and_or_2:
3274 case Builtin::BI__sync_fetch_and_or_4:
3275 case Builtin::BI__sync_fetch_and_or_8:
3276 case Builtin::BI__sync_fetch_and_or_16:
3277 BuiltinIndex = 2;
3278 break;
3279
3280 case Builtin::BI__sync_fetch_and_and:
3281 case Builtin::BI__sync_fetch_and_and_1:
3282 case Builtin::BI__sync_fetch_and_and_2:
3283 case Builtin::BI__sync_fetch_and_and_4:
3284 case Builtin::BI__sync_fetch_and_and_8:
3285 case Builtin::BI__sync_fetch_and_and_16:
3286 BuiltinIndex = 3;
3287 break;
Mike Stump11289f42009-09-09 15:08:12 +00003288
Douglas Gregor73722482011-11-28 16:30:08 +00003289 case Builtin::BI__sync_fetch_and_xor:
3290 case Builtin::BI__sync_fetch_and_xor_1:
3291 case Builtin::BI__sync_fetch_and_xor_2:
3292 case Builtin::BI__sync_fetch_and_xor_4:
3293 case Builtin::BI__sync_fetch_and_xor_8:
3294 case Builtin::BI__sync_fetch_and_xor_16:
3295 BuiltinIndex = 4;
3296 break;
3297
Hal Finkeld2208b52014-10-02 20:53:50 +00003298 case Builtin::BI__sync_fetch_and_nand:
3299 case Builtin::BI__sync_fetch_and_nand_1:
3300 case Builtin::BI__sync_fetch_and_nand_2:
3301 case Builtin::BI__sync_fetch_and_nand_4:
3302 case Builtin::BI__sync_fetch_and_nand_8:
3303 case Builtin::BI__sync_fetch_and_nand_16:
3304 BuiltinIndex = 5;
3305 WarnAboutSemanticsChange = true;
3306 break;
3307
Douglas Gregor73722482011-11-28 16:30:08 +00003308 case Builtin::BI__sync_add_and_fetch:
3309 case Builtin::BI__sync_add_and_fetch_1:
3310 case Builtin::BI__sync_add_and_fetch_2:
3311 case Builtin::BI__sync_add_and_fetch_4:
3312 case Builtin::BI__sync_add_and_fetch_8:
3313 case Builtin::BI__sync_add_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003314 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00003315 break;
3316
3317 case Builtin::BI__sync_sub_and_fetch:
3318 case Builtin::BI__sync_sub_and_fetch_1:
3319 case Builtin::BI__sync_sub_and_fetch_2:
3320 case Builtin::BI__sync_sub_and_fetch_4:
3321 case Builtin::BI__sync_sub_and_fetch_8:
3322 case Builtin::BI__sync_sub_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003323 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00003324 break;
3325
3326 case Builtin::BI__sync_and_and_fetch:
3327 case Builtin::BI__sync_and_and_fetch_1:
3328 case Builtin::BI__sync_and_and_fetch_2:
3329 case Builtin::BI__sync_and_and_fetch_4:
3330 case Builtin::BI__sync_and_and_fetch_8:
3331 case Builtin::BI__sync_and_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003332 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00003333 break;
3334
3335 case Builtin::BI__sync_or_and_fetch:
3336 case Builtin::BI__sync_or_and_fetch_1:
3337 case Builtin::BI__sync_or_and_fetch_2:
3338 case Builtin::BI__sync_or_and_fetch_4:
3339 case Builtin::BI__sync_or_and_fetch_8:
3340 case Builtin::BI__sync_or_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003341 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00003342 break;
3343
3344 case Builtin::BI__sync_xor_and_fetch:
3345 case Builtin::BI__sync_xor_and_fetch_1:
3346 case Builtin::BI__sync_xor_and_fetch_2:
3347 case Builtin::BI__sync_xor_and_fetch_4:
3348 case Builtin::BI__sync_xor_and_fetch_8:
3349 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003350 BuiltinIndex = 10;
3351 break;
3352
3353 case Builtin::BI__sync_nand_and_fetch:
3354 case Builtin::BI__sync_nand_and_fetch_1:
3355 case Builtin::BI__sync_nand_and_fetch_2:
3356 case Builtin::BI__sync_nand_and_fetch_4:
3357 case Builtin::BI__sync_nand_and_fetch_8:
3358 case Builtin::BI__sync_nand_and_fetch_16:
3359 BuiltinIndex = 11;
3360 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00003361 break;
Mike Stump11289f42009-09-09 15:08:12 +00003362
Chris Lattnerdc046542009-05-08 06:58:22 +00003363 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00003364 case Builtin::BI__sync_val_compare_and_swap_1:
3365 case Builtin::BI__sync_val_compare_and_swap_2:
3366 case Builtin::BI__sync_val_compare_and_swap_4:
3367 case Builtin::BI__sync_val_compare_and_swap_8:
3368 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003369 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00003370 NumFixed = 2;
3371 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003372
Chris Lattnerdc046542009-05-08 06:58:22 +00003373 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00003374 case Builtin::BI__sync_bool_compare_and_swap_1:
3375 case Builtin::BI__sync_bool_compare_and_swap_2:
3376 case Builtin::BI__sync_bool_compare_and_swap_4:
3377 case Builtin::BI__sync_bool_compare_and_swap_8:
3378 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003379 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00003380 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00003381 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00003382 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003383
3384 case Builtin::BI__sync_lock_test_and_set:
3385 case Builtin::BI__sync_lock_test_and_set_1:
3386 case Builtin::BI__sync_lock_test_and_set_2:
3387 case Builtin::BI__sync_lock_test_and_set_4:
3388 case Builtin::BI__sync_lock_test_and_set_8:
3389 case Builtin::BI__sync_lock_test_and_set_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003390 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00003391 break;
3392
Chris Lattnerdc046542009-05-08 06:58:22 +00003393 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00003394 case Builtin::BI__sync_lock_release_1:
3395 case Builtin::BI__sync_lock_release_2:
3396 case Builtin::BI__sync_lock_release_4:
3397 case Builtin::BI__sync_lock_release_8:
3398 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003399 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00003400 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00003401 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00003402 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003403
3404 case Builtin::BI__sync_swap:
3405 case Builtin::BI__sync_swap_1:
3406 case Builtin::BI__sync_swap_2:
3407 case Builtin::BI__sync_swap_4:
3408 case Builtin::BI__sync_swap_8:
3409 case Builtin::BI__sync_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003410 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00003411 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00003412 }
Mike Stump11289f42009-09-09 15:08:12 +00003413
Chris Lattnerdc046542009-05-08 06:58:22 +00003414 // Now that we know how many fixed arguments we expect, first check that we
3415 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003416 if (TheCall->getNumArgs() < 1+NumFixed) {
3417 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3418 << 0 << 1+NumFixed << TheCall->getNumArgs()
3419 << TheCall->getCallee()->getSourceRange();
3420 return ExprError();
3421 }
Mike Stump11289f42009-09-09 15:08:12 +00003422
Hal Finkeld2208b52014-10-02 20:53:50 +00003423 if (WarnAboutSemanticsChange) {
3424 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
3425 << TheCall->getCallee()->getSourceRange();
3426 }
3427
Chris Lattner5b9241b2009-05-08 15:36:58 +00003428 // Get the decl for the concrete builtin from this, we can tell what the
3429 // concrete integer type we should convert to is.
3430 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
Mehdi Amini7186a432016-10-11 19:04:24 +00003431 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00003432 FunctionDecl *NewBuiltinDecl;
3433 if (NewBuiltinID == BuiltinID)
3434 NewBuiltinDecl = FDecl;
3435 else {
3436 // Perform builtin lookup to avoid redeclaring it.
3437 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
3438 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
3439 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
3440 assert(Res.getFoundDecl());
3441 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00003442 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00003443 return ExprError();
3444 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003445
John McCallcf142162010-08-07 06:22:56 +00003446 // The first argument --- the pointer --- has a fixed type; we
3447 // deduce the types of the rest of the arguments accordingly. Walk
3448 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00003449 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00003450 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00003451
Chris Lattnerdc046542009-05-08 06:58:22 +00003452 // GCC does an implicit conversion to the pointer or integer ValType. This
3453 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00003454 // Initialize the argument.
3455 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3456 ValType, /*consume*/ false);
3457 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00003458 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003459 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003460
Chris Lattnerdc046542009-05-08 06:58:22 +00003461 // Okay, we have something that *can* be converted to the right type. Check
3462 // to see if there is a potentially weird extension going on here. This can
3463 // happen when you do an atomic operation on something like an char* and
3464 // pass in 42. The 42 gets converted to char. This is even more strange
3465 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00003466 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003467 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00003468 }
Mike Stump11289f42009-09-09 15:08:12 +00003469
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003470 ASTContext& Context = this->getASTContext();
3471
3472 // Create a new DeclRefExpr to refer to the new decl.
3473 DeclRefExpr* NewDRE = DeclRefExpr::Create(
3474 Context,
3475 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00003476 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003477 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00003478 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003479 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00003480 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003481 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00003482
Chris Lattnerdc046542009-05-08 06:58:22 +00003483 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00003484 // FIXME: This loses syntactic information.
3485 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
3486 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
3487 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003488 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00003489
Chandler Carruthbc8cab12010-07-18 07:23:17 +00003490 // Change the result type of the call to match the original value type. This
3491 // is arbitrary, but the codegen for these builtins ins design to handle it
3492 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00003493 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003494
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003495 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00003496}
3497
Michael Zolotukhin84df1232015-09-08 23:52:33 +00003498/// SemaBuiltinNontemporalOverloaded - We have a call to
3499/// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
3500/// overloaded function based on the pointer type of its last argument.
3501///
3502/// This function goes through and does final semantic checking for these
3503/// builtins.
3504ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
3505 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3506 DeclRefExpr *DRE =
3507 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3508 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3509 unsigned BuiltinID = FDecl->getBuiltinID();
3510 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
3511 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
3512 "Unexpected nontemporal load/store builtin!");
3513 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
3514 unsigned numArgs = isStore ? 2 : 1;
3515
3516 // Ensure that we have the proper number of arguments.
3517 if (checkArgCount(*this, TheCall, numArgs))
3518 return ExprError();
3519
3520 // Inspect the last argument of the nontemporal builtin. This should always
3521 // be a pointer type, from which we imply the type of the memory access.
3522 // Because it is a pointer type, we don't have to worry about any implicit
3523 // casts here.
3524 Expr *PointerArg = TheCall->getArg(numArgs - 1);
3525 ExprResult PointerArgResult =
3526 DefaultFunctionArrayLvalueConversion(PointerArg);
3527
3528 if (PointerArgResult.isInvalid())
3529 return ExprError();
3530 PointerArg = PointerArgResult.get();
3531 TheCall->setArg(numArgs - 1, PointerArg);
3532
3533 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
3534 if (!pointerType) {
3535 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
3536 << PointerArg->getType() << PointerArg->getSourceRange();
3537 return ExprError();
3538 }
3539
3540 QualType ValType = pointerType->getPointeeType();
3541
3542 // Strip any qualifiers off ValType.
3543 ValType = ValType.getUnqualifiedType();
3544 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3545 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
3546 !ValType->isVectorType()) {
3547 Diag(DRE->getLocStart(),
3548 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
3549 << PointerArg->getType() << PointerArg->getSourceRange();
3550 return ExprError();
3551 }
3552
3553 if (!isStore) {
3554 TheCall->setType(ValType);
3555 return TheCallResult;
3556 }
3557
3558 ExprResult ValArg = TheCall->getArg(0);
3559 InitializedEntity Entity = InitializedEntity::InitializeParameter(
3560 Context, ValType, /*consume*/ false);
3561 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
3562 if (ValArg.isInvalid())
3563 return ExprError();
3564
3565 TheCall->setArg(0, ValArg.get());
3566 TheCall->setType(Context.VoidTy);
3567 return TheCallResult;
3568}
3569
Chris Lattner6436fb62009-02-18 06:01:06 +00003570/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00003571/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00003572/// Note: It might also make sense to do the UTF-16 conversion here (would
3573/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00003574bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00003575 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00003576 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
3577
Douglas Gregorfb65e592011-07-27 05:40:30 +00003578 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00003579 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
3580 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00003581 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00003582 }
Mike Stump11289f42009-09-09 15:08:12 +00003583
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003584 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003585 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003586 unsigned NumBytes = String.size();
Justin Lebar90910552016-09-30 00:38:45 +00003587 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
3588 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
3589 llvm::UTF16 *ToPtr = &ToBuf[0];
3590
3591 llvm::ConversionResult Result =
3592 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
3593 ToPtr + NumBytes, llvm::strictConversion);
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003594 // Check for conversion failure.
Justin Lebar90910552016-09-30 00:38:45 +00003595 if (Result != llvm::conversionOK)
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003596 Diag(Arg->getLocStart(),
3597 diag::warn_cfstring_truncated) << Arg->getSourceRange();
3598 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00003599 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003600}
3601
Mehdi Amini06d367c2016-10-24 20:39:34 +00003602/// CheckObjCString - Checks that the format string argument to the os_log()
3603/// and os_trace() functions is correct, and converts it to const char *.
3604ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
3605 Arg = Arg->IgnoreParenCasts();
3606 auto *Literal = dyn_cast<StringLiteral>(Arg);
3607 if (!Literal) {
3608 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
3609 Literal = ObjcLiteral->getString();
3610 }
3611 }
3612
3613 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
3614 return ExprError(
3615 Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant)
3616 << Arg->getSourceRange());
3617 }
3618
3619 ExprResult Result(Literal);
3620 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
3621 InitializedEntity Entity =
3622 InitializedEntity::InitializeParameter(Context, ResultTy, false);
3623 Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
3624 return Result;
3625}
3626
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003627/// Check that the user is calling the appropriate va_start builtin for the
3628/// target and calling convention.
3629static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
3630 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
3631 bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
3632 bool IsWindows = TT.isOSWindows();
3633 bool IsMSVAStart = BuiltinID == X86::BI__builtin_ms_va_start;
3634 if (IsX64) {
3635 clang::CallingConv CC = CC_C;
3636 if (const FunctionDecl *FD = S.getCurFunctionDecl())
3637 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3638 if (IsMSVAStart) {
3639 // Don't allow this in System V ABI functions.
3640 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_X86_64Win64))
3641 return S.Diag(Fn->getLocStart(),
3642 diag::err_ms_va_start_used_in_sysv_function);
3643 } else {
3644 // On x86-64 Unix, don't allow this in Win64 ABI functions.
3645 // On x64 Windows, don't allow this in System V ABI functions.
3646 // (Yes, that means there's no corresponding way to support variadic
3647 // System V ABI functions on Windows.)
3648 if ((IsWindows && CC == CC_X86_64SysV) ||
3649 (!IsWindows && CC == CC_X86_64Win64))
3650 return S.Diag(Fn->getLocStart(),
3651 diag::err_va_start_used_in_wrong_abi_function)
3652 << !IsWindows;
3653 }
3654 return false;
3655 }
3656
3657 if (IsMSVAStart)
3658 return S.Diag(Fn->getLocStart(), diag::err_x86_builtin_64_only);
3659 return false;
3660}
3661
3662static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
3663 ParmVarDecl **LastParam = nullptr) {
3664 // Determine whether the current function, block, or obj-c method is variadic
3665 // and get its parameter list.
3666 bool IsVariadic = false;
3667 ArrayRef<ParmVarDecl *> Params;
Reid Klecknerf1deb832017-05-04 19:51:05 +00003668 DeclContext *Caller = S.CurContext;
3669 if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
3670 IsVariadic = Block->isVariadic();
3671 Params = Block->parameters();
3672 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003673 IsVariadic = FD->isVariadic();
3674 Params = FD->parameters();
Reid Klecknerf1deb832017-05-04 19:51:05 +00003675 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003676 IsVariadic = MD->isVariadic();
3677 // FIXME: This isn't correct for methods (results in bogus warning).
3678 Params = MD->parameters();
Reid Klecknerf1deb832017-05-04 19:51:05 +00003679 } else if (isa<CapturedDecl>(Caller)) {
3680 // We don't support va_start in a CapturedDecl.
3681 S.Diag(Fn->getLocStart(), diag::err_va_start_captured_stmt);
3682 return true;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003683 } else {
Reid Klecknerf1deb832017-05-04 19:51:05 +00003684 // This must be some other declcontext that parses exprs.
3685 S.Diag(Fn->getLocStart(), diag::err_va_start_outside_function);
3686 return true;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003687 }
3688
3689 if (!IsVariadic) {
Reid Klecknerf1deb832017-05-04 19:51:05 +00003690 S.Diag(Fn->getLocStart(), diag::err_va_start_fixed_function);
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003691 return true;
3692 }
3693
3694 if (LastParam)
3695 *LastParam = Params.empty() ? nullptr : Params.back();
3696
3697 return false;
3698}
3699
Charles Davisc7d5c942015-09-17 20:55:33 +00003700/// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
3701/// for validity. Emit an error and return true on failure; return false
3702/// on success.
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003703bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
Chris Lattner08464942007-12-28 05:29:59 +00003704 Expr *Fn = TheCall->getCallee();
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003705
3706 if (checkVAStartABI(*this, BuiltinID, Fn))
3707 return true;
3708
Chris Lattner08464942007-12-28 05:29:59 +00003709 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00003710 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003711 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003712 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3713 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00003714 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003715 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00003716 return true;
3717 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00003718
3719 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00003720 return Diag(TheCall->getLocEnd(),
3721 diag::err_typecheck_call_too_few_args_at_least)
3722 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00003723 }
3724
John McCall29ad95b2011-08-27 01:09:30 +00003725 // Type-check the first argument normally.
3726 if (checkBuiltinArgument(*this, TheCall, 0))
3727 return true;
3728
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003729 // Check that the current function is variadic, and get its last parameter.
3730 ParmVarDecl *LastParam;
3731 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
Chris Lattner43be2e62007-12-19 23:59:04 +00003732 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003733
Chris Lattner43be2e62007-12-19 23:59:04 +00003734 // Verify that the second argument to the builtin is the last argument of the
3735 // current function or method.
3736 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00003737 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00003738
Nico Weber9eea7642013-05-24 23:31:57 +00003739 // These are valid if SecondArgIsLastNamedArgument is false after the next
3740 // block.
3741 QualType Type;
3742 SourceLocation ParamLoc;
Aaron Ballman1de59c52016-04-24 13:30:21 +00003743 bool IsCRegister = false;
Nico Weber9eea7642013-05-24 23:31:57 +00003744
Anders Carlsson6a8350b2008-02-11 04:20:54 +00003745 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
3746 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003747 SecondArgIsLastNamedArgument = PV == LastParam;
Nico Weber9eea7642013-05-24 23:31:57 +00003748
3749 Type = PV->getType();
3750 ParamLoc = PV->getLocation();
Aaron Ballman1de59c52016-04-24 13:30:21 +00003751 IsCRegister =
3752 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
Chris Lattner43be2e62007-12-19 23:59:04 +00003753 }
3754 }
Mike Stump11289f42009-09-09 15:08:12 +00003755
Chris Lattner43be2e62007-12-19 23:59:04 +00003756 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00003757 Diag(TheCall->getArg(1)->getLocStart(),
Aaron Ballman05164812016-04-18 18:10:53 +00003758 diag::warn_second_arg_of_va_start_not_last_named_param);
Aaron Ballman1de59c52016-04-24 13:30:21 +00003759 else if (IsCRegister || Type->isReferenceType() ||
Aaron Ballmana4f597f2016-09-15 18:07:51 +00003760 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
3761 // Promotable integers are UB, but enumerations need a bit of
3762 // extra checking to see what their promotable type actually is.
3763 if (!Type->isPromotableIntegerType())
3764 return false;
3765 if (!Type->isEnumeralType())
3766 return true;
3767 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3768 return !(ED &&
3769 Context.typesAreCompatible(ED->getPromotionType(), Type));
3770 }()) {
Aaron Ballman1de59c52016-04-24 13:30:21 +00003771 unsigned Reason = 0;
3772 if (Type->isReferenceType()) Reason = 1;
3773 else if (IsCRegister) Reason = 2;
3774 Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
Nico Weber9eea7642013-05-24 23:31:57 +00003775 Diag(ParamLoc, diag::note_parameter_type) << Type;
3776 }
3777
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00003778 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00003779 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00003780}
Chris Lattner43be2e62007-12-19 23:59:04 +00003781
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00003782bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
3783 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
3784 // const char *named_addr);
3785
3786 Expr *Func = Call->getCallee();
3787
3788 if (Call->getNumArgs() < 3)
3789 return Diag(Call->getLocEnd(),
3790 diag::err_typecheck_call_too_few_args_at_least)
3791 << 0 /*function call*/ << 3 << Call->getNumArgs();
3792
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00003793 // Type-check the first argument normally.
3794 if (checkBuiltinArgument(*this, Call, 0))
3795 return true;
3796
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003797 // Check that the current function is variadic.
3798 if (checkVAStartIsInVariadicFunction(*this, Func))
3799 return true;
3800
Benjamin Kramere0ca6e12015-03-01 18:09:50 +00003801 const struct {
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00003802 unsigned ArgNo;
3803 QualType Type;
3804 } ArgumentTypes[] = {
3805 { 1, Context.getPointerType(Context.CharTy.withConst()) },
3806 { 2, Context.getSizeType() },
3807 };
3808
3809 for (const auto &AT : ArgumentTypes) {
3810 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
3811 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
3812 continue;
3813 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
3814 << Arg->getType() << AT.Type << 1 /* different class */
3815 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
3816 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
3817 }
3818
3819 return false;
3820}
3821
Chris Lattner2da14fb2007-12-20 00:26:33 +00003822/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
3823/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00003824bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
3825 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00003826 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00003827 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00003828 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00003829 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003830 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003831 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00003832 << SourceRange(TheCall->getArg(2)->getLocStart(),
3833 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00003834
John Wiegley01296292011-04-08 18:41:53 +00003835 ExprResult OrigArg0 = TheCall->getArg(0);
3836 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00003837
Chris Lattner2da14fb2007-12-20 00:26:33 +00003838 // Do standard promotions between the two arguments, returning their common
3839 // type.
Chris Lattner08464942007-12-28 05:29:59 +00003840 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00003841 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
3842 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00003843
3844 // Make sure any conversions are pushed back into the call; this is
3845 // type safe since unordered compare builtins are declared as "_Bool
3846 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00003847 TheCall->setArg(0, OrigArg0.get());
3848 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00003849
John Wiegley01296292011-04-08 18:41:53 +00003850 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00003851 return false;
3852
Chris Lattner2da14fb2007-12-20 00:26:33 +00003853 // If the common type isn't a real floating type, then the arguments were
3854 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00003855 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00003856 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003857 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00003858 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
3859 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00003860
Chris Lattner2da14fb2007-12-20 00:26:33 +00003861 return false;
3862}
3863
Benjamin Kramer634fc102010-02-15 22:42:31 +00003864/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
3865/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00003866/// to check everything. We expect the last argument to be a floating point
3867/// value.
3868bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
3869 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00003870 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00003871 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00003872 if (TheCall->getNumArgs() > NumArgs)
3873 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00003874 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003875 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00003876 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00003877 (*(TheCall->arg_end()-1))->getLocEnd());
3878
Benjamin Kramer64aae502010-02-16 10:07:31 +00003879 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00003880
Eli Friedman7e4faac2009-08-31 20:06:00 +00003881 if (OrigArg->isTypeDependent())
3882 return false;
3883
Chris Lattner68784ef2010-05-06 05:50:07 +00003884 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00003885 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00003886 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00003887 diag::err_typecheck_call_invalid_unary_fp)
3888 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00003889
Neil Hickey88c0fac2016-12-13 16:22:50 +00003890 // If this is an implicit conversion from float -> float or double, remove it.
Chris Lattner68784ef2010-05-06 05:50:07 +00003891 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
Neil Hickey7b5ddab2016-12-14 13:18:48 +00003892 // Only remove standard FloatCasts, leaving other casts inplace
3893 if (Cast->getCastKind() == CK_FloatingCast) {
3894 Expr *CastArg = Cast->getSubExpr();
3895 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
3896 assert((Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
3897 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float)) &&
3898 "promotion from float to either float or double is the only expected cast here");
3899 Cast->setSubExpr(nullptr);
3900 TheCall->setArg(NumArgs-1, CastArg);
3901 }
Chris Lattner68784ef2010-05-06 05:50:07 +00003902 }
3903 }
3904
Eli Friedman7e4faac2009-08-31 20:06:00 +00003905 return false;
3906}
3907
Tony Jiangbbc48e92017-05-24 15:13:32 +00003908// Customized Sema Checking for VSX builtins that have the following signature:
3909// vector [...] builtinName(vector [...], vector [...], const int);
3910// Which takes the same type of vectors (any legal vector type) for the first
3911// two arguments and takes compile time constant for the third argument.
3912// Example builtins are :
3913// vector double vec_xxpermdi(vector double, vector double, int);
3914// vector short vec_xxsldwi(vector short, vector short, int);
3915bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
3916 unsigned ExpectedNumArgs = 3;
3917 if (TheCall->getNumArgs() < ExpectedNumArgs)
3918 return Diag(TheCall->getLocEnd(),
3919 diag::err_typecheck_call_too_few_args_at_least)
3920 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
3921 << TheCall->getSourceRange();
3922
3923 if (TheCall->getNumArgs() > ExpectedNumArgs)
3924 return Diag(TheCall->getLocEnd(),
3925 diag::err_typecheck_call_too_many_args_at_most)
3926 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
3927 << TheCall->getSourceRange();
3928
3929 // Check the third argument is a compile time constant
3930 llvm::APSInt Value;
3931 if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
3932 return Diag(TheCall->getLocStart(),
3933 diag::err_vsx_builtin_nonconstant_argument)
3934 << 3 /* argument index */ << TheCall->getDirectCallee()
3935 << SourceRange(TheCall->getArg(2)->getLocStart(),
3936 TheCall->getArg(2)->getLocEnd());
3937
3938 QualType Arg1Ty = TheCall->getArg(0)->getType();
3939 QualType Arg2Ty = TheCall->getArg(1)->getType();
3940
3941 // Check the type of argument 1 and argument 2 are vectors.
3942 SourceLocation BuiltinLoc = TheCall->getLocStart();
3943 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
3944 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
3945 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
3946 << TheCall->getDirectCallee()
3947 << SourceRange(TheCall->getArg(0)->getLocStart(),
3948 TheCall->getArg(1)->getLocEnd());
3949 }
3950
3951 // Check the first two arguments are the same type.
3952 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
3953 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
3954 << TheCall->getDirectCallee()
3955 << SourceRange(TheCall->getArg(0)->getLocStart(),
3956 TheCall->getArg(1)->getLocEnd());
3957 }
3958
3959 // When default clang type checking is turned off and the customized type
3960 // checking is used, the returning type of the function must be explicitly
3961 // set. Otherwise it is _Bool by default.
3962 TheCall->setType(Arg1Ty);
3963
3964 return false;
3965}
3966
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003967/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
3968// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00003969ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00003970 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003971 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00003972 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00003973 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3974 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003975
Nate Begemana0110022010-06-08 00:16:34 +00003976 // Determine which of the following types of shufflevector we're checking:
3977 // 1) unary, vector mask: (lhs, mask)
Craig Topperb3174a82016-05-18 04:11:25 +00003978 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
Nate Begemana0110022010-06-08 00:16:34 +00003979 QualType resType = TheCall->getArg(0)->getType();
3980 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00003981
Douglas Gregorc25f7662009-05-19 22:10:17 +00003982 if (!TheCall->getArg(0)->isTypeDependent() &&
3983 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00003984 QualType LHSType = TheCall->getArg(0)->getType();
3985 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00003986
Craig Topperbaca3892013-07-29 06:47:04 +00003987 if (!LHSType->isVectorType() || !RHSType->isVectorType())
3988 return ExprError(Diag(TheCall->getLocStart(),
Tony Jiangedc78492017-05-24 14:45:57 +00003989 diag::err_vec_builtin_non_vector)
3990 << TheCall->getDirectCallee()
Craig Topperbaca3892013-07-29 06:47:04 +00003991 << SourceRange(TheCall->getArg(0)->getLocStart(),
3992 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00003993
Nate Begemana0110022010-06-08 00:16:34 +00003994 numElements = LHSType->getAs<VectorType>()->getNumElements();
3995 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00003996
Nate Begemana0110022010-06-08 00:16:34 +00003997 // Check to see if we have a call with 2 vector arguments, the unary shuffle
3998 // with mask. If so, verify that RHS is an integer vector type with the
3999 // same number of elts as lhs.
4000 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00004001 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00004002 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00004003 return ExprError(Diag(TheCall->getLocStart(),
Tony Jiangedc78492017-05-24 14:45:57 +00004004 diag::err_vec_builtin_incompatible_vector)
4005 << TheCall->getDirectCallee()
Craig Topperbaca3892013-07-29 06:47:04 +00004006 << SourceRange(TheCall->getArg(1)->getLocStart(),
4007 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00004008 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00004009 return ExprError(Diag(TheCall->getLocStart(),
Tony Jiangedc78492017-05-24 14:45:57 +00004010 diag::err_vec_builtin_incompatible_vector)
4011 << TheCall->getDirectCallee()
Craig Topperbaca3892013-07-29 06:47:04 +00004012 << SourceRange(TheCall->getArg(0)->getLocStart(),
4013 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00004014 } else if (numElements != numResElements) {
4015 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00004016 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00004017 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00004018 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004019 }
4020
4021 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00004022 if (TheCall->getArg(i)->isTypeDependent() ||
4023 TheCall->getArg(i)->isValueDependent())
4024 continue;
4025
Nate Begemana0110022010-06-08 00:16:34 +00004026 llvm::APSInt Result(32);
4027 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
4028 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00004029 diag::err_shufflevector_nonconstant_argument)
4030 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004031
Craig Topper50ad5b72013-08-03 17:40:38 +00004032 // Allow -1 which will be translated to undef in the IR.
4033 if (Result.isSigned() && Result.isAllOnesValue())
4034 continue;
4035
Chris Lattner7ab824e2008-08-10 02:05:13 +00004036 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004037 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00004038 diag::err_shufflevector_argument_too_large)
4039 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004040 }
4041
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004042 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004043
Chris Lattner7ab824e2008-08-10 02:05:13 +00004044 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004045 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00004046 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004047 }
4048
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004049 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
4050 TheCall->getCallee()->getLocStart(),
4051 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004052}
Chris Lattner43be2e62007-12-19 23:59:04 +00004053
Hal Finkelc4d7c822013-09-18 03:29:45 +00004054/// SemaConvertVectorExpr - Handle __builtin_convertvector
4055ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
4056 SourceLocation BuiltinLoc,
4057 SourceLocation RParenLoc) {
4058 ExprValueKind VK = VK_RValue;
4059 ExprObjectKind OK = OK_Ordinary;
4060 QualType DstTy = TInfo->getType();
4061 QualType SrcTy = E->getType();
4062
4063 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
4064 return ExprError(Diag(BuiltinLoc,
4065 diag::err_convertvector_non_vector)
4066 << E->getSourceRange());
4067 if (!DstTy->isVectorType() && !DstTy->isDependentType())
4068 return ExprError(Diag(BuiltinLoc,
4069 diag::err_convertvector_non_vector_type));
4070
4071 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
4072 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
4073 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
4074 if (SrcElts != DstElts)
4075 return ExprError(Diag(BuiltinLoc,
4076 diag::err_convertvector_incompatible_vector)
4077 << E->getSourceRange());
4078 }
4079
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004080 return new (Context)
4081 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00004082}
4083
Daniel Dunbarb7257262008-07-21 22:59:13 +00004084/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
4085// This is declared to take (const void*, ...) and can take two
4086// optional constant int args.
4087bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00004088 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00004089
Chris Lattner3b054132008-11-19 05:08:23 +00004090 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004091 return Diag(TheCall->getLocEnd(),
4092 diag::err_typecheck_call_too_many_args_at_most)
4093 << 0 /*function call*/ << 3 << NumArgs
4094 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00004095
4096 // Argument 0 is checked for us and the remaining arguments must be
4097 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00004098 for (unsigned i = 1; i != NumArgs; ++i)
4099 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00004100 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004101
Warren Hunt20e4a5d2014-02-21 23:08:53 +00004102 return false;
4103}
4104
Hal Finkelf0417332014-07-17 14:25:55 +00004105/// SemaBuiltinAssume - Handle __assume (MS Extension).
4106// __assume does not evaluate its arguments, and should warn if its argument
4107// has side effects.
4108bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
4109 Expr *Arg = TheCall->getArg(0);
4110 if (Arg->isInstantiationDependent()) return false;
4111
4112 if (Arg->HasSideEffects(Context))
David Majnemer51236642015-02-26 00:57:33 +00004113 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00004114 << Arg->getSourceRange()
4115 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
4116
4117 return false;
4118}
4119
David Majnemer86b1bfa2016-10-31 18:07:57 +00004120/// Handle __builtin_alloca_with_align. This is declared
David Majnemer51169932016-10-31 05:37:48 +00004121/// as (size_t, size_t) where the second size_t must be a power of 2 greater
4122/// than 8.
4123bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
4124 // The alignment must be a constant integer.
4125 Expr *Arg = TheCall->getArg(1);
4126
4127 // We can't check the value of a dependent argument.
4128 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
David Majnemer86b1bfa2016-10-31 18:07:57 +00004129 if (const auto *UE =
4130 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
4131 if (UE->getKind() == UETT_AlignOf)
4132 Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof)
4133 << Arg->getSourceRange();
4134
David Majnemer51169932016-10-31 05:37:48 +00004135 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
4136
4137 if (!Result.isPowerOf2())
4138 return Diag(TheCall->getLocStart(),
4139 diag::err_alignment_not_power_of_two)
4140 << Arg->getSourceRange();
4141
4142 if (Result < Context.getCharWidth())
4143 return Diag(TheCall->getLocStart(), diag::err_alignment_too_small)
4144 << (unsigned)Context.getCharWidth()
4145 << Arg->getSourceRange();
4146
4147 if (Result > INT32_MAX)
4148 return Diag(TheCall->getLocStart(), diag::err_alignment_too_big)
4149 << INT32_MAX
4150 << Arg->getSourceRange();
4151 }
4152
4153 return false;
4154}
4155
4156/// Handle __builtin_assume_aligned. This is declared
Hal Finkelbcc06082014-09-07 22:58:14 +00004157/// as (const void*, size_t, ...) and can take one optional constant int arg.
4158bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
4159 unsigned NumArgs = TheCall->getNumArgs();
4160
4161 if (NumArgs > 3)
4162 return Diag(TheCall->getLocEnd(),
4163 diag::err_typecheck_call_too_many_args_at_most)
4164 << 0 /*function call*/ << 3 << NumArgs
4165 << TheCall->getSourceRange();
4166
4167 // The alignment must be a constant integer.
4168 Expr *Arg = TheCall->getArg(1);
4169
4170 // We can't check the value of a dependent argument.
4171 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
4172 llvm::APSInt Result;
4173 if (SemaBuiltinConstantArg(TheCall, 1, Result))
4174 return true;
4175
4176 if (!Result.isPowerOf2())
4177 return Diag(TheCall->getLocStart(),
4178 diag::err_alignment_not_power_of_two)
4179 << Arg->getSourceRange();
4180 }
4181
4182 if (NumArgs > 2) {
4183 ExprResult Arg(TheCall->getArg(2));
4184 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
4185 Context.getSizeType(), false);
4186 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4187 if (Arg.isInvalid()) return true;
4188 TheCall->setArg(2, Arg.get());
4189 }
Hal Finkelf0417332014-07-17 14:25:55 +00004190
4191 return false;
4192}
4193
Mehdi Amini06d367c2016-10-24 20:39:34 +00004194bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
4195 unsigned BuiltinID =
4196 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
4197 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
4198
4199 unsigned NumArgs = TheCall->getNumArgs();
4200 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
4201 if (NumArgs < NumRequiredArgs) {
4202 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4203 << 0 /* function call */ << NumRequiredArgs << NumArgs
4204 << TheCall->getSourceRange();
4205 }
4206 if (NumArgs >= NumRequiredArgs + 0x100) {
4207 return Diag(TheCall->getLocEnd(),
4208 diag::err_typecheck_call_too_many_args_at_most)
4209 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
4210 << TheCall->getSourceRange();
4211 }
4212 unsigned i = 0;
4213
4214 // For formatting call, check buffer arg.
4215 if (!IsSizeCall) {
4216 ExprResult Arg(TheCall->getArg(i));
4217 InitializedEntity Entity = InitializedEntity::InitializeParameter(
4218 Context, Context.VoidPtrTy, false);
4219 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4220 if (Arg.isInvalid())
4221 return true;
4222 TheCall->setArg(i, Arg.get());
4223 i++;
4224 }
4225
4226 // Check string literal arg.
4227 unsigned FormatIdx = i;
4228 {
4229 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
4230 if (Arg.isInvalid())
4231 return true;
4232 TheCall->setArg(i, Arg.get());
4233 i++;
4234 }
4235
4236 // Make sure variadic args are scalar.
4237 unsigned FirstDataArg = i;
4238 while (i < NumArgs) {
4239 ExprResult Arg = DefaultVariadicArgumentPromotion(
4240 TheCall->getArg(i), VariadicFunction, nullptr);
4241 if (Arg.isInvalid())
4242 return true;
4243 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
4244 if (ArgSize.getQuantity() >= 0x100) {
4245 return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big)
4246 << i << (int)ArgSize.getQuantity() << 0xff
4247 << TheCall->getSourceRange();
4248 }
4249 TheCall->setArg(i, Arg.get());
4250 i++;
4251 }
4252
4253 // Check formatting specifiers. NOTE: We're only doing this for the non-size
4254 // call to avoid duplicate diagnostics.
4255 if (!IsSizeCall) {
4256 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
4257 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
4258 bool Success = CheckFormatArguments(
4259 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
4260 VariadicFunction, TheCall->getLocStart(), SourceRange(),
4261 CheckedVarArgs);
4262 if (!Success)
4263 return true;
4264 }
4265
4266 if (IsSizeCall) {
4267 TheCall->setType(Context.getSizeType());
4268 } else {
4269 TheCall->setType(Context.VoidPtrTy);
4270 }
4271 return false;
4272}
4273
Eric Christopher8d0c6212010-04-17 02:26:23 +00004274/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
4275/// TheCall is a constant expression.
4276bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
4277 llvm::APSInt &Result) {
4278 Expr *Arg = TheCall->getArg(ArgNum);
4279 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4280 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4281
4282 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
4283
4284 if (!Arg->isIntegerConstantExpr(Result, Context))
4285 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00004286 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00004287
Chris Lattnerd545ad12009-09-23 06:06:36 +00004288 return false;
4289}
4290
Richard Sandiford28940af2014-04-16 08:47:51 +00004291/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
4292/// TheCall is a constant expression in the range [Low, High].
4293bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
4294 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00004295 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00004296
4297 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00004298 Expr *Arg = TheCall->getArg(ArgNum);
4299 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00004300 return false;
4301
Eric Christopher8d0c6212010-04-17 02:26:23 +00004302 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00004303 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00004304 return true;
4305
Richard Sandiford28940af2014-04-16 08:47:51 +00004306 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00004307 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00004308 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00004309
4310 return false;
4311}
4312
Simon Dardis1f90f2d2016-10-19 17:50:52 +00004313/// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
4314/// TheCall is a constant expression is a multiple of Num..
4315bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
4316 unsigned Num) {
4317 llvm::APSInt Result;
4318
4319 // We can't check the value of a dependent argument.
4320 Expr *Arg = TheCall->getArg(ArgNum);
4321 if (Arg->isTypeDependent() || Arg->isValueDependent())
4322 return false;
4323
4324 // Check constant-ness first.
4325 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4326 return true;
4327
4328 if (Result.getSExtValue() % Num != 0)
4329 return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple)
4330 << Num << Arg->getSourceRange();
4331
4332 return false;
4333}
4334
Luke Cheeseman59b2d832015-06-15 17:51:01 +00004335/// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
4336/// TheCall is an ARM/AArch64 special register string literal.
4337bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
4338 int ArgNum, unsigned ExpectedFieldNum,
4339 bool AllowName) {
4340 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
4341 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
4342 BuiltinID == ARM::BI__builtin_arm_rsr ||
4343 BuiltinID == ARM::BI__builtin_arm_rsrp ||
4344 BuiltinID == ARM::BI__builtin_arm_wsr ||
4345 BuiltinID == ARM::BI__builtin_arm_wsrp;
4346 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
4347 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
4348 BuiltinID == AArch64::BI__builtin_arm_rsr ||
4349 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
4350 BuiltinID == AArch64::BI__builtin_arm_wsr ||
4351 BuiltinID == AArch64::BI__builtin_arm_wsrp;
4352 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
4353
4354 // We can't check the value of a dependent argument.
4355 Expr *Arg = TheCall->getArg(ArgNum);
4356 if (Arg->isTypeDependent() || Arg->isValueDependent())
4357 return false;
4358
4359 // Check if the argument is a string literal.
4360 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4361 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
4362 << Arg->getSourceRange();
4363
4364 // Check the type of special register given.
4365 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4366 SmallVector<StringRef, 6> Fields;
4367 Reg.split(Fields, ":");
4368
4369 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
4370 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4371 << Arg->getSourceRange();
4372
4373 // If the string is the name of a register then we cannot check that it is
4374 // valid here but if the string is of one the forms described in ACLE then we
4375 // can check that the supplied fields are integers and within the valid
4376 // ranges.
4377 if (Fields.size() > 1) {
4378 bool FiveFields = Fields.size() == 5;
4379
4380 bool ValidString = true;
4381 if (IsARMBuiltin) {
4382 ValidString &= Fields[0].startswith_lower("cp") ||
4383 Fields[0].startswith_lower("p");
4384 if (ValidString)
4385 Fields[0] =
4386 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
4387
4388 ValidString &= Fields[2].startswith_lower("c");
4389 if (ValidString)
4390 Fields[2] = Fields[2].drop_front(1);
4391
4392 if (FiveFields) {
4393 ValidString &= Fields[3].startswith_lower("c");
4394 if (ValidString)
4395 Fields[3] = Fields[3].drop_front(1);
4396 }
4397 }
4398
4399 SmallVector<int, 5> Ranges;
4400 if (FiveFields)
Oleg Ranevskyy85d93a82016-11-18 21:00:08 +00004401 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
Luke Cheeseman59b2d832015-06-15 17:51:01 +00004402 else
4403 Ranges.append({15, 7, 15});
4404
4405 for (unsigned i=0; i<Fields.size(); ++i) {
4406 int IntField;
4407 ValidString &= !Fields[i].getAsInteger(10, IntField);
4408 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
4409 }
4410
4411 if (!ValidString)
4412 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4413 << Arg->getSourceRange();
4414
4415 } else if (IsAArch64Builtin && Fields.size() == 1) {
4416 // If the register name is one of those that appear in the condition below
4417 // and the special register builtin being used is one of the write builtins,
4418 // then we require that the argument provided for writing to the register
4419 // is an integer constant expression. This is because it will be lowered to
4420 // an MSR (immediate) instruction, so we need to know the immediate at
4421 // compile time.
4422 if (TheCall->getNumArgs() != 2)
4423 return false;
4424
4425 std::string RegLower = Reg.lower();
4426 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
4427 RegLower != "pan" && RegLower != "uao")
4428 return false;
4429
4430 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
4431 }
4432
4433 return false;
4434}
4435
Eli Friedmanc97d0142009-05-03 06:04:26 +00004436/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004437/// This checks that the target supports __builtin_longjmp and
4438/// that val is a constant 1.
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004439bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004440 if (!Context.getTargetInfo().hasSjLjLowering())
4441 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
4442 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4443
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004444 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00004445 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00004446
Eric Christopher8d0c6212010-04-17 02:26:23 +00004447 // TODO: This is less than ideal. Overload this to take a value.
4448 if (SemaBuiltinConstantArg(TheCall, 1, Result))
4449 return true;
4450
4451 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004452 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
4453 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
4454
4455 return false;
4456}
4457
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004458/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
4459/// This checks that the target supports __builtin_setjmp.
4460bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
4461 if (!Context.getTargetInfo().hasSjLjLowering())
4462 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
4463 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4464 return false;
4465}
4466
Richard Smithd7293d72013-08-05 18:49:43 +00004467namespace {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004468class UncoveredArgHandler {
4469 enum { Unknown = -1, AllCovered = -2 };
4470 signed FirstUncoveredArg;
4471 SmallVector<const Expr *, 4> DiagnosticExprs;
4472
4473public:
4474 UncoveredArgHandler() : FirstUncoveredArg(Unknown) { }
4475
4476 bool hasUncoveredArg() const {
4477 return (FirstUncoveredArg >= 0);
4478 }
4479
4480 unsigned getUncoveredArg() const {
4481 assert(hasUncoveredArg() && "no uncovered argument");
4482 return FirstUncoveredArg;
4483 }
4484
4485 void setAllCovered() {
4486 // A string has been found with all arguments covered, so clear out
4487 // the diagnostics.
4488 DiagnosticExprs.clear();
4489 FirstUncoveredArg = AllCovered;
4490 }
4491
4492 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
4493 assert(NewFirstUncoveredArg >= 0 && "Outside range");
4494
4495 // Don't update if a previous string covers all arguments.
4496 if (FirstUncoveredArg == AllCovered)
4497 return;
4498
4499 // UncoveredArgHandler tracks the highest uncovered argument index
4500 // and with it all the strings that match this index.
4501 if (NewFirstUncoveredArg == FirstUncoveredArg)
4502 DiagnosticExprs.push_back(StrExpr);
4503 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
4504 DiagnosticExprs.clear();
4505 DiagnosticExprs.push_back(StrExpr);
4506 FirstUncoveredArg = NewFirstUncoveredArg;
4507 }
4508 }
4509
4510 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
4511};
4512
Richard Smithd7293d72013-08-05 18:49:43 +00004513enum StringLiteralCheckType {
4514 SLCT_NotALiteral,
4515 SLCT_UncheckedLiteral,
4516 SLCT_CheckedLiteral
4517};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004518} // end anonymous namespace
Richard Smithd7293d72013-08-05 18:49:43 +00004519
Stephen Hines648c3692016-09-16 01:07:04 +00004520static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
4521 BinaryOperatorKind BinOpKind,
4522 bool AddendIsRight) {
4523 unsigned BitWidth = Offset.getBitWidth();
4524 unsigned AddendBitWidth = Addend.getBitWidth();
4525 // There might be negative interim results.
4526 if (Addend.isUnsigned()) {
4527 Addend = Addend.zext(++AddendBitWidth);
4528 Addend.setIsSigned(true);
4529 }
4530 // Adjust the bit width of the APSInts.
4531 if (AddendBitWidth > BitWidth) {
4532 Offset = Offset.sext(AddendBitWidth);
4533 BitWidth = AddendBitWidth;
4534 } else if (BitWidth > AddendBitWidth) {
4535 Addend = Addend.sext(BitWidth);
4536 }
4537
4538 bool Ov = false;
4539 llvm::APSInt ResOffset = Offset;
4540 if (BinOpKind == BO_Add)
4541 ResOffset = Offset.sadd_ov(Addend, Ov);
4542 else {
4543 assert(AddendIsRight && BinOpKind == BO_Sub &&
4544 "operator must be add or sub with addend on the right");
4545 ResOffset = Offset.ssub_ov(Addend, Ov);
4546 }
4547
4548 // We add an offset to a pointer here so we should support an offset as big as
4549 // possible.
4550 if (Ov) {
4551 assert(BitWidth <= UINT_MAX / 2 && "index (intermediate) result too big");
Stephen Hinesfec73ad2016-09-16 07:21:24 +00004552 Offset = Offset.sext(2 * BitWidth);
Stephen Hines648c3692016-09-16 01:07:04 +00004553 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
4554 return;
4555 }
4556
4557 Offset = ResOffset;
4558}
4559
4560namespace {
4561// This is a wrapper class around StringLiteral to support offsetted string
4562// literals as format strings. It takes the offset into account when returning
4563// the string and its length or the source locations to display notes correctly.
4564class FormatStringLiteral {
4565 const StringLiteral *FExpr;
4566 int64_t Offset;
4567
4568 public:
4569 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
4570 : FExpr(fexpr), Offset(Offset) {}
4571
4572 StringRef getString() const {
4573 return FExpr->getString().drop_front(Offset);
4574 }
4575
4576 unsigned getByteLength() const {
4577 return FExpr->getByteLength() - getCharByteWidth() * Offset;
4578 }
4579 unsigned getLength() const { return FExpr->getLength() - Offset; }
4580 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
4581
4582 StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
4583
4584 QualType getType() const { return FExpr->getType(); }
4585
4586 bool isAscii() const { return FExpr->isAscii(); }
4587 bool isWide() const { return FExpr->isWide(); }
4588 bool isUTF8() const { return FExpr->isUTF8(); }
4589 bool isUTF16() const { return FExpr->isUTF16(); }
4590 bool isUTF32() const { return FExpr->isUTF32(); }
4591 bool isPascal() const { return FExpr->isPascal(); }
4592
4593 SourceLocation getLocationOfByte(
4594 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
4595 const TargetInfo &Target, unsigned *StartToken = nullptr,
4596 unsigned *StartTokenByteOffset = nullptr) const {
4597 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
4598 StartToken, StartTokenByteOffset);
4599 }
4600
4601 SourceLocation getLocStart() const LLVM_READONLY {
4602 return FExpr->getLocStart().getLocWithOffset(Offset);
4603 }
4604 SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); }
4605};
4606} // end anonymous namespace
4607
4608static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004609 const Expr *OrigFormatExpr,
4610 ArrayRef<const Expr *> Args,
4611 bool HasVAListArg, unsigned format_idx,
4612 unsigned firstDataArg,
4613 Sema::FormatStringType Type,
4614 bool inFunctionCall,
4615 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004616 llvm::SmallBitVector &CheckedVarArgs,
4617 UncoveredArgHandler &UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004618
Richard Smith55ce3522012-06-25 20:30:08 +00004619// Determine if an expression is a string literal or constant string.
4620// If this function returns false on the arguments to a function expecting a
4621// format string, we will usually need to emit a warning.
4622// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00004623static StringLiteralCheckType
4624checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
4625 bool HasVAListArg, unsigned format_idx,
4626 unsigned firstDataArg, Sema::FormatStringType Type,
4627 Sema::VariadicCallType CallType, bool InFunctionCall,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004628 llvm::SmallBitVector &CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00004629 UncoveredArgHandler &UncoveredArg,
4630 llvm::APSInt Offset) {
Ted Kremenek808829352010-09-09 03:51:39 +00004631 tryAgain:
Stephen Hines648c3692016-09-16 01:07:04 +00004632 assert(Offset.isSigned() && "invalid offset");
4633
Douglas Gregorc25f7662009-05-19 22:10:17 +00004634 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00004635 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004636
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004637 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00004638
Richard Smithd7293d72013-08-05 18:49:43 +00004639 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00004640 // Technically -Wformat-nonliteral does not warn about this case.
4641 // The behavior of printf and friends in this case is implementation
4642 // dependent. Ideally if the format string cannot be null then
4643 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00004644 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00004645
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004646 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00004647 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004648 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00004649 // The expression is a literal if both sub-expressions were, and it was
4650 // completely checked only if both sub-expressions were checked.
4651 const AbstractConditionalOperator *C =
4652 cast<AbstractConditionalOperator>(E);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004653
4654 // Determine whether it is necessary to check both sub-expressions, for
4655 // example, because the condition expression is a constant that can be
4656 // evaluated at compile time.
4657 bool CheckLeft = true, CheckRight = true;
4658
4659 bool Cond;
4660 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
4661 if (Cond)
4662 CheckRight = false;
4663 else
4664 CheckLeft = false;
4665 }
4666
Stephen Hines648c3692016-09-16 01:07:04 +00004667 // We need to maintain the offsets for the right and the left hand side
4668 // separately to check if every possible indexed expression is a valid
4669 // string literal. They might have different offsets for different string
4670 // literals in the end.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004671 StringLiteralCheckType Left;
4672 if (!CheckLeft)
4673 Left = SLCT_UncheckedLiteral;
4674 else {
4675 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
4676 HasVAListArg, format_idx, firstDataArg,
4677 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00004678 CheckedVarArgs, UncoveredArg, Offset);
4679 if (Left == SLCT_NotALiteral || !CheckRight) {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004680 return Left;
Stephen Hines648c3692016-09-16 01:07:04 +00004681 }
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004682 }
4683
Richard Smith55ce3522012-06-25 20:30:08 +00004684 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00004685 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004686 HasVAListArg, format_idx, firstDataArg,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004687 Type, CallType, InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00004688 UncoveredArg, Offset);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004689
4690 return (CheckLeft && Left < Right) ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004691 }
4692
4693 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00004694 E = cast<ImplicitCastExpr>(E)->getSubExpr();
4695 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004696 }
4697
John McCallc07a0c72011-02-17 10:25:35 +00004698 case Stmt::OpaqueValueExprClass:
4699 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
4700 E = src;
4701 goto tryAgain;
4702 }
Richard Smith55ce3522012-06-25 20:30:08 +00004703 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00004704
Ted Kremeneka8890832011-02-24 23:03:04 +00004705 case Stmt::PredefinedExprClass:
4706 // While __func__, etc., are technically not string literals, they
4707 // cannot contain format specifiers and thus are not a security
4708 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00004709 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00004710
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004711 case Stmt::DeclRefExprClass: {
4712 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004713
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004714 // As an exception, do not flag errors for variables binding to
4715 // const string literals.
4716 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
4717 bool isConstant = false;
4718 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004719
Richard Smithd7293d72013-08-05 18:49:43 +00004720 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
4721 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00004722 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00004723 isConstant = T.isConstant(S.Context) &&
4724 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00004725 } else if (T->isObjCObjectPointerType()) {
4726 // In ObjC, there is usually no "const ObjectPointer" type,
4727 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00004728 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004729 }
Mike Stump11289f42009-09-09 15:08:12 +00004730
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004731 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00004732 if (const Expr *Init = VD->getAnyInitializer()) {
4733 // Look through initializers like const char c[] = { "foo" }
4734 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4735 if (InitList->isStringLiteralInit())
4736 Init = InitList->getInit(0)->IgnoreParenImpCasts();
4737 }
Richard Smithd7293d72013-08-05 18:49:43 +00004738 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004739 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004740 firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00004741 /*InFunctionCall*/ false, CheckedVarArgs,
4742 UncoveredArg, Offset);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00004743 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004744 }
Mike Stump11289f42009-09-09 15:08:12 +00004745
Anders Carlssonb012ca92009-06-28 19:55:58 +00004746 // For vprintf* functions (i.e., HasVAListArg==true), we add a
4747 // special check to see if the format string is a function parameter
4748 // of the function calling the printf function. If the function
4749 // has an attribute indicating it is a printf-like function, then we
4750 // should suppress warnings concerning non-literals being used in a call
4751 // to a vprintf function. For example:
4752 //
4753 // void
4754 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
4755 // va_list ap;
4756 // va_start(ap, fmt);
4757 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
4758 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00004759 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004760 if (HasVAListArg) {
4761 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
4762 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
4763 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00004764 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004765 // adjust for implicit parameter
4766 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4767 if (MD->isInstance())
4768 ++PVIndex;
4769 // We also check if the formats are compatible.
4770 // We can't pass a 'scanf' string to a 'printf' function.
4771 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00004772 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00004773 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004774 }
4775 }
4776 }
4777 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004778 }
Mike Stump11289f42009-09-09 15:08:12 +00004779
Richard Smith55ce3522012-06-25 20:30:08 +00004780 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004781 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004782
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00004783 case Stmt::CallExprClass:
4784 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00004785 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00004786 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
4787 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
4788 unsigned ArgIndex = FA->getFormatIdx();
4789 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4790 if (MD->isInstance())
4791 --ArgIndex;
4792 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00004793
Richard Smithd7293d72013-08-05 18:49:43 +00004794 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004795 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00004796 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00004797 CheckedVarArgs, UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004798 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4799 unsigned BuiltinID = FD->getBuiltinID();
4800 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
4801 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
4802 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00004803 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004804 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004805 firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004806 InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00004807 UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004808 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00004809 }
4810 }
Mike Stump11289f42009-09-09 15:08:12 +00004811
Richard Smith55ce3522012-06-25 20:30:08 +00004812 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00004813 }
Alex Lorenzd9007142016-10-24 09:42:34 +00004814 case Stmt::ObjCMessageExprClass: {
4815 const auto *ME = cast<ObjCMessageExpr>(E);
4816 if (const auto *ND = ME->getMethodDecl()) {
4817 if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
4818 unsigned ArgIndex = FA->getFormatIdx();
4819 const Expr *Arg = ME->getArg(ArgIndex - 1);
4820 return checkFormatStringExpr(
4821 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
4822 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
4823 }
4824 }
4825
4826 return SLCT_NotALiteral;
4827 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004828 case Stmt::ObjCStringLiteralClass:
4829 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00004830 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004831
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004832 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004833 StrE = ObjCFExpr->getString();
4834 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004835 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004836
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004837 if (StrE) {
Stephen Hines648c3692016-09-16 01:07:04 +00004838 if (Offset.isNegative() || Offset > StrE->getLength()) {
4839 // TODO: It would be better to have an explicit warning for out of
4840 // bounds literals.
4841 return SLCT_NotALiteral;
4842 }
4843 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
4844 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004845 firstDataArg, Type, InFunctionCall, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004846 CheckedVarArgs, UncoveredArg);
Richard Smith55ce3522012-06-25 20:30:08 +00004847 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004848 }
Mike Stump11289f42009-09-09 15:08:12 +00004849
Richard Smith55ce3522012-06-25 20:30:08 +00004850 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004851 }
Stephen Hines648c3692016-09-16 01:07:04 +00004852 case Stmt::BinaryOperatorClass: {
4853 llvm::APSInt LResult;
4854 llvm::APSInt RResult;
4855
4856 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
4857
4858 // A string literal + an int offset is still a string literal.
4859 if (BinOp->isAdditiveOp()) {
4860 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
4861 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
4862
4863 if (LIsInt != RIsInt) {
4864 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
4865
4866 if (LIsInt) {
4867 if (BinOpKind == BO_Add) {
4868 sumOffsets(Offset, LResult, BinOpKind, RIsInt);
4869 E = BinOp->getRHS();
4870 goto tryAgain;
4871 }
4872 } else {
4873 sumOffsets(Offset, RResult, BinOpKind, RIsInt);
4874 E = BinOp->getLHS();
4875 goto tryAgain;
4876 }
4877 }
Stephen Hines648c3692016-09-16 01:07:04 +00004878 }
George Burgess IVd273aab2016-09-22 00:00:26 +00004879
4880 return SLCT_NotALiteral;
Stephen Hines648c3692016-09-16 01:07:04 +00004881 }
4882 case Stmt::UnaryOperatorClass: {
4883 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
4884 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
4885 if (UnaOp->getOpcode() == clang::UO_AddrOf && ASE) {
4886 llvm::APSInt IndexResult;
4887 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
4888 sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true);
4889 E = ASE->getBase();
4890 goto tryAgain;
4891 }
4892 }
4893
4894 return SLCT_NotALiteral;
4895 }
Mike Stump11289f42009-09-09 15:08:12 +00004896
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004897 default:
Richard Smith55ce3522012-06-25 20:30:08 +00004898 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004899 }
4900}
4901
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004902Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00004903 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Mehdi Amini06d367c2016-10-24 20:39:34 +00004904 .Case("scanf", FST_Scanf)
4905 .Cases("printf", "printf0", FST_Printf)
4906 .Cases("NSString", "CFString", FST_NSString)
4907 .Case("strftime", FST_Strftime)
4908 .Case("strfmon", FST_Strfmon)
4909 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
4910 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
4911 .Case("os_trace", FST_OSLog)
4912 .Case("os_log", FST_OSLog)
4913 .Default(FST_Unknown);
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004914}
4915
Jordan Rose3e0ec582012-07-19 18:10:23 +00004916/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00004917/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00004918/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004919bool Sema::CheckFormatArguments(const FormatAttr *Format,
4920 ArrayRef<const Expr *> Args,
4921 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004922 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00004923 SourceLocation Loc, SourceRange Range,
4924 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00004925 FormatStringInfo FSI;
4926 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004927 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00004928 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00004929 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00004930 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004931}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00004932
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004933bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004934 bool HasVAListArg, unsigned format_idx,
4935 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004936 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00004937 SourceLocation Loc, SourceRange Range,
4938 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00004939 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004940 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004941 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00004942 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00004943 }
Mike Stump11289f42009-09-09 15:08:12 +00004944
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004945 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00004946
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004947 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00004948 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00004949 // Dynamically generated format strings are difficult to
4950 // automatically vet at compile time. Requiring that format strings
4951 // are string literals: (1) permits the checking of format strings by
4952 // the compiler and thereby (2) can practically remove the source of
4953 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00004954
Mike Stump11289f42009-09-09 15:08:12 +00004955 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00004956 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00004957 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00004958 // the same format string checking logic for both ObjC and C strings.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004959 UncoveredArgHandler UncoveredArg;
Richard Smith55ce3522012-06-25 20:30:08 +00004960 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00004961 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
4962 format_idx, firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00004963 /*IsFunctionCall*/ true, CheckedVarArgs,
4964 UncoveredArg,
4965 /*no string offset*/ llvm::APSInt(64, false) = 0);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004966
4967 // Generate a diagnostic where an uncovered argument is detected.
4968 if (UncoveredArg.hasUncoveredArg()) {
4969 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
4970 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
4971 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
4972 }
4973
Richard Smith55ce3522012-06-25 20:30:08 +00004974 if (CT != SLCT_NotALiteral)
4975 // Literal format string found, check done!
4976 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00004977
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00004978 // Strftime is particular as it always uses a single 'time' argument,
4979 // so it is safe to pass a non-literal string.
4980 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00004981 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00004982
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00004983 // Do not emit diag when the string param is a macro expansion and the
4984 // format is either NSString or CFString. This is a hack to prevent
4985 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
4986 // which are usually used in place of NS and CF string literals.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004987 SourceLocation FormatLoc = Args[format_idx]->getLocStart();
4988 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
Richard Smith55ce3522012-06-25 20:30:08 +00004989 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00004990
Chris Lattnercc5d1c22009-04-29 04:59:47 +00004991 // If there are no arguments specified, warn with -Wformat-security, otherwise
4992 // warn only with -Wformat-nonliteral.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004993 if (Args.size() == firstDataArg) {
Bob Wilson57819fc2016-03-15 20:56:38 +00004994 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
4995 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004996 switch (Type) {
4997 default:
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004998 break;
4999 case FST_Kprintf:
5000 case FST_FreeBSDKPrintf:
5001 case FST_Printf:
Bob Wilson57819fc2016-03-15 20:56:38 +00005002 Diag(FormatLoc, diag::note_format_security_fixit)
5003 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005004 break;
5005 case FST_NSString:
Bob Wilson57819fc2016-03-15 20:56:38 +00005006 Diag(FormatLoc, diag::note_format_security_fixit)
5007 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005008 break;
5009 }
5010 } else {
5011 Diag(FormatLoc, diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00005012 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005013 }
Richard Smith55ce3522012-06-25 20:30:08 +00005014 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005015}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00005016
Ted Kremenekab278de2010-01-28 23:39:18 +00005017namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00005018class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
5019protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00005020 Sema &S;
Stephen Hines648c3692016-09-16 01:07:04 +00005021 const FormatStringLiteral *FExpr;
Ted Kremenekab278de2010-01-28 23:39:18 +00005022 const Expr *OrigFormatExpr;
Mehdi Amini06d367c2016-10-24 20:39:34 +00005023 const Sema::FormatStringType FSType;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00005024 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00005025 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00005026 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00005027 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005028 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00005029 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00005030 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00005031 bool usesPositionalArgs;
5032 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00005033 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00005034 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00005035 llvm::SmallBitVector &CheckedVarArgs;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005036 UncoveredArgHandler &UncoveredArg;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005037
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005038public:
Stephen Hines648c3692016-09-16 01:07:04 +00005039 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00005040 const Expr *origFormatExpr,
5041 const Sema::FormatStringType type, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005042 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Mehdi Amini06d367c2016-10-24 20:39:34 +00005043 ArrayRef<const Expr *> Args, unsigned formatIdx,
5044 bool inFunctionCall, Sema::VariadicCallType callType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005045 llvm::SmallBitVector &CheckedVarArgs,
5046 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00005047 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
5048 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
5049 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
5050 usesPositionalArgs(false), atFirstArg(true),
5051 inFunctionCall(inFunctionCall), CallType(callType),
5052 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
Richard Smithd7293d72013-08-05 18:49:43 +00005053 CoveredArgs.resize(numDataArgs);
5054 CoveredArgs.reset();
5055 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005056
Ted Kremenek019d2242010-01-29 01:50:07 +00005057 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005058
Ted Kremenek02087932010-07-16 02:11:22 +00005059 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005060 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005061
Jordan Rose92303592012-09-08 04:00:03 +00005062 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005063 const analyze_format_string::FormatSpecifier &FS,
5064 const analyze_format_string::ConversionSpecifier &CS,
5065 const char *startSpecifier, unsigned specifierLen,
5066 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00005067
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005068 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005069 const analyze_format_string::FormatSpecifier &FS,
5070 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005071
5072 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005073 const analyze_format_string::ConversionSpecifier &CS,
5074 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005075
Craig Toppere14c0f82014-03-12 04:55:44 +00005076 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00005077
Craig Toppere14c0f82014-03-12 04:55:44 +00005078 void HandleInvalidPosition(const char *startSpecifier,
5079 unsigned specifierLen,
5080 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00005081
Craig Toppere14c0f82014-03-12 04:55:44 +00005082 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00005083
Craig Toppere14c0f82014-03-12 04:55:44 +00005084 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005085
Richard Trieu03cf7b72011-10-28 00:41:25 +00005086 template <typename Range>
Benjamin Kramer7320b992016-06-15 14:20:56 +00005087 static void
5088 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
5089 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
5090 bool IsStringLocation, Range StringRange,
5091 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005092
Ted Kremenek02087932010-07-16 02:11:22 +00005093protected:
Ted Kremenekce815422010-07-19 21:25:57 +00005094 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
5095 const char *startSpec,
5096 unsigned specifierLen,
5097 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005098
5099 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
5100 const char *startSpec,
5101 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00005102
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005103 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00005104 CharSourceRange getSpecifierRange(const char *startSpecifier,
5105 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00005106 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005107
Ted Kremenek5739de72010-01-29 01:06:55 +00005108 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005109
5110 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
5111 const analyze_format_string::ConversionSpecifier &CS,
5112 const char *startSpecifier, unsigned specifierLen,
5113 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005114
5115 template <typename Range>
5116 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5117 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00005118 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00005119};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005120} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00005121
Ted Kremenek02087932010-07-16 02:11:22 +00005122SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00005123 return OrigFormatExpr->getSourceRange();
5124}
5125
Ted Kremenek02087932010-07-16 02:11:22 +00005126CharSourceRange CheckFormatHandler::
5127getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00005128 SourceLocation Start = getLocationOfByte(startSpecifier);
5129 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
5130
5131 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00005132 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00005133
5134 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005135}
5136
Ted Kremenek02087932010-07-16 02:11:22 +00005137SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Stephen Hines648c3692016-09-16 01:07:04 +00005138 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
5139 S.getLangOpts(), S.Context.getTargetInfo());
Ted Kremenekab278de2010-01-28 23:39:18 +00005140}
5141
Ted Kremenek02087932010-07-16 02:11:22 +00005142void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
5143 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00005144 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
5145 getLocationOfByte(startSpecifier),
5146 /*IsStringLocation*/true,
5147 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00005148}
5149
Jordan Rose92303592012-09-08 04:00:03 +00005150void CheckFormatHandler::HandleInvalidLengthModifier(
5151 const analyze_format_string::FormatSpecifier &FS,
5152 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00005153 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00005154 using namespace analyze_format_string;
5155
5156 const LengthModifier &LM = FS.getLengthModifier();
5157 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5158
5159 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00005160 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00005161 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005162 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00005163 getLocationOfByte(LM.getStart()),
5164 /*IsStringLocation*/true,
5165 getSpecifierRange(startSpecifier, specifierLen));
5166
5167 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5168 << FixedLM->toString()
5169 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5170
5171 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005172 FixItHint Hint;
5173 if (DiagID == diag::warn_format_nonsensical_length)
5174 Hint = FixItHint::CreateRemoval(LMRange);
5175
5176 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00005177 getLocationOfByte(LM.getStart()),
5178 /*IsStringLocation*/true,
5179 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00005180 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00005181 }
5182}
5183
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005184void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00005185 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005186 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005187 using namespace analyze_format_string;
5188
5189 const LengthModifier &LM = FS.getLengthModifier();
5190 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5191
5192 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00005193 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00005194 if (FixedLM) {
5195 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5196 << LM.toString() << 0,
5197 getLocationOfByte(LM.getStart()),
5198 /*IsStringLocation*/true,
5199 getSpecifierRange(startSpecifier, specifierLen));
5200
5201 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5202 << FixedLM->toString()
5203 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5204
5205 } else {
5206 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5207 << LM.toString() << 0,
5208 getLocationOfByte(LM.getStart()),
5209 /*IsStringLocation*/true,
5210 getSpecifierRange(startSpecifier, specifierLen));
5211 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005212}
5213
5214void CheckFormatHandler::HandleNonStandardConversionSpecifier(
5215 const analyze_format_string::ConversionSpecifier &CS,
5216 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00005217 using namespace analyze_format_string;
5218
5219 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00005220 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00005221 if (FixedCS) {
5222 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5223 << CS.toString() << /*conversion specifier*/1,
5224 getLocationOfByte(CS.getStart()),
5225 /*IsStringLocation*/true,
5226 getSpecifierRange(startSpecifier, specifierLen));
5227
5228 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
5229 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
5230 << FixedCS->toString()
5231 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
5232 } else {
5233 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5234 << CS.toString() << /*conversion specifier*/1,
5235 getLocationOfByte(CS.getStart()),
5236 /*IsStringLocation*/true,
5237 getSpecifierRange(startSpecifier, specifierLen));
5238 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005239}
5240
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00005241void CheckFormatHandler::HandlePosition(const char *startPos,
5242 unsigned posLen) {
5243 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
5244 getLocationOfByte(startPos),
5245 /*IsStringLocation*/true,
5246 getSpecifierRange(startPos, posLen));
5247}
5248
Ted Kremenekd1668192010-02-27 01:41:03 +00005249void
Ted Kremenek02087932010-07-16 02:11:22 +00005250CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
5251 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005252 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
5253 << (unsigned) p,
5254 getLocationOfByte(startPos), /*IsStringLocation*/true,
5255 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00005256}
5257
Ted Kremenek02087932010-07-16 02:11:22 +00005258void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00005259 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005260 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
5261 getLocationOfByte(startPos),
5262 /*IsStringLocation*/true,
5263 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00005264}
5265
Ted Kremenek02087932010-07-16 02:11:22 +00005266void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005267 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00005268 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00005269 EmitFormatDiagnostic(
5270 S.PDiag(diag::warn_printf_format_string_contains_null_char),
5271 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
5272 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00005273 }
Ted Kremenek02087932010-07-16 02:11:22 +00005274}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005275
Jordan Rose58bbe422012-07-19 18:10:08 +00005276// Note that this may return NULL if there was an error parsing or building
5277// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00005278const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005279 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00005280}
5281
5282void CheckFormatHandler::DoneProcessing() {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005283 // Does the number of data arguments exceed the number of
5284 // format conversions in the format string?
Ted Kremenek02087932010-07-16 02:11:22 +00005285 if (!HasVAListArg) {
5286 // Find any arguments that weren't covered.
5287 CoveredArgs.flip();
5288 signed notCoveredArg = CoveredArgs.find_first();
5289 if (notCoveredArg >= 0) {
5290 assert((unsigned)notCoveredArg < NumDataArgs);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005291 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
5292 } else {
5293 UncoveredArg.setAllCovered();
Ted Kremenek02087932010-07-16 02:11:22 +00005294 }
5295 }
5296}
5297
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005298void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
5299 const Expr *ArgExpr) {
5300 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
5301 "Invalid state");
5302
5303 if (!ArgExpr)
5304 return;
5305
5306 SourceLocation Loc = ArgExpr->getLocStart();
5307
5308 if (S.getSourceManager().isInSystemMacro(Loc))
5309 return;
5310
5311 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
5312 for (auto E : DiagnosticExprs)
5313 PDiag << E->getSourceRange();
5314
5315 CheckFormatHandler::EmitFormatDiagnostic(
5316 S, IsFunctionCall, DiagnosticExprs[0],
5317 PDiag, Loc, /*IsStringLocation*/false,
5318 DiagnosticExprs[0]->getSourceRange());
5319}
5320
Ted Kremenekce815422010-07-19 21:25:57 +00005321bool
5322CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
5323 SourceLocation Loc,
5324 const char *startSpec,
5325 unsigned specifierLen,
5326 const char *csStart,
5327 unsigned csLen) {
Ted Kremenekce815422010-07-19 21:25:57 +00005328 bool keepGoing = true;
5329 if (argIndex < NumDataArgs) {
5330 // Consider the argument coverered, even though the specifier doesn't
5331 // make sense.
5332 CoveredArgs.set(argIndex);
5333 }
5334 else {
5335 // If argIndex exceeds the number of data arguments we
5336 // don't issue a warning because that is just a cascade of warnings (and
5337 // they may have intended '%%' anyway). We don't want to continue processing
5338 // the format string after this point, however, as we will like just get
5339 // gibberish when trying to match arguments.
5340 keepGoing = false;
5341 }
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005342
5343 StringRef Specifier(csStart, csLen);
5344
5345 // If the specifier in non-printable, it could be the first byte of a UTF-8
5346 // sequence. In that case, print the UTF-8 code point. If not, print the byte
5347 // hex value.
5348 std::string CodePointStr;
5349 if (!llvm::sys::locale::isPrint(*csStart)) {
Justin Lebar90910552016-09-30 00:38:45 +00005350 llvm::UTF32 CodePoint;
5351 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
5352 const llvm::UTF8 *E =
5353 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
5354 llvm::ConversionResult Result =
5355 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005356
Justin Lebar90910552016-09-30 00:38:45 +00005357 if (Result != llvm::conversionOK) {
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005358 unsigned char FirstChar = *csStart;
Justin Lebar90910552016-09-30 00:38:45 +00005359 CodePoint = (llvm::UTF32)FirstChar;
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005360 }
5361
5362 llvm::raw_string_ostream OS(CodePointStr);
5363 if (CodePoint < 256)
5364 OS << "\\x" << llvm::format("%02x", CodePoint);
5365 else if (CodePoint <= 0xFFFF)
5366 OS << "\\u" << llvm::format("%04x", CodePoint);
5367 else
5368 OS << "\\U" << llvm::format("%08x", CodePoint);
5369 OS.flush();
5370 Specifier = CodePointStr;
5371 }
5372
5373 EmitFormatDiagnostic(
5374 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
5375 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
5376
Ted Kremenekce815422010-07-19 21:25:57 +00005377 return keepGoing;
5378}
5379
Richard Trieu03cf7b72011-10-28 00:41:25 +00005380void
5381CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
5382 const char *startSpec,
5383 unsigned specifierLen) {
5384 EmitFormatDiagnostic(
5385 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
5386 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
5387}
5388
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005389bool
5390CheckFormatHandler::CheckNumArgs(
5391 const analyze_format_string::FormatSpecifier &FS,
5392 const analyze_format_string::ConversionSpecifier &CS,
5393 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
5394
5395 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005396 PartialDiagnostic PDiag = FS.usesPositionalArg()
5397 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
5398 << (argIndex+1) << NumDataArgs)
5399 : S.PDiag(diag::warn_printf_insufficient_data_args);
5400 EmitFormatDiagnostic(
5401 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
5402 getSpecifierRange(startSpecifier, specifierLen));
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005403
5404 // Since more arguments than conversion tokens are given, by extension
5405 // all arguments are covered, so mark this as so.
5406 UncoveredArg.setAllCovered();
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005407 return false;
5408 }
5409 return true;
5410}
5411
Richard Trieu03cf7b72011-10-28 00:41:25 +00005412template<typename Range>
5413void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
5414 SourceLocation Loc,
5415 bool IsStringLocation,
5416 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00005417 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005418 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00005419 Loc, IsStringLocation, StringRange, FixIt);
5420}
5421
5422/// \brief If the format string is not within the funcion call, emit a note
5423/// so that the function call and string are in diagnostic messages.
5424///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00005425/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00005426/// call and only one diagnostic message will be produced. Otherwise, an
5427/// extra note will be emitted pointing to location of the format string.
5428///
5429/// \param ArgumentExpr the expression that is passed as the format string
5430/// argument in the function call. Used for getting locations when two
5431/// diagnostics are emitted.
5432///
5433/// \param PDiag the callee should already have provided any strings for the
5434/// diagnostic message. This function only adds locations and fixits
5435/// to diagnostics.
5436///
5437/// \param Loc primary location for diagnostic. If two diagnostics are
5438/// required, one will be at Loc and a new SourceLocation will be created for
5439/// the other one.
5440///
5441/// \param IsStringLocation if true, Loc points to the format string should be
5442/// used for the note. Otherwise, Loc points to the argument list and will
5443/// be used with PDiag.
5444///
5445/// \param StringRange some or all of the string to highlight. This is
5446/// templated so it can accept either a CharSourceRange or a SourceRange.
5447///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00005448/// \param FixIt optional fix it hint for the format string.
Benjamin Kramer7320b992016-06-15 14:20:56 +00005449template <typename Range>
5450void CheckFormatHandler::EmitFormatDiagnostic(
5451 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
5452 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
5453 Range StringRange, ArrayRef<FixItHint> FixIt) {
Jordan Roseaee34382012-09-05 22:56:26 +00005454 if (InFunctionCall) {
5455 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
5456 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00005457 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00005458 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005459 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
5460 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00005461
5462 const Sema::SemaDiagnosticBuilder &Note =
5463 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
5464 diag::note_format_string_defined);
5465
5466 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00005467 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00005468 }
5469}
5470
Ted Kremenek02087932010-07-16 02:11:22 +00005471//===--- CHECK: Printf format string checking ------------------------------===//
5472
5473namespace {
5474class CheckPrintfHandler : public CheckFormatHandler {
5475public:
Stephen Hines648c3692016-09-16 01:07:04 +00005476 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00005477 const Expr *origFormatExpr,
5478 const Sema::FormatStringType type, unsigned firstDataArg,
5479 unsigned numDataArgs, bool isObjC, const char *beg,
5480 bool hasVAListArg, ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005481 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00005482 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005483 llvm::SmallBitVector &CheckedVarArgs,
5484 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00005485 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
5486 numDataArgs, beg, hasVAListArg, Args, formatIdx,
5487 inFunctionCall, CallType, CheckedVarArgs,
5488 UncoveredArg) {}
5489
5490 bool isObjCContext() const { return FSType == Sema::FST_NSString; }
5491
5492 /// Returns true if '%@' specifiers are allowed in the format string.
5493 bool allowsObjCArg() const {
5494 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
5495 FSType == Sema::FST_OSTrace;
5496 }
Jordan Rose3e0ec582012-07-19 18:10:23 +00005497
Ted Kremenek02087932010-07-16 02:11:22 +00005498 bool HandleInvalidPrintfConversionSpecifier(
5499 const analyze_printf::PrintfSpecifier &FS,
5500 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005501 unsigned specifierLen) override;
5502
Ted Kremenek02087932010-07-16 02:11:22 +00005503 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
5504 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005505 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00005506 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5507 const char *StartSpecifier,
5508 unsigned SpecifierLen,
5509 const Expr *E);
5510
Ted Kremenek02087932010-07-16 02:11:22 +00005511 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
5512 const char *startSpecifier, unsigned specifierLen);
5513 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
5514 const analyze_printf::OptionalAmount &Amt,
5515 unsigned type,
5516 const char *startSpecifier, unsigned specifierLen);
5517 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
5518 const analyze_printf::OptionalFlag &flag,
5519 const char *startSpecifier, unsigned specifierLen);
5520 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
5521 const analyze_printf::OptionalFlag &ignoredFlag,
5522 const analyze_printf::OptionalFlag &flag,
5523 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005524 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00005525 const Expr *E);
Ted Kremenek2b417712015-07-02 05:39:16 +00005526
5527 void HandleEmptyObjCModifierFlag(const char *startFlag,
5528 unsigned flagLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00005529
Ted Kremenek2b417712015-07-02 05:39:16 +00005530 void HandleInvalidObjCModifierFlag(const char *startFlag,
5531 unsigned flagLen) override;
5532
5533 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
5534 const char *flagsEnd,
5535 const char *conversionPosition)
5536 override;
5537};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005538} // end anonymous namespace
Ted Kremenek02087932010-07-16 02:11:22 +00005539
5540bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
5541 const analyze_printf::PrintfSpecifier &FS,
5542 const char *startSpecifier,
5543 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005544 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00005545 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00005546
Ted Kremenekce815422010-07-19 21:25:57 +00005547 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
5548 getLocationOfByte(CS.getStart()),
5549 startSpecifier, specifierLen,
5550 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00005551}
5552
Ted Kremenek02087932010-07-16 02:11:22 +00005553bool CheckPrintfHandler::HandleAmount(
5554 const analyze_format_string::OptionalAmount &Amt,
5555 unsigned k, const char *startSpecifier,
5556 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00005557 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00005558 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00005559 unsigned argIndex = Amt.getArgIndex();
5560 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005561 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
5562 << k,
5563 getLocationOfByte(Amt.getStart()),
5564 /*IsStringLocation*/true,
5565 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00005566 // Don't do any more checking. We will just emit
5567 // spurious errors.
5568 return false;
5569 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005570
Ted Kremenek5739de72010-01-29 01:06:55 +00005571 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00005572 // Although not in conformance with C99, we also allow the argument to be
5573 // an 'unsigned int' as that is a reasonably safe case. GCC also
5574 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00005575 CoveredArgs.set(argIndex);
5576 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00005577 if (!Arg)
5578 return false;
5579
Ted Kremenek5739de72010-01-29 01:06:55 +00005580 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005581
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005582 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
5583 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005584
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005585 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005586 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005587 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00005588 << T << Arg->getSourceRange(),
5589 getLocationOfByte(Amt.getStart()),
5590 /*IsStringLocation*/true,
5591 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00005592 // Don't do any more checking. We will just emit
5593 // spurious errors.
5594 return false;
5595 }
5596 }
5597 }
5598 return true;
5599}
Ted Kremenek5739de72010-01-29 01:06:55 +00005600
Tom Careb49ec692010-06-17 19:00:27 +00005601void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00005602 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005603 const analyze_printf::OptionalAmount &Amt,
5604 unsigned type,
5605 const char *startSpecifier,
5606 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005607 const analyze_printf::PrintfConversionSpecifier &CS =
5608 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00005609
Richard Trieu03cf7b72011-10-28 00:41:25 +00005610 FixItHint fixit =
5611 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
5612 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
5613 Amt.getConstantLength()))
5614 : FixItHint();
5615
5616 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
5617 << type << CS.toString(),
5618 getLocationOfByte(Amt.getStart()),
5619 /*IsStringLocation*/true,
5620 getSpecifierRange(startSpecifier, specifierLen),
5621 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00005622}
5623
Ted Kremenek02087932010-07-16 02:11:22 +00005624void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005625 const analyze_printf::OptionalFlag &flag,
5626 const char *startSpecifier,
5627 unsigned specifierLen) {
5628 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005629 const analyze_printf::PrintfConversionSpecifier &CS =
5630 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00005631 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
5632 << flag.toString() << CS.toString(),
5633 getLocationOfByte(flag.getPosition()),
5634 /*IsStringLocation*/true,
5635 getSpecifierRange(startSpecifier, specifierLen),
5636 FixItHint::CreateRemoval(
5637 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00005638}
5639
5640void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00005641 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005642 const analyze_printf::OptionalFlag &ignoredFlag,
5643 const analyze_printf::OptionalFlag &flag,
5644 const char *startSpecifier,
5645 unsigned specifierLen) {
5646 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00005647 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
5648 << ignoredFlag.toString() << flag.toString(),
5649 getLocationOfByte(ignoredFlag.getPosition()),
5650 /*IsStringLocation*/true,
5651 getSpecifierRange(startSpecifier, specifierLen),
5652 FixItHint::CreateRemoval(
5653 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00005654}
5655
Ted Kremenek2b417712015-07-02 05:39:16 +00005656// void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5657// bool IsStringLocation, Range StringRange,
5658// ArrayRef<FixItHint> Fixit = None);
5659
5660void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
5661 unsigned flagLen) {
5662 // Warn about an empty flag.
5663 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
5664 getLocationOfByte(startFlag),
5665 /*IsStringLocation*/true,
5666 getSpecifierRange(startFlag, flagLen));
5667}
5668
5669void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
5670 unsigned flagLen) {
5671 // Warn about an invalid flag.
5672 auto Range = getSpecifierRange(startFlag, flagLen);
5673 StringRef flag(startFlag, flagLen);
5674 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
5675 getLocationOfByte(startFlag),
5676 /*IsStringLocation*/true,
5677 Range, FixItHint::CreateRemoval(Range));
5678}
5679
5680void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
5681 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
5682 // Warn about using '[...]' without a '@' conversion.
5683 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
5684 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
5685 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
5686 getLocationOfByte(conversionPosition),
5687 /*IsStringLocation*/true,
5688 Range, FixItHint::CreateRemoval(Range));
5689}
5690
Richard Smith55ce3522012-06-25 20:30:08 +00005691// Determines if the specified is a C++ class or struct containing
5692// a member with the specified name and kind (e.g. a CXXMethodDecl named
5693// "c_str()").
5694template<typename MemberKind>
5695static llvm::SmallPtrSet<MemberKind*, 1>
5696CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
5697 const RecordType *RT = Ty->getAs<RecordType>();
5698 llvm::SmallPtrSet<MemberKind*, 1> Results;
5699
5700 if (!RT)
5701 return Results;
5702 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00005703 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00005704 return Results;
5705
Alp Tokerb6cc5922014-05-03 03:45:55 +00005706 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00005707 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00005708 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00005709
5710 // We just need to include all members of the right kind turned up by the
5711 // filter, at this point.
5712 if (S.LookupQualifiedName(R, RT->getDecl()))
5713 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
5714 NamedDecl *decl = (*I)->getUnderlyingDecl();
5715 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
5716 Results.insert(FK);
5717 }
5718 return Results;
5719}
5720
Richard Smith2868a732014-02-28 01:36:39 +00005721/// Check if we could call '.c_str()' on an object.
5722///
5723/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
5724/// allow the call, or if it would be ambiguous).
5725bool Sema::hasCStrMethod(const Expr *E) {
5726 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5727 MethodSet Results =
5728 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
5729 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5730 MI != ME; ++MI)
5731 if ((*MI)->getMinRequiredArguments() == 0)
5732 return true;
5733 return false;
5734}
5735
Richard Smith55ce3522012-06-25 20:30:08 +00005736// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005737// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00005738// Returns true when a c_str() conversion method is found.
5739bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00005740 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00005741 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5742
5743 MethodSet Results =
5744 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
5745
5746 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5747 MI != ME; ++MI) {
5748 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00005749 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00005750 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00005751 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00005752 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00005753 S.Diag(E->getLocStart(), diag::note_printf_c_str)
5754 << "c_str()"
5755 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
5756 return true;
5757 }
5758 }
5759
5760 return false;
5761}
5762
Ted Kremenekab278de2010-01-28 23:39:18 +00005763bool
Ted Kremenek02087932010-07-16 02:11:22 +00005764CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00005765 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00005766 const char *startSpecifier,
5767 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005768 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00005769 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005770 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00005771
Ted Kremenek6cd69422010-07-19 22:01:06 +00005772 if (FS.consumesDataArgument()) {
5773 if (atFirstArg) {
5774 atFirstArg = false;
5775 usesPositionalArgs = FS.usesPositionalArg();
5776 }
5777 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005778 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
5779 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00005780 return false;
5781 }
Ted Kremenek5739de72010-01-29 01:06:55 +00005782 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005783
Ted Kremenekd1668192010-02-27 01:41:03 +00005784 // First check if the field width, precision, and conversion specifier
5785 // have matching data arguments.
5786 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
5787 startSpecifier, specifierLen)) {
5788 return false;
5789 }
5790
5791 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
5792 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00005793 return false;
5794 }
5795
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005796 if (!CS.consumesDataArgument()) {
5797 // FIXME: Technically specifying a precision or field width here
5798 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00005799 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005800 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005801
Ted Kremenek4a49d982010-02-26 19:18:41 +00005802 // Consume the argument.
5803 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00005804 if (argIndex < NumDataArgs) {
5805 // The check to see if the argIndex is valid will come later.
5806 // We set the bit here because we may exit early from this
5807 // function if we encounter some other error.
5808 CoveredArgs.set(argIndex);
5809 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00005810
Dimitry Andric6b5ed342015-02-19 22:32:33 +00005811 // FreeBSD kernel extensions.
5812 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
5813 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
5814 // We need at least two arguments.
5815 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
5816 return false;
5817
5818 // Claim the second argument.
5819 CoveredArgs.set(argIndex + 1);
5820
5821 // Type check the first argument (int for %b, pointer for %D)
5822 const Expr *Ex = getDataArg(argIndex);
5823 const analyze_printf::ArgType &AT =
5824 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
5825 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
5826 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
5827 EmitFormatDiagnostic(
5828 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5829 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
5830 << false << Ex->getSourceRange(),
5831 Ex->getLocStart(), /*IsStringLocation*/false,
5832 getSpecifierRange(startSpecifier, specifierLen));
5833
5834 // Type check the second argument (char * for both %b and %D)
5835 Ex = getDataArg(argIndex + 1);
5836 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
5837 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
5838 EmitFormatDiagnostic(
5839 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5840 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
5841 << false << Ex->getSourceRange(),
5842 Ex->getLocStart(), /*IsStringLocation*/false,
5843 getSpecifierRange(startSpecifier, specifierLen));
5844
5845 return true;
5846 }
5847
Ted Kremenek4a49d982010-02-26 19:18:41 +00005848 // Check for using an Objective-C specific conversion specifier
5849 // in a non-ObjC literal.
Mehdi Amini06d367c2016-10-24 20:39:34 +00005850 if (!allowsObjCArg() && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00005851 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5852 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00005853 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005854
Mehdi Amini06d367c2016-10-24 20:39:34 +00005855 // %P can only be used with os_log.
5856 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
5857 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5858 specifierLen);
5859 }
5860
5861 // %n is not allowed with os_log.
5862 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
5863 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
5864 getLocationOfByte(CS.getStart()),
5865 /*IsStringLocation*/ false,
5866 getSpecifierRange(startSpecifier, specifierLen));
5867
5868 return true;
5869 }
5870
5871 // Only scalars are allowed for os_trace.
5872 if (FSType == Sema::FST_OSTrace &&
5873 (CS.getKind() == ConversionSpecifier::PArg ||
5874 CS.getKind() == ConversionSpecifier::sArg ||
5875 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
5876 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5877 specifierLen);
5878 }
5879
5880 // Check for use of public/private annotation outside of os_log().
5881 if (FSType != Sema::FST_OSLog) {
5882 if (FS.isPublic().isSet()) {
5883 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
5884 << "public",
5885 getLocationOfByte(FS.isPublic().getPosition()),
5886 /*IsStringLocation*/ false,
5887 getSpecifierRange(startSpecifier, specifierLen));
5888 }
5889 if (FS.isPrivate().isSet()) {
5890 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
5891 << "private",
5892 getLocationOfByte(FS.isPrivate().getPosition()),
5893 /*IsStringLocation*/ false,
5894 getSpecifierRange(startSpecifier, specifierLen));
5895 }
5896 }
5897
Tom Careb49ec692010-06-17 19:00:27 +00005898 // Check for invalid use of field width
5899 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00005900 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00005901 startSpecifier, specifierLen);
5902 }
5903
5904 // Check for invalid use of precision
5905 if (!FS.hasValidPrecision()) {
5906 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
5907 startSpecifier, specifierLen);
5908 }
5909
Mehdi Amini06d367c2016-10-24 20:39:34 +00005910 // Precision is mandatory for %P specifier.
5911 if (CS.getKind() == ConversionSpecifier::PArg &&
5912 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
5913 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
5914 getLocationOfByte(startSpecifier),
5915 /*IsStringLocation*/ false,
5916 getSpecifierRange(startSpecifier, specifierLen));
5917 }
5918
Tom Careb49ec692010-06-17 19:00:27 +00005919 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00005920 if (!FS.hasValidThousandsGroupingPrefix())
5921 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00005922 if (!FS.hasValidLeadingZeros())
5923 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
5924 if (!FS.hasValidPlusPrefix())
5925 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00005926 if (!FS.hasValidSpacePrefix())
5927 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00005928 if (!FS.hasValidAlternativeForm())
5929 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
5930 if (!FS.hasValidLeftJustified())
5931 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
5932
5933 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00005934 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
5935 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
5936 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00005937 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
5938 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
5939 startSpecifier, specifierLen);
5940
5941 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00005942 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00005943 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5944 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00005945 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00005946 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00005947 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00005948 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5949 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00005950
Jordan Rose92303592012-09-08 04:00:03 +00005951 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
5952 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
5953
Ted Kremenek9fcd8302010-01-29 01:43:31 +00005954 // The remaining checks depend on the data arguments.
5955 if (HasVAListArg)
5956 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005957
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005958 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00005959 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005960
Jordan Rose58bbe422012-07-19 18:10:08 +00005961 const Expr *Arg = getDataArg(argIndex);
5962 if (!Arg)
5963 return true;
5964
5965 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00005966}
5967
Jordan Roseaee34382012-09-05 22:56:26 +00005968static bool requiresParensToAddCast(const Expr *E) {
5969 // FIXME: We should have a general way to reason about operator
5970 // precedence and whether parens are actually needed here.
5971 // Take care of a few common cases where they aren't.
5972 const Expr *Inside = E->IgnoreImpCasts();
5973 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
5974 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
5975
5976 switch (Inside->getStmtClass()) {
5977 case Stmt::ArraySubscriptExprClass:
5978 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005979 case Stmt::CharacterLiteralClass:
5980 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005981 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005982 case Stmt::FloatingLiteralClass:
5983 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005984 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005985 case Stmt::ObjCArrayLiteralClass:
5986 case Stmt::ObjCBoolLiteralExprClass:
5987 case Stmt::ObjCBoxedExprClass:
5988 case Stmt::ObjCDictionaryLiteralClass:
5989 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005990 case Stmt::ObjCIvarRefExprClass:
5991 case Stmt::ObjCMessageExprClass:
5992 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005993 case Stmt::ObjCStringLiteralClass:
5994 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005995 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005996 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005997 case Stmt::UnaryOperatorClass:
5998 return false;
5999 default:
6000 return true;
6001 }
6002}
6003
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006004static std::pair<QualType, StringRef>
6005shouldNotPrintDirectly(const ASTContext &Context,
6006 QualType IntendedTy,
6007 const Expr *E) {
6008 // Use a 'while' to peel off layers of typedefs.
6009 QualType TyTy = IntendedTy;
6010 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
6011 StringRef Name = UserTy->getDecl()->getName();
6012 QualType CastTy = llvm::StringSwitch<QualType>(Name)
Alexander Shaposhnikov62351372017-06-26 23:02:27 +00006013 .Case("CFIndex", Context.LongTy)
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006014 .Case("NSInteger", Context.LongTy)
6015 .Case("NSUInteger", Context.UnsignedLongTy)
6016 .Case("SInt32", Context.IntTy)
6017 .Case("UInt32", Context.UnsignedIntTy)
6018 .Default(QualType());
6019
6020 if (!CastTy.isNull())
6021 return std::make_pair(CastTy, Name);
6022
6023 TyTy = UserTy->desugar();
6024 }
6025
6026 // Strip parens if necessary.
6027 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
6028 return shouldNotPrintDirectly(Context,
6029 PE->getSubExpr()->getType(),
6030 PE->getSubExpr());
6031
6032 // If this is a conditional expression, then its result type is constructed
6033 // via usual arithmetic conversions and thus there might be no necessary
6034 // typedef sugar there. Recurse to operands to check for NSInteger &
6035 // Co. usage condition.
6036 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
6037 QualType TrueTy, FalseTy;
6038 StringRef TrueName, FalseName;
6039
6040 std::tie(TrueTy, TrueName) =
6041 shouldNotPrintDirectly(Context,
6042 CO->getTrueExpr()->getType(),
6043 CO->getTrueExpr());
6044 std::tie(FalseTy, FalseName) =
6045 shouldNotPrintDirectly(Context,
6046 CO->getFalseExpr()->getType(),
6047 CO->getFalseExpr());
6048
6049 if (TrueTy == FalseTy)
6050 return std::make_pair(TrueTy, TrueName);
6051 else if (TrueTy.isNull())
6052 return std::make_pair(FalseTy, FalseName);
6053 else if (FalseTy.isNull())
6054 return std::make_pair(TrueTy, TrueName);
6055 }
6056
6057 return std::make_pair(QualType(), StringRef());
6058}
6059
Richard Smith55ce3522012-06-25 20:30:08 +00006060bool
6061CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
6062 const char *StartSpecifier,
6063 unsigned SpecifierLen,
6064 const Expr *E) {
6065 using namespace analyze_format_string;
6066 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006067 // Now type check the data expression that matches the
6068 // format specifier.
Mehdi Amini06d367c2016-10-24 20:39:34 +00006069 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
Jordan Rose22b74712012-09-05 22:56:19 +00006070 if (!AT.isValid())
6071 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00006072
Jordan Rose598ec092012-12-05 18:44:40 +00006073 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00006074 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
6075 ExprTy = TET->getUnderlyingExpr()->getType();
6076 }
6077
Seth Cantrellb4802962015-03-04 03:12:10 +00006078 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
6079
6080 if (match == analyze_printf::ArgType::Match) {
Jordan Rose22b74712012-09-05 22:56:19 +00006081 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00006082 }
Jordan Rose98709982012-06-04 22:48:57 +00006083
Jordan Rose22b74712012-09-05 22:56:19 +00006084 // Look through argument promotions for our error message's reported type.
6085 // This includes the integral and floating promotions, but excludes array
6086 // and function pointer decay; seeing that an argument intended to be a
6087 // string has type 'char [6]' is probably more confusing than 'char *'.
6088 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6089 if (ICE->getCastKind() == CK_IntegralCast ||
6090 ICE->getCastKind() == CK_FloatingCast) {
6091 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00006092 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00006093
6094 // Check if we didn't match because of an implicit cast from a 'char'
6095 // or 'short' to an 'int'. This is done because printf is a varargs
6096 // function.
6097 if (ICE->getType() == S.Context.IntTy ||
6098 ICE->getType() == S.Context.UnsignedIntTy) {
6099 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00006100 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00006101 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00006102 }
Jordan Rose98709982012-06-04 22:48:57 +00006103 }
Jordan Rose598ec092012-12-05 18:44:40 +00006104 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
6105 // Special case for 'a', which has type 'int' in C.
6106 // Note, however, that we do /not/ want to treat multibyte constants like
6107 // 'MooV' as characters! This form is deprecated but still exists.
6108 if (ExprTy == S.Context.IntTy)
6109 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
6110 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00006111 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006112
Jordan Rosebc53ed12014-05-31 04:12:14 +00006113 // Look through enums to their underlying type.
6114 bool IsEnum = false;
6115 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
6116 ExprTy = EnumTy->getDecl()->getIntegerType();
6117 IsEnum = true;
6118 }
6119
Jordan Rose0e5badd2012-12-05 18:44:49 +00006120 // %C in an Objective-C context prints a unichar, not a wchar_t.
6121 // If the argument is an integer of some kind, believe the %C and suggest
6122 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00006123 QualType IntendedTy = ExprTy;
Mehdi Amini06d367c2016-10-24 20:39:34 +00006124 if (isObjCContext() &&
Jordan Rose0e5badd2012-12-05 18:44:49 +00006125 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
6126 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
6127 !ExprTy->isCharType()) {
6128 // 'unichar' is defined as a typedef of unsigned short, but we should
6129 // prefer using the typedef if it is visible.
6130 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00006131
6132 // While we are here, check if the value is an IntegerLiteral that happens
6133 // to be within the valid range.
6134 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
6135 const llvm::APInt &V = IL->getValue();
6136 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
6137 return true;
6138 }
6139
Jordan Rose0e5badd2012-12-05 18:44:49 +00006140 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
6141 Sema::LookupOrdinaryName);
6142 if (S.LookupName(Result, S.getCurScope())) {
6143 NamedDecl *ND = Result.getFoundDecl();
6144 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
6145 if (TD->getUnderlyingType() == IntendedTy)
6146 IntendedTy = S.Context.getTypedefType(TD);
6147 }
6148 }
6149 }
6150
6151 // Special-case some of Darwin's platform-independence types by suggesting
6152 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006153 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00006154 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006155 QualType CastTy;
6156 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
6157 if (!CastTy.isNull()) {
6158 IntendedTy = CastTy;
6159 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00006160 }
6161 }
6162
Jordan Rose22b74712012-09-05 22:56:19 +00006163 // We may be able to offer a FixItHint if it is a supported type.
6164 PrintfSpecifier fixedFS = FS;
Mehdi Amini06d367c2016-10-24 20:39:34 +00006165 bool success =
6166 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006167
Jordan Rose22b74712012-09-05 22:56:19 +00006168 if (success) {
6169 // Get the fix string from the fixed format specifier
6170 SmallString<16> buf;
6171 llvm::raw_svector_ostream os(buf);
6172 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006173
Jordan Roseaee34382012-09-05 22:56:26 +00006174 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
6175
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006176 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Daniel Jasperad8d8492015-03-04 14:18:20 +00006177 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6178 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6179 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6180 }
Jordan Rose0e5badd2012-12-05 18:44:49 +00006181 // In this case, the specifier is wrong and should be changed to match
6182 // the argument.
Daniel Jasperad8d8492015-03-04 14:18:20 +00006183 EmitFormatDiagnostic(S.PDiag(diag)
6184 << AT.getRepresentativeTypeName(S.Context)
6185 << IntendedTy << IsEnum << E->getSourceRange(),
6186 E->getLocStart(),
6187 /*IsStringLocation*/ false, SpecRange,
6188 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00006189 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00006190 // The canonical type for formatting this value is different from the
6191 // actual type of the expression. (This occurs, for example, with Darwin's
6192 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
6193 // should be printed as 'long' for 64-bit compatibility.)
6194 // Rather than emitting a normal format/argument mismatch, we want to
6195 // add a cast to the recommended type (and correct the format string
6196 // if necessary).
6197 SmallString<16> CastBuf;
6198 llvm::raw_svector_ostream CastFix(CastBuf);
6199 CastFix << "(";
6200 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
6201 CastFix << ")";
6202
6203 SmallVector<FixItHint,4> Hints;
6204 if (!AT.matchesType(S.Context, IntendedTy))
6205 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
6206
6207 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
6208 // If there's already a cast present, just replace it.
6209 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
6210 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
6211
6212 } else if (!requiresParensToAddCast(E)) {
6213 // If the expression has high enough precedence,
6214 // just write the C-style cast.
6215 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6216 CastFix.str()));
6217 } else {
6218 // Otherwise, add parens around the expression as well as the cast.
6219 CastFix << "(";
6220 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6221 CastFix.str()));
6222
Alp Tokerb6cc5922014-05-03 03:45:55 +00006223 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00006224 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
6225 }
6226
Jordan Rose0e5badd2012-12-05 18:44:49 +00006227 if (ShouldNotPrintDirectly) {
6228 // The expression has a type that should not be printed directly.
6229 // We extract the name from the typedef because we don't want to show
6230 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006231 StringRef Name;
6232 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
6233 Name = TypedefTy->getDecl()->getName();
6234 else
6235 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00006236 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00006237 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00006238 << E->getSourceRange(),
6239 E->getLocStart(), /*IsStringLocation=*/false,
6240 SpecRange, Hints);
6241 } else {
6242 // In this case, the expression could be printed using a different
6243 // specifier, but we've decided that the specifier is probably correct
6244 // and we should cast instead. Just use the normal warning message.
6245 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00006246 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6247 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00006248 << E->getSourceRange(),
6249 E->getLocStart(), /*IsStringLocation*/false,
6250 SpecRange, Hints);
6251 }
Jordan Roseaee34382012-09-05 22:56:26 +00006252 }
Jordan Rose22b74712012-09-05 22:56:19 +00006253 } else {
6254 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
6255 SpecifierLen);
6256 // Since the warning for passing non-POD types to variadic functions
6257 // was deferred until now, we emit a warning for non-POD
6258 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00006259 switch (S.isValidVarArgType(ExprTy)) {
6260 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00006261 case Sema::VAK_ValidInCXX11: {
6262 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6263 if (match == analyze_printf::ArgType::NoMatchPedantic) {
6264 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6265 }
Richard Smithd7293d72013-08-05 18:49:43 +00006266
Seth Cantrellb4802962015-03-04 03:12:10 +00006267 EmitFormatDiagnostic(
6268 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
6269 << IsEnum << CSR << E->getSourceRange(),
6270 E->getLocStart(), /*IsStringLocation*/ false, CSR);
6271 break;
6272 }
Richard Smithd7293d72013-08-05 18:49:43 +00006273 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00006274 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00006275 EmitFormatDiagnostic(
6276 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006277 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00006278 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00006279 << CallType
6280 << AT.getRepresentativeTypeName(S.Context)
6281 << CSR
6282 << E->getSourceRange(),
6283 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00006284 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00006285 break;
6286
6287 case Sema::VAK_Invalid:
6288 if (ExprTy->isObjCObjectType())
6289 EmitFormatDiagnostic(
6290 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
6291 << S.getLangOpts().CPlusPlus11
6292 << ExprTy
6293 << CallType
6294 << AT.getRepresentativeTypeName(S.Context)
6295 << CSR
6296 << E->getSourceRange(),
6297 E->getLocStart(), /*IsStringLocation*/false, CSR);
6298 else
6299 // FIXME: If this is an initializer list, suggest removing the braces
6300 // or inserting a cast to the target type.
6301 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
6302 << isa<InitListExpr>(E) << ExprTy << CallType
6303 << AT.getRepresentativeTypeName(S.Context)
6304 << E->getSourceRange();
6305 break;
6306 }
6307
6308 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
6309 "format string specifier index out of range");
6310 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006311 }
6312
Ted Kremenekab278de2010-01-28 23:39:18 +00006313 return true;
6314}
6315
Ted Kremenek02087932010-07-16 02:11:22 +00006316//===--- CHECK: Scanf format string checking ------------------------------===//
6317
6318namespace {
6319class CheckScanfHandler : public CheckFormatHandler {
6320public:
Stephen Hines648c3692016-09-16 01:07:04 +00006321 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00006322 const Expr *origFormatExpr, Sema::FormatStringType type,
6323 unsigned firstDataArg, unsigned numDataArgs,
6324 const char *beg, bool hasVAListArg,
6325 ArrayRef<const Expr *> Args, unsigned formatIdx,
6326 bool inFunctionCall, Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006327 llvm::SmallBitVector &CheckedVarArgs,
6328 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00006329 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
6330 numDataArgs, beg, hasVAListArg, Args, formatIdx,
6331 inFunctionCall, CallType, CheckedVarArgs,
6332 UncoveredArg) {}
6333
Ted Kremenek02087932010-07-16 02:11:22 +00006334 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
6335 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006336 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00006337
6338 bool HandleInvalidScanfConversionSpecifier(
6339 const analyze_scanf::ScanfSpecifier &FS,
6340 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006341 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006342
Craig Toppere14c0f82014-03-12 04:55:44 +00006343 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00006344};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006345} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00006346
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006347void CheckScanfHandler::HandleIncompleteScanList(const char *start,
6348 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006349 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
6350 getLocationOfByte(end), /*IsStringLocation*/true,
6351 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006352}
6353
Ted Kremenekce815422010-07-19 21:25:57 +00006354bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
6355 const analyze_scanf::ScanfSpecifier &FS,
6356 const char *startSpecifier,
6357 unsigned specifierLen) {
6358
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006359 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00006360 FS.getConversionSpecifier();
6361
6362 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
6363 getLocationOfByte(CS.getStart()),
6364 startSpecifier, specifierLen,
6365 CS.getStart(), CS.getLength());
6366}
6367
Ted Kremenek02087932010-07-16 02:11:22 +00006368bool CheckScanfHandler::HandleScanfSpecifier(
6369 const analyze_scanf::ScanfSpecifier &FS,
6370 const char *startSpecifier,
6371 unsigned specifierLen) {
Ted Kremenek02087932010-07-16 02:11:22 +00006372 using namespace analyze_scanf;
6373 using namespace analyze_format_string;
6374
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006375 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00006376
Ted Kremenek6cd69422010-07-19 22:01:06 +00006377 // Handle case where '%' and '*' don't consume an argument. These shouldn't
6378 // be used to decide if we are using positional arguments consistently.
6379 if (FS.consumesDataArgument()) {
6380 if (atFirstArg) {
6381 atFirstArg = false;
6382 usesPositionalArgs = FS.usesPositionalArg();
6383 }
6384 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006385 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
6386 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00006387 return false;
6388 }
Ted Kremenek02087932010-07-16 02:11:22 +00006389 }
6390
6391 // Check if the field with is non-zero.
6392 const OptionalAmount &Amt = FS.getFieldWidth();
6393 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
6394 if (Amt.getConstantAmount() == 0) {
6395 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
6396 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00006397 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
6398 getLocationOfByte(Amt.getStart()),
6399 /*IsStringLocation*/true, R,
6400 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00006401 }
6402 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006403
Ted Kremenek02087932010-07-16 02:11:22 +00006404 if (!FS.consumesDataArgument()) {
6405 // FIXME: Technically specifying a precision or field width here
6406 // makes no sense. Worth issuing a warning at some point.
6407 return true;
6408 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006409
Ted Kremenek02087932010-07-16 02:11:22 +00006410 // Consume the argument.
6411 unsigned argIndex = FS.getArgIndex();
6412 if (argIndex < NumDataArgs) {
6413 // The check to see if the argIndex is valid will come later.
6414 // We set the bit here because we may exit early from this
6415 // function if we encounter some other error.
6416 CoveredArgs.set(argIndex);
6417 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006418
Ted Kremenek4407ea42010-07-20 20:04:47 +00006419 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00006420 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00006421 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6422 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00006423 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006424 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00006425 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006426 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6427 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00006428
Jordan Rose92303592012-09-08 04:00:03 +00006429 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6430 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6431
Ted Kremenek02087932010-07-16 02:11:22 +00006432 // The remaining checks depend on the data arguments.
6433 if (HasVAListArg)
6434 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00006435
Ted Kremenek6adb7e32010-07-26 19:45:42 +00006436 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00006437 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00006438
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006439 // Check that the argument type matches the format specifier.
6440 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00006441 if (!Ex)
6442 return true;
6443
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00006444 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00006445
6446 if (!AT.isValid()) {
6447 return true;
6448 }
6449
Seth Cantrellb4802962015-03-04 03:12:10 +00006450 analyze_format_string::ArgType::MatchKind match =
6451 AT.matchesType(S.Context, Ex->getType());
Seth Cantrell79340072015-03-04 05:58:08 +00006452 if (match == analyze_format_string::ArgType::Match) {
6453 return true;
6454 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006455
Seth Cantrell79340072015-03-04 05:58:08 +00006456 ScanfSpecifier fixedFS = FS;
6457 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
6458 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006459
Seth Cantrell79340072015-03-04 05:58:08 +00006460 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6461 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6462 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6463 }
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006464
Seth Cantrell79340072015-03-04 05:58:08 +00006465 if (success) {
6466 // Get the fix string from the fixed format specifier.
6467 SmallString<128> buf;
6468 llvm::raw_svector_ostream os(buf);
6469 fixedFS.toString(os);
6470
6471 EmitFormatDiagnostic(
6472 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
6473 << Ex->getType() << false << Ex->getSourceRange(),
6474 Ex->getLocStart(),
6475 /*IsStringLocation*/ false,
6476 getSpecifierRange(startSpecifier, specifierLen),
6477 FixItHint::CreateReplacement(
6478 getSpecifierRange(startSpecifier, specifierLen), os.str()));
6479 } else {
6480 EmitFormatDiagnostic(S.PDiag(diag)
6481 << AT.getRepresentativeTypeName(S.Context)
6482 << Ex->getType() << false << Ex->getSourceRange(),
6483 Ex->getLocStart(),
6484 /*IsStringLocation*/ false,
6485 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006486 }
6487
Ted Kremenek02087932010-07-16 02:11:22 +00006488 return true;
6489}
6490
Stephen Hines648c3692016-09-16 01:07:04 +00006491static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006492 const Expr *OrigFormatExpr,
6493 ArrayRef<const Expr *> Args,
6494 bool HasVAListArg, unsigned format_idx,
6495 unsigned firstDataArg,
6496 Sema::FormatStringType Type,
6497 bool inFunctionCall,
6498 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006499 llvm::SmallBitVector &CheckedVarArgs,
6500 UncoveredArgHandler &UncoveredArg) {
Ted Kremenekab278de2010-01-28 23:39:18 +00006501 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00006502 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006503 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006504 S, inFunctionCall, Args[format_idx],
6505 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00006506 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00006507 return;
6508 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006509
Ted Kremenekab278de2010-01-28 23:39:18 +00006510 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006511 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00006512 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006513 // Account for cases where the string literal is truncated in a declaration.
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006514 const ConstantArrayType *T =
6515 S.Context.getAsConstantArrayType(FExpr->getType());
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006516 assert(T && "String literal not of constant array type!");
6517 size_t TypeSize = T->getSize().getZExtValue();
6518 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00006519 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006520
6521 // Emit a warning if the string literal is truncated and does not contain an
6522 // embedded null character.
6523 if (TypeSize <= StrRef.size() &&
6524 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
6525 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006526 S, inFunctionCall, Args[format_idx],
6527 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006528 FExpr->getLocStart(),
6529 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
6530 return;
6531 }
6532
Ted Kremenekab278de2010-01-28 23:39:18 +00006533 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00006534 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006535 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006536 S, inFunctionCall, Args[format_idx],
6537 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00006538 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00006539 return;
6540 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006541
6542 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
Mehdi Amini06d367c2016-10-24 20:39:34 +00006543 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
6544 Type == Sema::FST_OSTrace) {
6545 CheckPrintfHandler H(
6546 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
6547 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
6548 HasVAListArg, Args, format_idx, inFunctionCall, CallType,
6549 CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006550
Hans Wennborg23926bd2011-12-15 10:25:47 +00006551 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006552 S.getLangOpts(),
6553 S.Context.getTargetInfo(),
6554 Type == Sema::FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00006555 H.DoneProcessing();
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006556 } else if (Type == Sema::FST_Scanf) {
Mehdi Amini06d367c2016-10-24 20:39:34 +00006557 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
6558 numDataArgs, Str, HasVAListArg, Args, format_idx,
6559 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006560
Hans Wennborg23926bd2011-12-15 10:25:47 +00006561 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006562 S.getLangOpts(),
6563 S.Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00006564 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00006565 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00006566}
6567
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00006568bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
6569 // Str - The format string. NOTE: this is NOT null-terminated!
6570 StringRef StrRef = FExpr->getString();
6571 const char *Str = StrRef.data();
6572 // Account for cases where the string literal is truncated in a declaration.
6573 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
6574 assert(T && "String literal not of constant array type!");
6575 size_t TypeSize = T->getSize().getZExtValue();
6576 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
6577 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
6578 getLangOpts(),
6579 Context.getTargetInfo());
6580}
6581
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006582//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
6583
6584// Returns the related absolute value function that is larger, of 0 if one
6585// does not exist.
6586static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
6587 switch (AbsFunction) {
6588 default:
6589 return 0;
6590
6591 case Builtin::BI__builtin_abs:
6592 return Builtin::BI__builtin_labs;
6593 case Builtin::BI__builtin_labs:
6594 return Builtin::BI__builtin_llabs;
6595 case Builtin::BI__builtin_llabs:
6596 return 0;
6597
6598 case Builtin::BI__builtin_fabsf:
6599 return Builtin::BI__builtin_fabs;
6600 case Builtin::BI__builtin_fabs:
6601 return Builtin::BI__builtin_fabsl;
6602 case Builtin::BI__builtin_fabsl:
6603 return 0;
6604
6605 case Builtin::BI__builtin_cabsf:
6606 return Builtin::BI__builtin_cabs;
6607 case Builtin::BI__builtin_cabs:
6608 return Builtin::BI__builtin_cabsl;
6609 case Builtin::BI__builtin_cabsl:
6610 return 0;
6611
6612 case Builtin::BIabs:
6613 return Builtin::BIlabs;
6614 case Builtin::BIlabs:
6615 return Builtin::BIllabs;
6616 case Builtin::BIllabs:
6617 return 0;
6618
6619 case Builtin::BIfabsf:
6620 return Builtin::BIfabs;
6621 case Builtin::BIfabs:
6622 return Builtin::BIfabsl;
6623 case Builtin::BIfabsl:
6624 return 0;
6625
6626 case Builtin::BIcabsf:
6627 return Builtin::BIcabs;
6628 case Builtin::BIcabs:
6629 return Builtin::BIcabsl;
6630 case Builtin::BIcabsl:
6631 return 0;
6632 }
6633}
6634
6635// Returns the argument type of the absolute value function.
6636static QualType getAbsoluteValueArgumentType(ASTContext &Context,
6637 unsigned AbsType) {
6638 if (AbsType == 0)
6639 return QualType();
6640
6641 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
6642 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
6643 if (Error != ASTContext::GE_None)
6644 return QualType();
6645
6646 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
6647 if (!FT)
6648 return QualType();
6649
6650 if (FT->getNumParams() != 1)
6651 return QualType();
6652
6653 return FT->getParamType(0);
6654}
6655
6656// Returns the best absolute value function, or zero, based on type and
6657// current absolute value function.
6658static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
6659 unsigned AbsFunctionKind) {
6660 unsigned BestKind = 0;
6661 uint64_t ArgSize = Context.getTypeSize(ArgType);
6662 for (unsigned Kind = AbsFunctionKind; Kind != 0;
6663 Kind = getLargerAbsoluteValueFunction(Kind)) {
6664 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
6665 if (Context.getTypeSize(ParamType) >= ArgSize) {
6666 if (BestKind == 0)
6667 BestKind = Kind;
6668 else if (Context.hasSameType(ParamType, ArgType)) {
6669 BestKind = Kind;
6670 break;
6671 }
6672 }
6673 }
6674 return BestKind;
6675}
6676
6677enum AbsoluteValueKind {
6678 AVK_Integer,
6679 AVK_Floating,
6680 AVK_Complex
6681};
6682
6683static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
6684 if (T->isIntegralOrEnumerationType())
6685 return AVK_Integer;
6686 if (T->isRealFloatingType())
6687 return AVK_Floating;
6688 if (T->isAnyComplexType())
6689 return AVK_Complex;
6690
6691 llvm_unreachable("Type not integer, floating, or complex");
6692}
6693
6694// Changes the absolute value function to a different type. Preserves whether
6695// the function is a builtin.
6696static unsigned changeAbsFunction(unsigned AbsKind,
6697 AbsoluteValueKind ValueKind) {
6698 switch (ValueKind) {
6699 case AVK_Integer:
6700 switch (AbsKind) {
6701 default:
6702 return 0;
6703 case Builtin::BI__builtin_fabsf:
6704 case Builtin::BI__builtin_fabs:
6705 case Builtin::BI__builtin_fabsl:
6706 case Builtin::BI__builtin_cabsf:
6707 case Builtin::BI__builtin_cabs:
6708 case Builtin::BI__builtin_cabsl:
6709 return Builtin::BI__builtin_abs;
6710 case Builtin::BIfabsf:
6711 case Builtin::BIfabs:
6712 case Builtin::BIfabsl:
6713 case Builtin::BIcabsf:
6714 case Builtin::BIcabs:
6715 case Builtin::BIcabsl:
6716 return Builtin::BIabs;
6717 }
6718 case AVK_Floating:
6719 switch (AbsKind) {
6720 default:
6721 return 0;
6722 case Builtin::BI__builtin_abs:
6723 case Builtin::BI__builtin_labs:
6724 case Builtin::BI__builtin_llabs:
6725 case Builtin::BI__builtin_cabsf:
6726 case Builtin::BI__builtin_cabs:
6727 case Builtin::BI__builtin_cabsl:
6728 return Builtin::BI__builtin_fabsf;
6729 case Builtin::BIabs:
6730 case Builtin::BIlabs:
6731 case Builtin::BIllabs:
6732 case Builtin::BIcabsf:
6733 case Builtin::BIcabs:
6734 case Builtin::BIcabsl:
6735 return Builtin::BIfabsf;
6736 }
6737 case AVK_Complex:
6738 switch (AbsKind) {
6739 default:
6740 return 0;
6741 case Builtin::BI__builtin_abs:
6742 case Builtin::BI__builtin_labs:
6743 case Builtin::BI__builtin_llabs:
6744 case Builtin::BI__builtin_fabsf:
6745 case Builtin::BI__builtin_fabs:
6746 case Builtin::BI__builtin_fabsl:
6747 return Builtin::BI__builtin_cabsf;
6748 case Builtin::BIabs:
6749 case Builtin::BIlabs:
6750 case Builtin::BIllabs:
6751 case Builtin::BIfabsf:
6752 case Builtin::BIfabs:
6753 case Builtin::BIfabsl:
6754 return Builtin::BIcabsf;
6755 }
6756 }
6757 llvm_unreachable("Unable to convert function");
6758}
6759
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00006760static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006761 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
6762 if (!FnInfo)
6763 return 0;
6764
6765 switch (FDecl->getBuiltinID()) {
6766 default:
6767 return 0;
6768 case Builtin::BI__builtin_abs:
6769 case Builtin::BI__builtin_fabs:
6770 case Builtin::BI__builtin_fabsf:
6771 case Builtin::BI__builtin_fabsl:
6772 case Builtin::BI__builtin_labs:
6773 case Builtin::BI__builtin_llabs:
6774 case Builtin::BI__builtin_cabs:
6775 case Builtin::BI__builtin_cabsf:
6776 case Builtin::BI__builtin_cabsl:
6777 case Builtin::BIabs:
6778 case Builtin::BIlabs:
6779 case Builtin::BIllabs:
6780 case Builtin::BIfabs:
6781 case Builtin::BIfabsf:
6782 case Builtin::BIfabsl:
6783 case Builtin::BIcabs:
6784 case Builtin::BIcabsf:
6785 case Builtin::BIcabsl:
6786 return FDecl->getBuiltinID();
6787 }
6788 llvm_unreachable("Unknown Builtin type");
6789}
6790
6791// If the replacement is valid, emit a note with replacement function.
6792// Additionally, suggest including the proper header if not already included.
6793static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00006794 unsigned AbsKind, QualType ArgType) {
6795 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00006796 const char *HeaderName = nullptr;
Mehdi Amini7186a432016-10-11 19:04:24 +00006797 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00006798 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
6799 FunctionName = "std::abs";
6800 if (ArgType->isIntegralOrEnumerationType()) {
6801 HeaderName = "cstdlib";
6802 } else if (ArgType->isRealFloatingType()) {
6803 HeaderName = "cmath";
6804 } else {
6805 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006806 }
Richard Trieubeffb832014-04-15 23:47:53 +00006807
6808 // Lookup all std::abs
6809 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00006810 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00006811 R.suppressDiagnostics();
6812 S.LookupQualifiedName(R, Std);
6813
6814 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006815 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00006816 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
6817 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
6818 } else {
6819 FDecl = dyn_cast<FunctionDecl>(I);
6820 }
6821 if (!FDecl)
6822 continue;
6823
6824 // Found std::abs(), check that they are the right ones.
6825 if (FDecl->getNumParams() != 1)
6826 continue;
6827
6828 // Check that the parameter type can handle the argument.
6829 QualType ParamType = FDecl->getParamDecl(0)->getType();
6830 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
6831 S.Context.getTypeSize(ArgType) <=
6832 S.Context.getTypeSize(ParamType)) {
6833 // Found a function, don't need the header hint.
6834 EmitHeaderHint = false;
6835 break;
6836 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006837 }
Richard Trieubeffb832014-04-15 23:47:53 +00006838 }
6839 } else {
Eric Christopher02d5d862015-08-06 01:01:12 +00006840 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
Richard Trieubeffb832014-04-15 23:47:53 +00006841 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
6842
6843 if (HeaderName) {
6844 DeclarationName DN(&S.Context.Idents.get(FunctionName));
6845 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
6846 R.suppressDiagnostics();
6847 S.LookupName(R, S.getCurScope());
6848
6849 if (R.isSingleResult()) {
6850 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
6851 if (FD && FD->getBuiltinID() == AbsKind) {
6852 EmitHeaderHint = false;
6853 } else {
6854 return;
6855 }
6856 } else if (!R.empty()) {
6857 return;
6858 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006859 }
6860 }
6861
6862 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00006863 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006864
Richard Trieubeffb832014-04-15 23:47:53 +00006865 if (!HeaderName)
6866 return;
6867
6868 if (!EmitHeaderHint)
6869 return;
6870
Alp Toker5d96e0a2014-07-11 20:53:51 +00006871 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
6872 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00006873}
6874
Richard Trieua7f30b12016-12-06 01:42:28 +00006875template <std::size_t StrLen>
6876static bool IsStdFunction(const FunctionDecl *FDecl,
6877 const char (&Str)[StrLen]) {
Richard Trieubeffb832014-04-15 23:47:53 +00006878 if (!FDecl)
6879 return false;
Richard Trieua7f30b12016-12-06 01:42:28 +00006880 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
Richard Trieubeffb832014-04-15 23:47:53 +00006881 return false;
Richard Trieua7f30b12016-12-06 01:42:28 +00006882 if (!FDecl->isInStdNamespace())
Richard Trieubeffb832014-04-15 23:47:53 +00006883 return false;
6884
6885 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006886}
6887
6888// Warn when using the wrong abs() function.
6889void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
Richard Trieua7f30b12016-12-06 01:42:28 +00006890 const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006891 if (Call->getNumArgs() != 1)
6892 return;
6893
6894 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieua7f30b12016-12-06 01:42:28 +00006895 bool IsStdAbs = IsStdFunction(FDecl, "abs");
Richard Trieubeffb832014-04-15 23:47:53 +00006896 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006897 return;
6898
6899 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
6900 QualType ParamType = Call->getArg(0)->getType();
6901
Alp Toker5d96e0a2014-07-11 20:53:51 +00006902 // Unsigned types cannot be negative. Suggest removing the absolute value
6903 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006904 if (ArgType->isUnsignedIntegerType()) {
Mehdi Amini7186a432016-10-11 19:04:24 +00006905 const char *FunctionName =
Eric Christopher02d5d862015-08-06 01:01:12 +00006906 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006907 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
6908 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00006909 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006910 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
6911 return;
6912 }
6913
David Majnemer7f77eb92015-11-15 03:04:34 +00006914 // Taking the absolute value of a pointer is very suspicious, they probably
6915 // wanted to index into an array, dereference a pointer, call a function, etc.
6916 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
6917 unsigned DiagType = 0;
6918 if (ArgType->isFunctionType())
6919 DiagType = 1;
6920 else if (ArgType->isArrayType())
6921 DiagType = 2;
6922
6923 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
6924 return;
6925 }
6926
Richard Trieubeffb832014-04-15 23:47:53 +00006927 // std::abs has overloads which prevent most of the absolute value problems
6928 // from occurring.
6929 if (IsStdAbs)
6930 return;
6931
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006932 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
6933 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
6934
6935 // The argument and parameter are the same kind. Check if they are the right
6936 // size.
6937 if (ArgValueKind == ParamValueKind) {
6938 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
6939 return;
6940
6941 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
6942 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
6943 << FDecl << ArgType << ParamType;
6944
6945 if (NewAbsKind == 0)
6946 return;
6947
6948 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00006949 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006950 return;
6951 }
6952
6953 // ArgValueKind != ParamValueKind
6954 // The wrong type of absolute value function was used. Attempt to find the
6955 // proper one.
6956 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
6957 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
6958 if (NewAbsKind == 0)
6959 return;
6960
6961 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
6962 << FDecl << ParamValueKind << ArgValueKind;
6963
6964 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00006965 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006966}
6967
Richard Trieu67c00712016-12-05 23:41:46 +00006968//===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
Richard Trieua7f30b12016-12-06 01:42:28 +00006969void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
6970 const FunctionDecl *FDecl) {
Richard Trieu67c00712016-12-05 23:41:46 +00006971 if (!Call || !FDecl) return;
6972
6973 // Ignore template specializations and macros.
Richard Smith51ec0cf2017-02-21 01:17:38 +00006974 if (inTemplateInstantiation()) return;
Richard Trieu67c00712016-12-05 23:41:46 +00006975 if (Call->getExprLoc().isMacroID()) return;
6976
6977 // Only care about the one template argument, two function parameter std::max
6978 if (Call->getNumArgs() != 2) return;
Richard Trieua7f30b12016-12-06 01:42:28 +00006979 if (!IsStdFunction(FDecl, "max")) return;
Richard Trieu67c00712016-12-05 23:41:46 +00006980 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
6981 if (!ArgList) return;
6982 if (ArgList->size() != 1) return;
6983
6984 // Check that template type argument is unsigned integer.
6985 const auto& TA = ArgList->get(0);
6986 if (TA.getKind() != TemplateArgument::Type) return;
6987 QualType ArgType = TA.getAsType();
6988 if (!ArgType->isUnsignedIntegerType()) return;
6989
6990 // See if either argument is a literal zero.
6991 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
6992 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
6993 if (!MTE) return false;
6994 const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
6995 if (!Num) return false;
6996 if (Num->getValue() != 0) return false;
6997 return true;
6998 };
6999
7000 const Expr *FirstArg = Call->getArg(0);
7001 const Expr *SecondArg = Call->getArg(1);
7002 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
7003 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
7004
7005 // Only warn when exactly one argument is zero.
7006 if (IsFirstArgZero == IsSecondArgZero) return;
7007
7008 SourceRange FirstRange = FirstArg->getSourceRange();
7009 SourceRange SecondRange = SecondArg->getSourceRange();
7010
7011 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
7012
7013 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
7014 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
7015
7016 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
7017 SourceRange RemovalRange;
7018 if (IsFirstArgZero) {
7019 RemovalRange = SourceRange(FirstRange.getBegin(),
7020 SecondRange.getBegin().getLocWithOffset(-1));
7021 } else {
7022 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
7023 SecondRange.getEnd());
7024 }
7025
7026 Diag(Call->getExprLoc(), diag::note_remove_max_call)
7027 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
7028 << FixItHint::CreateRemoval(RemovalRange);
7029}
7030
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007031//===--- CHECK: Standard memory functions ---------------------------------===//
7032
Nico Weber0e6daef2013-12-26 23:38:39 +00007033/// \brief Takes the expression passed to the size_t parameter of functions
7034/// such as memcmp, strncat, etc and warns if it's a comparison.
7035///
7036/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
7037static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
7038 IdentifierInfo *FnName,
7039 SourceLocation FnLoc,
7040 SourceLocation RParenLoc) {
7041 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
7042 if (!Size)
7043 return false;
7044
7045 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
7046 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
7047 return false;
7048
Nico Weber0e6daef2013-12-26 23:38:39 +00007049 SourceRange SizeRange = Size->getSourceRange();
7050 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
7051 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00007052 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00007053 << FnName << FixItHint::CreateInsertion(
7054 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00007055 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00007056 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00007057 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00007058 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
7059 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00007060
7061 return true;
7062}
7063
Reid Kleckner5fb5b122014-06-27 23:58:21 +00007064/// \brief Determine whether the given type is or contains a dynamic class type
7065/// (e.g., whether it has a vtable).
7066static const CXXRecordDecl *getContainedDynamicClass(QualType T,
7067 bool &IsContained) {
7068 // Look through array types while ignoring qualifiers.
7069 const Type *Ty = T->getBaseElementTypeUnsafe();
7070 IsContained = false;
7071
7072 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
7073 RD = RD ? RD->getDefinition() : nullptr;
Richard Trieu1c7237a2016-03-31 04:18:07 +00007074 if (!RD || RD->isInvalidDecl())
Reid Kleckner5fb5b122014-06-27 23:58:21 +00007075 return nullptr;
7076
7077 if (RD->isDynamicClass())
7078 return RD;
7079
7080 // Check all the fields. If any bases were dynamic, the class is dynamic.
7081 // It's impossible for a class to transitively contain itself by value, so
7082 // infinite recursion is impossible.
7083 for (auto *FD : RD->fields()) {
7084 bool SubContained;
7085 if (const CXXRecordDecl *ContainedRD =
7086 getContainedDynamicClass(FD->getType(), SubContained)) {
7087 IsContained = true;
7088 return ContainedRD;
7089 }
7090 }
7091
7092 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00007093}
7094
Chandler Carruth889ed862011-06-21 23:04:20 +00007095/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007096/// otherwise returns NULL.
Nico Weberc44b35e2015-03-21 17:37:46 +00007097static const Expr *getSizeOfExprArg(const Expr *E) {
Nico Weberc5e73862011-06-14 16:14:58 +00007098 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007099 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
7100 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
7101 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00007102
Craig Topperc3ec1492014-05-26 06:22:03 +00007103 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007104}
7105
Chandler Carruth889ed862011-06-21 23:04:20 +00007106/// \brief If E is a sizeof expression, returns its argument type.
Nico Weberc44b35e2015-03-21 17:37:46 +00007107static QualType getSizeOfArgType(const Expr *E) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007108 if (const UnaryExprOrTypeTraitExpr *SizeOf =
7109 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
7110 if (SizeOf->getKind() == clang::UETT_SizeOf)
7111 return SizeOf->getTypeOfArgument();
7112
7113 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00007114}
7115
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007116/// \brief Check for dangerous or invalid arguments to memset().
7117///
Chandler Carruthac687262011-06-03 06:23:57 +00007118/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007119/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
7120/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007121///
7122/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007123void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00007124 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007125 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00007126 assert(BId != 0);
7127
Ted Kremenekb5fabb22011-04-28 01:38:02 +00007128 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00007129 // we have enough arguments, and if not, abort further checking.
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007130 unsigned ExpectedNumArgs =
7131 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00007132 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00007133 return;
7134
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007135 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
Anna Zaks22122702012-01-17 00:37:07 +00007136 BId == Builtin::BIstrndup ? 1 : 2);
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007137 unsigned LenArg =
7138 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00007139 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007140
Nico Weber0e6daef2013-12-26 23:38:39 +00007141 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
7142 Call->getLocStart(), Call->getRParenLoc()))
7143 return;
7144
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007145 // We have special checking when the length is a sizeof expression.
7146 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
7147 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
7148 llvm::FoldingSetNodeID SizeOfArgID;
7149
Bruno Cardoso Lopesc73e4c32016-08-11 18:33:15 +00007150 // Although widely used, 'bzero' is not a standard function. Be more strict
7151 // with the argument types before allowing diagnostics and only allow the
7152 // form bzero(ptr, sizeof(...)).
7153 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7154 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
7155 return;
7156
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007157 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
7158 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00007159 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007160
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007161 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00007162 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007163 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00007164 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00007165
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007166 // Never warn about void type pointers. This can be used to suppress
7167 // false positives.
7168 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007169 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007170
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007171 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
7172 // actually comparing the expressions for equality. Because computing the
7173 // expression IDs can be expensive, we only do this if the diagnostic is
7174 // enabled.
7175 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007176 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
7177 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007178 // We only compute IDs for expressions if the warning is enabled, and
7179 // cache the sizeof arg's ID.
7180 if (SizeOfArgID == llvm::FoldingSetNodeID())
7181 SizeOfArg->Profile(SizeOfArgID, Context, true);
7182 llvm::FoldingSetNodeID DestID;
7183 Dest->Profile(DestID, Context, true);
7184 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00007185 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
7186 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007187 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00007188 StringRef ReadableName = FnName->getName();
7189
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007190 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00007191 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007192 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00007193 if (!PointeeTy->isIncompleteType() &&
7194 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007195 ActionIdx = 2; // If the pointee's size is sizeof(char),
7196 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00007197
7198 // If the function is defined as a builtin macro, do not show macro
7199 // expansion.
7200 SourceLocation SL = SizeOfArg->getExprLoc();
7201 SourceRange DSR = Dest->getSourceRange();
7202 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00007203 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00007204
7205 if (SM.isMacroArgExpansion(SL)) {
7206 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
7207 SL = SM.getSpellingLoc(SL);
7208 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
7209 SM.getSpellingLoc(DSR.getEnd()));
7210 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
7211 SM.getSpellingLoc(SSR.getEnd()));
7212 }
7213
Anna Zaksd08d9152012-05-30 23:14:52 +00007214 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007215 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00007216 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00007217 << PointeeTy
7218 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00007219 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00007220 << SSR);
7221 DiagRuntimeBehavior(SL, SizeOfArg,
7222 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
7223 << ActionIdx
7224 << SSR);
7225
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007226 break;
7227 }
7228 }
7229
7230 // Also check for cases where the sizeof argument is the exact same
7231 // type as the memory argument, and where it points to a user-defined
7232 // record type.
7233 if (SizeOfArgTy != QualType()) {
7234 if (PointeeTy->isRecordType() &&
7235 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
7236 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
7237 PDiag(diag::warn_sizeof_pointer_type_memaccess)
7238 << FnName << SizeOfArgTy << ArgIdx
7239 << PointeeTy << Dest->getSourceRange()
7240 << LenExpr->getSourceRange());
7241 break;
7242 }
Nico Weberc5e73862011-06-14 16:14:58 +00007243 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00007244 } else if (DestTy->isArrayType()) {
7245 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00007246 }
Nico Weberc5e73862011-06-14 16:14:58 +00007247
Nico Weberc44b35e2015-03-21 17:37:46 +00007248 if (PointeeTy == QualType())
7249 continue;
Anna Zaks22122702012-01-17 00:37:07 +00007250
Nico Weberc44b35e2015-03-21 17:37:46 +00007251 // Always complain about dynamic classes.
7252 bool IsContained;
7253 if (const CXXRecordDecl *ContainedRD =
7254 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00007255
Nico Weberc44b35e2015-03-21 17:37:46 +00007256 unsigned OperationType = 0;
7257 // "overwritten" if we're warning about the destination for any call
7258 // but memcmp; otherwise a verb appropriate to the call.
7259 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
7260 if (BId == Builtin::BImemcpy)
7261 OperationType = 1;
7262 else if(BId == Builtin::BImemmove)
7263 OperationType = 2;
7264 else if (BId == Builtin::BImemcmp)
7265 OperationType = 3;
7266 }
7267
John McCall31168b02011-06-15 23:02:42 +00007268 DiagRuntimeBehavior(
7269 Dest->getExprLoc(), Dest,
Nico Weberc44b35e2015-03-21 17:37:46 +00007270 PDiag(diag::warn_dyn_class_memaccess)
7271 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
7272 << FnName << IsContained << ContainedRD << OperationType
7273 << Call->getCallee()->getSourceRange());
7274 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
7275 BId != Builtin::BImemset)
7276 DiagRuntimeBehavior(
7277 Dest->getExprLoc(), Dest,
7278 PDiag(diag::warn_arc_object_memaccess)
7279 << ArgIdx << FnName << PointeeTy
7280 << Call->getCallee()->getSourceRange());
7281 else
7282 continue;
7283
7284 DiagRuntimeBehavior(
7285 Dest->getExprLoc(), Dest,
7286 PDiag(diag::note_bad_memaccess_silence)
7287 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
7288 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007289 }
7290}
7291
Ted Kremenek6865f772011-08-18 20:55:45 +00007292// A little helper routine: ignore addition and subtraction of integer literals.
7293// This intentionally does not ignore all integer constant expressions because
7294// we don't want to remove sizeof().
7295static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
7296 Ex = Ex->IgnoreParenCasts();
7297
7298 for (;;) {
7299 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
7300 if (!BO || !BO->isAdditiveOp())
7301 break;
7302
7303 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
7304 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
7305
7306 if (isa<IntegerLiteral>(RHS))
7307 Ex = LHS;
7308 else if (isa<IntegerLiteral>(LHS))
7309 Ex = RHS;
7310 else
7311 break;
7312 }
7313
7314 return Ex;
7315}
7316
Anna Zaks13b08572012-08-08 21:42:23 +00007317static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
7318 ASTContext &Context) {
7319 // Only handle constant-sized or VLAs, but not flexible members.
7320 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
7321 // Only issue the FIXIT for arrays of size > 1.
7322 if (CAT->getSize().getSExtValue() <= 1)
7323 return false;
7324 } else if (!Ty->isVariableArrayType()) {
7325 return false;
7326 }
7327 return true;
7328}
7329
Ted Kremenek6865f772011-08-18 20:55:45 +00007330// Warn if the user has made the 'size' argument to strlcpy or strlcat
7331// be the size of the source, instead of the destination.
7332void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
7333 IdentifierInfo *FnName) {
7334
7335 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00007336 unsigned NumArgs = Call->getNumArgs();
7337 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00007338 return;
7339
7340 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
7341 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00007342 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00007343
7344 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
7345 Call->getLocStart(), Call->getRParenLoc()))
7346 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00007347
7348 // Look for 'strlcpy(dst, x, sizeof(x))'
7349 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
7350 CompareWithSrc = Ex;
7351 else {
7352 // Look for 'strlcpy(dst, x, strlen(x))'
7353 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00007354 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
7355 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00007356 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
7357 }
7358 }
7359
7360 if (!CompareWithSrc)
7361 return;
7362
7363 // Determine if the argument to sizeof/strlen is equal to the source
7364 // argument. In principle there's all kinds of things you could do
7365 // here, for instance creating an == expression and evaluating it with
7366 // EvaluateAsBooleanCondition, but this uses a more direct technique:
7367 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
7368 if (!SrcArgDRE)
7369 return;
7370
7371 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
7372 if (!CompareWithSrcDRE ||
7373 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
7374 return;
7375
7376 const Expr *OriginalSizeArg = Call->getArg(2);
7377 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
7378 << OriginalSizeArg->getSourceRange() << FnName;
7379
7380 // Output a FIXIT hint if the destination is an array (rather than a
7381 // pointer to an array). This could be enhanced to handle some
7382 // pointers if we know the actual size, like if DstArg is 'array+2'
7383 // we could say 'sizeof(array)-2'.
7384 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00007385 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00007386 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00007387
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00007388 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00007389 llvm::raw_svector_ostream OS(sizeString);
7390 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007391 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00007392 OS << ")";
7393
7394 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
7395 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
7396 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00007397}
7398
Anna Zaks314cd092012-02-01 19:08:57 +00007399/// Check if two expressions refer to the same declaration.
7400static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
7401 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
7402 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
7403 return D1->getDecl() == D2->getDecl();
7404 return false;
7405}
7406
7407static const Expr *getStrlenExprArg(const Expr *E) {
7408 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
7409 const FunctionDecl *FD = CE->getDirectCallee();
7410 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00007411 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00007412 return CE->getArg(0)->IgnoreParenCasts();
7413 }
Craig Topperc3ec1492014-05-26 06:22:03 +00007414 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00007415}
7416
7417// Warn on anti-patterns as the 'size' argument to strncat.
7418// The correct size argument should look like following:
7419// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
7420void Sema::CheckStrncatArguments(const CallExpr *CE,
7421 IdentifierInfo *FnName) {
7422 // Don't crash if the user has the wrong number of arguments.
7423 if (CE->getNumArgs() < 3)
7424 return;
7425 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
7426 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
7427 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
7428
Nico Weber0e6daef2013-12-26 23:38:39 +00007429 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
7430 CE->getRParenLoc()))
7431 return;
7432
Anna Zaks314cd092012-02-01 19:08:57 +00007433 // Identify common expressions, which are wrongly used as the size argument
7434 // to strncat and may lead to buffer overflows.
7435 unsigned PatternType = 0;
7436 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
7437 // - sizeof(dst)
7438 if (referToTheSameDecl(SizeOfArg, DstArg))
7439 PatternType = 1;
7440 // - sizeof(src)
7441 else if (referToTheSameDecl(SizeOfArg, SrcArg))
7442 PatternType = 2;
7443 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
7444 if (BE->getOpcode() == BO_Sub) {
7445 const Expr *L = BE->getLHS()->IgnoreParenCasts();
7446 const Expr *R = BE->getRHS()->IgnoreParenCasts();
7447 // - sizeof(dst) - strlen(dst)
7448 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
7449 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
7450 PatternType = 1;
7451 // - sizeof(src) - (anything)
7452 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
7453 PatternType = 2;
7454 }
7455 }
7456
7457 if (PatternType == 0)
7458 return;
7459
Anna Zaks5069aa32012-02-03 01:27:37 +00007460 // Generate the diagnostic.
7461 SourceLocation SL = LenArg->getLocStart();
7462 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00007463 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00007464
7465 // If the function is defined as a builtin macro, do not show macro expansion.
7466 if (SM.isMacroArgExpansion(SL)) {
7467 SL = SM.getSpellingLoc(SL);
7468 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
7469 SM.getSpellingLoc(SR.getEnd()));
7470 }
7471
Anna Zaks13b08572012-08-08 21:42:23 +00007472 // Check if the destination is an array (rather than a pointer to an array).
7473 QualType DstTy = DstArg->getType();
7474 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
7475 Context);
7476 if (!isKnownSizeArray) {
7477 if (PatternType == 1)
7478 Diag(SL, diag::warn_strncat_wrong_size) << SR;
7479 else
7480 Diag(SL, diag::warn_strncat_src_size) << SR;
7481 return;
7482 }
7483
Anna Zaks314cd092012-02-01 19:08:57 +00007484 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00007485 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00007486 else
Anna Zaks5069aa32012-02-03 01:27:37 +00007487 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00007488
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00007489 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00007490 llvm::raw_svector_ostream OS(sizeString);
7491 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007492 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00007493 OS << ") - ";
7494 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007495 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00007496 OS << ") - 1";
7497
Anna Zaks5069aa32012-02-03 01:27:37 +00007498 Diag(SL, diag::note_strncat_wrong_size)
7499 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00007500}
7501
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007502//===--- CHECK: Return Address of Stack Variable --------------------------===//
7503
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007504static const Expr *EvalVal(const Expr *E,
7505 SmallVectorImpl<const DeclRefExpr *> &refVars,
7506 const Decl *ParentDecl);
7507static const Expr *EvalAddr(const Expr *E,
7508 SmallVectorImpl<const DeclRefExpr *> &refVars,
7509 const Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007510
7511/// CheckReturnStackAddr - Check if a return statement returns the address
7512/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007513static void
7514CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
7515 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00007516
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007517 const Expr *stackE = nullptr;
7518 SmallVector<const DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007519
7520 // Perform checking for returned stack addresses, local blocks,
7521 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00007522 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007523 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007524 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00007525 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007526 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007527 }
7528
Craig Topperc3ec1492014-05-26 06:22:03 +00007529 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007530 return; // Nothing suspicious was found.
7531
Simon Pilgrim750bde62017-03-31 11:00:53 +00007532 // Parameters are initialized in the calling scope, so taking the address
Richard Trieu81b6c562016-08-05 23:24:47 +00007533 // of a parameter reference doesn't need a warning.
7534 for (auto *DRE : refVars)
7535 if (isa<ParmVarDecl>(DRE->getDecl()))
7536 return;
7537
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007538 SourceLocation diagLoc;
7539 SourceRange diagRange;
7540 if (refVars.empty()) {
7541 diagLoc = stackE->getLocStart();
7542 diagRange = stackE->getSourceRange();
7543 } else {
7544 // We followed through a reference variable. 'stackE' contains the
7545 // problematic expression but we will warn at the return statement pointing
7546 // at the reference variable. We will later display the "trail" of
7547 // reference variables using notes.
7548 diagLoc = refVars[0]->getLocStart();
7549 diagRange = refVars[0]->getSourceRange();
7550 }
7551
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007552 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
7553 // address of local var
Craig Topperda7b27f2015-11-17 05:40:09 +00007554 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007555 << DR->getDecl()->getDeclName() << diagRange;
7556 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007557 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007558 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007559 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007560 } else { // local temporary.
Richard Trieu81b6c562016-08-05 23:24:47 +00007561 // If there is an LValue->RValue conversion, then the value of the
7562 // reference type is used, not the reference.
7563 if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
7564 if (ICE->getCastKind() == CK_LValueToRValue) {
7565 return;
7566 }
7567 }
Craig Topperda7b27f2015-11-17 05:40:09 +00007568 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
7569 << lhsType->isReferenceType() << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007570 }
7571
7572 // Display the "trail" of reference variables that we followed until we
7573 // found the problematic expression using notes.
7574 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007575 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007576 // If this var binds to another reference var, show the range of the next
7577 // var, otherwise the var binds to the problematic expression, in which case
7578 // show the range of the expression.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007579 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
7580 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007581 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
7582 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007583 }
7584}
7585
7586/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
7587/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007588/// to a location on the stack, a local block, an address of a label, or a
7589/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007590/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007591/// encounter a subexpression that (1) clearly does not lead to one of the
7592/// above problematic expressions (2) is something we cannot determine leads to
7593/// a problematic expression based on such local checking.
7594///
7595/// Both EvalAddr and EvalVal follow through reference variables to evaluate
7596/// the expression that they point to. Such variables are added to the
7597/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007598///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00007599/// EvalAddr processes expressions that are pointers that are used as
7600/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007601/// At the base case of the recursion is a check for the above problematic
7602/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007603///
7604/// This implementation handles:
7605///
7606/// * pointer-to-pointer casts
7607/// * implicit conversions from array references to pointers
7608/// * taking the address of fields
7609/// * arbitrary interplay between "&" and "*" operators
7610/// * pointer arithmetic from an address of a stack variable
7611/// * taking the address of an array element where the array is on the stack
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007612static const Expr *EvalAddr(const Expr *E,
7613 SmallVectorImpl<const DeclRefExpr *> &refVars,
7614 const Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007615 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00007616 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007617
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007618 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00007619 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00007620 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00007621 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00007622 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00007623
Peter Collingbourne91147592011-04-15 00:35:48 +00007624 E = E->IgnoreParens();
7625
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007626 // Our "symbolic interpreter" is just a dispatch off the currently
7627 // viewed AST node. We then recursively traverse the AST by calling
7628 // EvalAddr and EvalVal appropriately.
7629 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007630 case Stmt::DeclRefExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007631 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007632
Richard Smith40f08eb2014-01-30 22:05:38 +00007633 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00007634 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00007635 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00007636
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007637 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007638 // If this is a reference variable, follow through to the expression that
7639 // it points to.
7640 if (V->hasLocalStorage() &&
7641 V->getType()->isReferenceType() && V->hasInit()) {
7642 // Add the reference variable to the "trail".
7643 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007644 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007645 }
7646
Craig Topperc3ec1492014-05-26 06:22:03 +00007647 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007648 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007649
Chris Lattner934edb22007-12-28 05:31:15 +00007650 case Stmt::UnaryOperatorClass: {
7651 // The only unary operator that make sense to handle here
7652 // is AddrOf. All others don't make sense as pointers.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007653 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007654
John McCalle3027922010-08-25 11:45:40 +00007655 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007656 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007657 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007658 }
Mike Stump11289f42009-09-09 15:08:12 +00007659
Chris Lattner934edb22007-12-28 05:31:15 +00007660 case Stmt::BinaryOperatorClass: {
7661 // Handle pointer arithmetic. All other binary operators are not valid
7662 // in this context.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007663 const BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00007664 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00007665
John McCalle3027922010-08-25 11:45:40 +00007666 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00007667 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00007668
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007669 const Expr *Base = B->getLHS();
Chris Lattner934edb22007-12-28 05:31:15 +00007670
7671 // Determine which argument is the real pointer base. It could be
7672 // the RHS argument instead of the LHS.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007673 if (!Base->getType()->isPointerType())
7674 Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00007675
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007676 assert(Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007677 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00007678 }
Steve Naroff2752a172008-09-10 19:17:48 +00007679
Chris Lattner934edb22007-12-28 05:31:15 +00007680 // For conditional operators we need to see if either the LHS or RHS are
7681 // valid DeclRefExpr*s. If one of them is valid, we return it.
7682 case Stmt::ConditionalOperatorClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007683 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007684
Chris Lattner934edb22007-12-28 05:31:15 +00007685 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007686 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007687 if (const Expr *LHSExpr = C->getLHS()) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007688 // In C++, we can have a throw-expression, which has 'void' type.
7689 if (!LHSExpr->getType()->isVoidType())
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007690 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007691 return LHS;
7692 }
Chris Lattner934edb22007-12-28 05:31:15 +00007693
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007694 // In C++, we can have a throw-expression, which has 'void' type.
7695 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00007696 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007697
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007698 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00007699 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007700
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007701 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00007702 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007703 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00007704 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007705
7706 case Stmt::AddrLabelExprClass:
7707 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00007708
John McCall28fc7092011-11-10 05:35:25 +00007709 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007710 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7711 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00007712
Ted Kremenekc3b4c522008-08-07 00:49:01 +00007713 // For casts, we need to handle conversions from arrays to
7714 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00007715 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00007716 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00007717 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00007718 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00007719 case Stmt::CXXStaticCastExprClass:
7720 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00007721 case Stmt::CXXConstCastExprClass:
7722 case Stmt::CXXReinterpretCastExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007723 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Eli Friedman8195ad72012-02-23 23:04:32 +00007724 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00007725 case CK_LValueToRValue:
7726 case CK_NoOp:
7727 case CK_BaseToDerived:
7728 case CK_DerivedToBase:
7729 case CK_UncheckedDerivedToBase:
7730 case CK_Dynamic:
7731 case CK_CPointerToObjCPointerCast:
7732 case CK_BlockPointerToObjCPointerCast:
7733 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007734 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00007735
7736 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007737 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00007738
Richard Trieudadefde2014-07-02 04:39:38 +00007739 case CK_BitCast:
7740 if (SubExpr->getType()->isAnyPointerType() ||
7741 SubExpr->getType()->isBlockPointerType() ||
7742 SubExpr->getType()->isObjCQualifiedIdType())
7743 return EvalAddr(SubExpr, refVars, ParentDecl);
7744 else
7745 return nullptr;
7746
Eli Friedman8195ad72012-02-23 23:04:32 +00007747 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00007748 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00007749 }
Chris Lattner934edb22007-12-28 05:31:15 +00007750 }
Mike Stump11289f42009-09-09 15:08:12 +00007751
Douglas Gregorfe314812011-06-21 17:03:29 +00007752 case Stmt::MaterializeTemporaryExprClass:
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007753 if (const Expr *Result =
7754 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7755 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00007756 return Result;
Douglas Gregorfe314812011-06-21 17:03:29 +00007757 return E;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007758
Chris Lattner934edb22007-12-28 05:31:15 +00007759 // Everything else: we simply don't reason about them.
7760 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00007761 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00007762 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007763}
Mike Stump11289f42009-09-09 15:08:12 +00007764
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007765/// EvalVal - This function is complements EvalAddr in the mutual recursion.
7766/// See the comments for EvalAddr for more details.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007767static const Expr *EvalVal(const Expr *E,
7768 SmallVectorImpl<const DeclRefExpr *> &refVars,
7769 const Decl *ParentDecl) {
7770 do {
7771 // We should only be called for evaluating non-pointer expressions, or
7772 // expressions with a pointer type that are not used as references but
7773 // instead
7774 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00007775
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007776 // Our "symbolic interpreter" is just a dispatch off the currently
7777 // viewed AST node. We then recursively traverse the AST by calling
7778 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00007779
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007780 E = E->IgnoreParens();
7781 switch (E->getStmtClass()) {
7782 case Stmt::ImplicitCastExprClass: {
7783 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
7784 if (IE->getValueKind() == VK_LValue) {
7785 E = IE->getSubExpr();
7786 continue;
7787 }
Craig Topperc3ec1492014-05-26 06:22:03 +00007788 return nullptr;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007789 }
Richard Smith40f08eb2014-01-30 22:05:38 +00007790
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007791 case Stmt::ExprWithCleanupsClass:
7792 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7793 ParentDecl);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007794
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007795 case Stmt::DeclRefExprClass: {
7796 // When we hit a DeclRefExpr we are looking at code that refers to a
7797 // variable's name. If it's not a reference variable we check if it has
7798 // local storage within the function, and if so, return the expression.
7799 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7800
7801 // If we leave the immediate function, the lifetime isn't about to end.
7802 if (DR->refersToEnclosingVariableOrCapture())
7803 return nullptr;
7804
7805 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
7806 // Check if it refers to itself, e.g. "int& i = i;".
7807 if (V == ParentDecl)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007808 return DR;
7809
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007810 if (V->hasLocalStorage()) {
7811 if (!V->getType()->isReferenceType())
7812 return DR;
7813
7814 // Reference variable, follow through to the expression that
7815 // it points to.
7816 if (V->hasInit()) {
7817 // Add the reference variable to the "trail".
7818 refVars.push_back(DR);
7819 return EvalVal(V->getInit(), refVars, V);
7820 }
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007821 }
7822 }
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007823
7824 return nullptr;
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007825 }
Mike Stump11289f42009-09-09 15:08:12 +00007826
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007827 case Stmt::UnaryOperatorClass: {
7828 // The only unary operator that make sense to handle here
7829 // is Deref. All others don't resolve to a "name." This includes
7830 // handling all sorts of rvalues passed to a unary operator.
7831 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007832
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007833 if (U->getOpcode() == UO_Deref)
7834 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Mike Stump11289f42009-09-09 15:08:12 +00007835
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007836 return nullptr;
7837 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007838
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007839 case Stmt::ArraySubscriptExprClass: {
7840 // Array subscripts are potential references to data on the stack. We
7841 // retrieve the DeclRefExpr* for the array variable if it indeed
7842 // has local storage.
Saleem Abdulrasoolcfd45532016-02-15 01:51:24 +00007843 const auto *ASE = cast<ArraySubscriptExpr>(E);
7844 if (ASE->isTypeDependent())
7845 return nullptr;
7846 return EvalAddr(ASE->getBase(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007847 }
Mike Stump11289f42009-09-09 15:08:12 +00007848
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007849 case Stmt::OMPArraySectionExprClass: {
7850 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
7851 ParentDecl);
7852 }
Mike Stump11289f42009-09-09 15:08:12 +00007853
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007854 case Stmt::ConditionalOperatorClass: {
7855 // For conditional operators we need to see if either the LHS or RHS are
7856 // non-NULL Expr's. If one is non-NULL, we return it.
7857 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Alexey Bataev1a3320e2015-08-25 14:24:04 +00007858
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007859 // Handle the GNU extension for missing LHS.
7860 if (const Expr *LHSExpr = C->getLHS()) {
7861 // In C++, we can have a throw-expression, which has 'void' type.
7862 if (!LHSExpr->getType()->isVoidType())
7863 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
7864 return LHS;
7865 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007866
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007867 // In C++, we can have a throw-expression, which has 'void' type.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007868 if (C->getRHS()->getType()->isVoidType())
7869 return nullptr;
7870
7871 return EvalVal(C->getRHS(), refVars, ParentDecl);
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007872 }
7873
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007874 // Accesses to members are potential references to data on the stack.
7875 case Stmt::MemberExprClass: {
7876 const MemberExpr *M = cast<MemberExpr>(E);
Anders Carlsson801c5c72007-11-30 19:04:31 +00007877
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007878 // Check for indirect access. We only want direct field accesses.
7879 if (M->isArrow())
7880 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00007881
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007882 // Check whether the member type is itself a reference, in which case
7883 // we're not going to refer to the member, but to what the member refers
7884 // to.
7885 if (M->getMemberDecl()->getType()->isReferenceType())
7886 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00007887
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007888 return EvalVal(M->getBase(), refVars, ParentDecl);
7889 }
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00007890
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007891 case Stmt::MaterializeTemporaryExprClass:
7892 if (const Expr *Result =
7893 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7894 refVars, ParentDecl))
7895 return Result;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007896 return E;
7897
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007898 default:
7899 // Check that we don't return or take the address of a reference to a
7900 // temporary. This is only useful in C++.
7901 if (!E->isTypeDependent() && E->isRValue())
7902 return E;
7903
7904 // Everything else: we simply don't reason about them.
7905 return nullptr;
7906 }
7907 } while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007908}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007909
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007910void
7911Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
7912 SourceLocation ReturnLoc,
7913 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00007914 const AttrVec *Attrs,
7915 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007916 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
7917
7918 // Check if the return value is null but should not be.
Douglas Gregorb4866e82015-06-19 18:13:19 +00007919 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
7920 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
Benjamin Kramerae852a62014-02-23 14:34:50 +00007921 CheckNonNullExpr(*this, RetValExp))
7922 Diag(ReturnLoc, diag::warn_null_ret)
7923 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00007924
7925 // C++11 [basic.stc.dynamic.allocation]p4:
7926 // If an allocation function declared with a non-throwing
7927 // exception-specification fails to allocate storage, it shall return
7928 // a null pointer. Any other allocation function that fails to allocate
7929 // storage shall indicate failure only by throwing an exception [...]
7930 if (FD) {
7931 OverloadedOperatorKind Op = FD->getOverloadedOperator();
7932 if (Op == OO_New || Op == OO_Array_New) {
7933 const FunctionProtoType *Proto
7934 = FD->getType()->castAs<FunctionProtoType>();
7935 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
7936 CheckNonNullExpr(*this, RetValExp))
7937 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
7938 << FD << getLangOpts().CPlusPlus11;
7939 }
7940 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007941}
7942
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007943//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
7944
7945/// Check for comparisons of floating point operands using != and ==.
7946/// Issue a warning if these are no self-comparisons, as they are not likely
7947/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00007948void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00007949 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
7950 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007951
7952 // Special case: check for x == x (which is OK).
7953 // Do not emit warnings for such cases.
7954 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
7955 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
7956 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00007957 return;
Mike Stump11289f42009-09-09 15:08:12 +00007958
Ted Kremenekeda40e22007-11-29 00:59:04 +00007959 // Special case: check for comparisons against literals that can be exactly
7960 // represented by APFloat. In such cases, do not emit a warning. This
7961 // is a heuristic: often comparison against such literals are used to
7962 // detect if a value in a variable has not changed. This clearly can
7963 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00007964 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
7965 if (FLL->isExact())
7966 return;
7967 } else
7968 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
7969 if (FLR->isExact())
7970 return;
Mike Stump11289f42009-09-09 15:08:12 +00007971
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007972 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00007973 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00007974 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00007975 return;
Mike Stump11289f42009-09-09 15:08:12 +00007976
David Blaikie1f4ff152012-07-16 20:47:22 +00007977 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00007978 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00007979 return;
Mike Stump11289f42009-09-09 15:08:12 +00007980
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007981 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00007982 Diag(Loc, diag::warn_floatingpoint_eq)
7983 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007984}
John McCallca01b222010-01-04 23:21:16 +00007985
John McCall70aa5392010-01-06 05:24:50 +00007986//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
7987//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00007988
John McCall70aa5392010-01-06 05:24:50 +00007989namespace {
John McCallca01b222010-01-04 23:21:16 +00007990
John McCall70aa5392010-01-06 05:24:50 +00007991/// Structure recording the 'active' range of an integer-valued
7992/// expression.
7993struct IntRange {
7994 /// The number of bits active in the int.
7995 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00007996
John McCall70aa5392010-01-06 05:24:50 +00007997 /// True if the int is known not to have negative values.
7998 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00007999
John McCall70aa5392010-01-06 05:24:50 +00008000 IntRange(unsigned Width, bool NonNegative)
8001 : Width(Width), NonNegative(NonNegative)
8002 {}
John McCallca01b222010-01-04 23:21:16 +00008003
John McCall817d4af2010-11-10 23:38:19 +00008004 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00008005 static IntRange forBoolType() {
8006 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00008007 }
8008
John McCall817d4af2010-11-10 23:38:19 +00008009 /// Returns the range of an opaque value of the given integral type.
8010 static IntRange forValueOfType(ASTContext &C, QualType T) {
8011 return forValueOfCanonicalType(C,
8012 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00008013 }
8014
John McCall817d4af2010-11-10 23:38:19 +00008015 /// Returns the range of an opaque value of a canonical integral type.
8016 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00008017 assert(T->isCanonicalUnqualified());
8018
8019 if (const VectorType *VT = dyn_cast<VectorType>(T))
8020 T = VT->getElementType().getTypePtr();
8021 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8022 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00008023 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8024 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00008025
David Majnemer6a426652013-06-07 22:07:20 +00008026 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00008027 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00008028 EnumDecl *Enum = ET->getDecl();
8029 if (!Enum->isCompleteDefinition())
8030 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00008031
David Majnemer6a426652013-06-07 22:07:20 +00008032 unsigned NumPositive = Enum->getNumPositiveBits();
8033 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00008034
David Majnemer6a426652013-06-07 22:07:20 +00008035 if (NumNegative == 0)
8036 return IntRange(NumPositive, true/*NonNegative*/);
8037 else
8038 return IntRange(std::max(NumPositive + 1, NumNegative),
8039 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00008040 }
John McCall70aa5392010-01-06 05:24:50 +00008041
8042 const BuiltinType *BT = cast<BuiltinType>(T);
8043 assert(BT->isInteger());
8044
8045 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8046 }
8047
John McCall817d4af2010-11-10 23:38:19 +00008048 /// Returns the "target" range of a canonical integral type, i.e.
8049 /// the range of values expressible in the type.
8050 ///
8051 /// This matches forValueOfCanonicalType except that enums have the
8052 /// full range of their type, not the range of their enumerators.
8053 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
8054 assert(T->isCanonicalUnqualified());
8055
8056 if (const VectorType *VT = dyn_cast<VectorType>(T))
8057 T = VT->getElementType().getTypePtr();
8058 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8059 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00008060 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8061 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00008062 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00008063 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00008064
8065 const BuiltinType *BT = cast<BuiltinType>(T);
8066 assert(BT->isInteger());
8067
8068 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8069 }
8070
8071 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00008072 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00008073 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00008074 L.NonNegative && R.NonNegative);
8075 }
8076
John McCall817d4af2010-11-10 23:38:19 +00008077 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00008078 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00008079 return IntRange(std::min(L.Width, R.Width),
8080 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00008081 }
8082};
8083
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008084IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008085 if (value.isSigned() && value.isNegative())
8086 return IntRange(value.getMinSignedBits(), false);
8087
8088 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00008089 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00008090
8091 // isNonNegative() just checks the sign bit without considering
8092 // signedness.
8093 return IntRange(value.getActiveBits(), true);
8094}
8095
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008096IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
8097 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008098 if (result.isInt())
8099 return GetValueRange(C, result.getInt(), MaxWidth);
8100
8101 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00008102 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
8103 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
8104 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
8105 R = IntRange::join(R, El);
8106 }
John McCall70aa5392010-01-06 05:24:50 +00008107 return R;
8108 }
8109
8110 if (result.isComplexInt()) {
8111 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
8112 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
8113 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00008114 }
8115
8116 // This can happen with lossless casts to intptr_t of "based" lvalues.
8117 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00008118 // FIXME: The only reason we need to pass the type in here is to get
8119 // the sign right on this one case. It would be nice if APValue
8120 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008121 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00008122 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00008123}
John McCall70aa5392010-01-06 05:24:50 +00008124
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008125QualType GetExprType(const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008126 QualType Ty = E->getType();
8127 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
8128 Ty = AtomicRHS->getValueType();
8129 return Ty;
8130}
8131
John McCall70aa5392010-01-06 05:24:50 +00008132/// Pseudo-evaluate the given integer expression, estimating the
8133/// range of values it might take.
8134///
8135/// \param MaxWidth - the width to which the value will be truncated
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008136IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008137 E = E->IgnoreParens();
8138
8139 // Try a full evaluation first.
8140 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00008141 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00008142 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00008143
8144 // I think we only want to look through implicit casts here; if the
8145 // user has an explicit widening cast, we should treat the value as
8146 // being of the new, wider type.
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008147 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00008148 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00008149 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
8150
Eli Friedmane6d33952013-07-08 20:20:06 +00008151 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00008152
George Burgess IVdf1ed002016-01-13 01:52:39 +00008153 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
8154 CE->getCastKind() == CK_BooleanToSignedIntegral;
John McCall2ce81ad2010-01-06 22:07:33 +00008155
John McCall70aa5392010-01-06 05:24:50 +00008156 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00008157 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00008158 return OutputTypeRange;
8159
8160 IntRange SubRange
8161 = GetExprRange(C, CE->getSubExpr(),
8162 std::min(MaxWidth, OutputTypeRange.Width));
8163
8164 // Bail out if the subexpr's range is as wide as the cast type.
8165 if (SubRange.Width >= OutputTypeRange.Width)
8166 return OutputTypeRange;
8167
8168 // Otherwise, we take the smaller width, and we're non-negative if
8169 // either the output type or the subexpr is.
8170 return IntRange(SubRange.Width,
8171 SubRange.NonNegative || OutputTypeRange.NonNegative);
8172 }
8173
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008174 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008175 // If we can fold the condition, just take that operand.
8176 bool CondResult;
8177 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
8178 return GetExprRange(C, CondResult ? CO->getTrueExpr()
8179 : CO->getFalseExpr(),
8180 MaxWidth);
8181
8182 // Otherwise, conservatively merge.
8183 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
8184 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
8185 return IntRange::join(L, R);
8186 }
8187
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008188 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008189 switch (BO->getOpcode()) {
8190
8191 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00008192 case BO_LAnd:
8193 case BO_LOr:
8194 case BO_LT:
8195 case BO_GT:
8196 case BO_LE:
8197 case BO_GE:
8198 case BO_EQ:
8199 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00008200 return IntRange::forBoolType();
8201
John McCallc3688382011-07-13 06:35:24 +00008202 // The type of the assignments is the type of the LHS, so the RHS
8203 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00008204 case BO_MulAssign:
8205 case BO_DivAssign:
8206 case BO_RemAssign:
8207 case BO_AddAssign:
8208 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00008209 case BO_XorAssign:
8210 case BO_OrAssign:
8211 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00008212 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00008213
John McCallc3688382011-07-13 06:35:24 +00008214 // Simple assignments just pass through the RHS, which will have
8215 // been coerced to the LHS type.
8216 case BO_Assign:
8217 // TODO: bitfields?
8218 return GetExprRange(C, BO->getRHS(), MaxWidth);
8219
John McCall70aa5392010-01-06 05:24:50 +00008220 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00008221 case BO_PtrMemD:
8222 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00008223 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008224
John McCall2ce81ad2010-01-06 22:07:33 +00008225 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00008226 case BO_And:
8227 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00008228 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
8229 GetExprRange(C, BO->getRHS(), MaxWidth));
8230
John McCall70aa5392010-01-06 05:24:50 +00008231 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00008232 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00008233 // ...except that we want to treat '1 << (blah)' as logically
8234 // positive. It's an important idiom.
8235 if (IntegerLiteral *I
8236 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
8237 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008238 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00008239 return IntRange(R.Width, /*NonNegative*/ true);
8240 }
8241 }
8242 // fallthrough
8243
John McCalle3027922010-08-25 11:45:40 +00008244 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00008245 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008246
John McCall2ce81ad2010-01-06 22:07:33 +00008247 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00008248 case BO_Shr:
8249 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00008250 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8251
8252 // If the shift amount is a positive constant, drop the width by
8253 // that much.
8254 llvm::APSInt shift;
8255 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
8256 shift.isNonNegative()) {
8257 unsigned zext = shift.getZExtValue();
8258 if (zext >= L.Width)
8259 L.Width = (L.NonNegative ? 0 : 1);
8260 else
8261 L.Width -= zext;
8262 }
8263
8264 return L;
8265 }
8266
8267 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00008268 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00008269 return GetExprRange(C, BO->getRHS(), MaxWidth);
8270
John McCall2ce81ad2010-01-06 22:07:33 +00008271 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00008272 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00008273 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00008274 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008275 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00008276
John McCall51431812011-07-14 22:39:48 +00008277 // The width of a division result is mostly determined by the size
8278 // of the LHS.
8279 case BO_Div: {
8280 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00008281 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008282 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8283
8284 // If the divisor is constant, use that.
8285 llvm::APSInt divisor;
8286 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
8287 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
8288 if (log2 >= L.Width)
8289 L.Width = (L.NonNegative ? 0 : 1);
8290 else
8291 L.Width = std::min(L.Width - log2, MaxWidth);
8292 return L;
8293 }
8294
8295 // Otherwise, just use the LHS's width.
8296 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8297 return IntRange(L.Width, L.NonNegative && R.NonNegative);
8298 }
8299
8300 // The result of a remainder can't be larger than the result of
8301 // either side.
8302 case BO_Rem: {
8303 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00008304 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008305 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8306 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8307
8308 IntRange meet = IntRange::meet(L, R);
8309 meet.Width = std::min(meet.Width, MaxWidth);
8310 return meet;
8311 }
8312
8313 // The default behavior is okay for these.
8314 case BO_Mul:
8315 case BO_Add:
8316 case BO_Xor:
8317 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00008318 break;
8319 }
8320
John McCall51431812011-07-14 22:39:48 +00008321 // The default case is to treat the operation as if it were closed
8322 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00008323 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8324 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
8325 return IntRange::join(L, R);
8326 }
8327
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008328 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008329 switch (UO->getOpcode()) {
8330 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00008331 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00008332 return IntRange::forBoolType();
8333
8334 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00008335 case UO_Deref:
8336 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00008337 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008338
8339 default:
8340 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
8341 }
8342 }
8343
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008344 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
Ted Kremeneka553fbf2013-10-14 18:55:27 +00008345 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
8346
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008347 if (const auto *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00008348 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00008349 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00008350
Eli Friedmane6d33952013-07-08 20:20:06 +00008351 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008352}
John McCall263a48b2010-01-04 23:31:57 +00008353
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008354IntRange GetExprRange(ASTContext &C, const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008355 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00008356}
8357
John McCall263a48b2010-01-04 23:31:57 +00008358/// Checks whether the given value, which currently has the given
8359/// source semantics, has the same value when coerced through the
8360/// target semantics.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008361bool IsSameFloatAfterCast(const llvm::APFloat &value,
8362 const llvm::fltSemantics &Src,
8363 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00008364 llvm::APFloat truncated = value;
8365
8366 bool ignored;
8367 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
8368 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
8369
8370 return truncated.bitwiseIsEqual(value);
8371}
8372
8373/// Checks whether the given value, which currently has the given
8374/// source semantics, has the same value when coerced through the
8375/// target semantics.
8376///
8377/// The value might be a vector of floats (or a complex number).
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008378bool IsSameFloatAfterCast(const APValue &value,
8379 const llvm::fltSemantics &Src,
8380 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00008381 if (value.isFloat())
8382 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
8383
8384 if (value.isVector()) {
8385 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
8386 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
8387 return false;
8388 return true;
8389 }
8390
8391 assert(value.isComplexFloat());
8392 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
8393 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
8394}
8395
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008396void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008397
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008398bool IsZero(Sema &S, Expr *E) {
Ted Kremenek6274be42010-09-23 21:43:44 +00008399 // Suppress cases where we are comparing against an enum constant.
8400 if (const DeclRefExpr *DR =
8401 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
8402 if (isa<EnumConstantDecl>(DR->getDecl()))
8403 return false;
8404
8405 // Suppress cases where the '0' value is expanded from a macro.
8406 if (E->getLocStart().isMacroID())
8407 return false;
8408
John McCallcc7e5bf2010-05-06 08:58:33 +00008409 llvm::APSInt Value;
8410 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
8411}
8412
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008413bool HasEnumType(Expr *E) {
John McCall2551c1b2010-10-06 00:25:24 +00008414 // Strip off implicit integral promotions.
8415 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00008416 if (ICE->getCastKind() != CK_IntegralCast &&
8417 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00008418 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00008419 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00008420 }
8421
8422 return E->getType()->isEnumeralType();
8423}
8424
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008425void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00008426 // Disable warning in template instantiations.
Richard Smith51ec0cf2017-02-21 01:17:38 +00008427 if (S.inTemplateInstantiation())
Richard Trieu36594562013-11-01 21:47:19 +00008428 return;
8429
John McCalle3027922010-08-25 11:45:40 +00008430 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00008431 if (E->isValueDependent())
8432 return;
8433
John McCalle3027922010-08-25 11:45:40 +00008434 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008435 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00008436 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00008437 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00008438 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008439 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00008440 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00008441 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00008442 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008443 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00008444 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00008445 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00008446 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008447 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00008448 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00008449 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
8450 }
8451}
8452
Benjamin Kramer7320b992016-06-15 14:20:56 +00008453void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E, Expr *Constant,
8454 Expr *Other, const llvm::APSInt &Value,
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008455 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00008456 // Disable warning in template instantiations.
Richard Smith51ec0cf2017-02-21 01:17:38 +00008457 if (S.inTemplateInstantiation())
Richard Trieudd51d742013-11-01 21:19:43 +00008458 return;
8459
Richard Trieu0f097742014-04-04 04:13:47 +00008460 // TODO: Investigate using GetExprRange() to get tighter bounds
8461 // on the bit ranges.
8462 QualType OtherT = Other->getType();
David Majnemer7800f1f2015-05-23 01:32:17 +00008463 if (const auto *AT = OtherT->getAs<AtomicType>())
Justin Bogner4f42fc42014-07-21 18:01:53 +00008464 OtherT = AT->getValueType();
Richard Trieu0f097742014-04-04 04:13:47 +00008465 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
8466 unsigned OtherWidth = OtherRange.Width;
8467
8468 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
8469
Richard Trieu560910c2012-11-14 22:50:24 +00008470 // 0 values are handled later by CheckTrivialUnsignedComparison().
Richard Trieu0f097742014-04-04 04:13:47 +00008471 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00008472 return;
8473
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008474 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00008475 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00008476
Richard Trieu0f097742014-04-04 04:13:47 +00008477 // Used for diagnostic printout.
8478 enum {
8479 LiteralConstant = 0,
8480 CXXBoolLiteralTrue,
8481 CXXBoolLiteralFalse
8482 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00008483
Richard Trieu0f097742014-04-04 04:13:47 +00008484 if (!OtherIsBooleanType) {
8485 QualType ConstantT = Constant->getType();
8486 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00008487
Richard Trieu0f097742014-04-04 04:13:47 +00008488 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
8489 return;
8490 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
8491 "comparison with non-integer type");
8492
8493 bool ConstantSigned = ConstantT->isSignedIntegerType();
8494 bool CommonSigned = CommonT->isSignedIntegerType();
8495
8496 bool EqualityOnly = false;
8497
8498 if (CommonSigned) {
8499 // The common type is signed, therefore no signed to unsigned conversion.
8500 if (!OtherRange.NonNegative) {
8501 // Check that the constant is representable in type OtherT.
8502 if (ConstantSigned) {
8503 if (OtherWidth >= Value.getMinSignedBits())
8504 return;
8505 } else { // !ConstantSigned
8506 if (OtherWidth >= Value.getActiveBits() + 1)
8507 return;
8508 }
8509 } else { // !OtherSigned
8510 // Check that the constant is representable in type OtherT.
8511 // Negative values are out of range.
8512 if (ConstantSigned) {
8513 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
8514 return;
8515 } else { // !ConstantSigned
8516 if (OtherWidth >= Value.getActiveBits())
8517 return;
8518 }
Richard Trieu560910c2012-11-14 22:50:24 +00008519 }
Richard Trieu0f097742014-04-04 04:13:47 +00008520 } else { // !CommonSigned
8521 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00008522 if (OtherWidth >= Value.getActiveBits())
8523 return;
Craig Toppercf360162014-06-18 05:13:11 +00008524 } else { // OtherSigned
8525 assert(!ConstantSigned &&
8526 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00008527 // Check to see if the constant is representable in OtherT.
8528 if (OtherWidth > Value.getActiveBits())
8529 return;
8530 // Check to see if the constant is equivalent to a negative value
8531 // cast to CommonT.
8532 if (S.Context.getIntWidth(ConstantT) ==
8533 S.Context.getIntWidth(CommonT) &&
8534 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
8535 return;
8536 // The constant value rests between values that OtherT can represent
8537 // after conversion. Relational comparison still works, but equality
8538 // comparisons will be tautological.
8539 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00008540 }
8541 }
Richard Trieu0f097742014-04-04 04:13:47 +00008542
8543 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
8544
8545 if (op == BO_EQ || op == BO_NE) {
8546 IsTrue = op == BO_NE;
8547 } else if (EqualityOnly) {
8548 return;
8549 } else if (RhsConstant) {
8550 if (op == BO_GT || op == BO_GE)
8551 IsTrue = !PositiveConstant;
8552 else // op == BO_LT || op == BO_LE
8553 IsTrue = PositiveConstant;
8554 } else {
8555 if (op == BO_LT || op == BO_LE)
8556 IsTrue = !PositiveConstant;
8557 else // op == BO_GT || op == BO_GE
8558 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00008559 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00008560 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00008561 // Other isKnownToHaveBooleanValue
8562 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
8563 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
8564 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
8565
8566 static const struct LinkedConditions {
8567 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
8568 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
8569 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
8570 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
8571 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
8572 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
8573
8574 } TruthTable = {
8575 // Constant on LHS. | Constant on RHS. |
8576 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
8577 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
8578 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
8579 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
8580 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
8581 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
8582 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
8583 };
8584
8585 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
8586
8587 enum ConstantValue ConstVal = Zero;
8588 if (Value.isUnsigned() || Value.isNonNegative()) {
8589 if (Value == 0) {
8590 LiteralOrBoolConstant =
8591 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
8592 ConstVal = Zero;
8593 } else if (Value == 1) {
8594 LiteralOrBoolConstant =
8595 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
8596 ConstVal = One;
8597 } else {
8598 LiteralOrBoolConstant = LiteralConstant;
8599 ConstVal = GT_One;
8600 }
8601 } else {
8602 ConstVal = LT_Zero;
8603 }
8604
8605 CompareBoolWithConstantResult CmpRes;
8606
8607 switch (op) {
8608 case BO_LT:
8609 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
8610 break;
8611 case BO_GT:
8612 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
8613 break;
8614 case BO_LE:
8615 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
8616 break;
8617 case BO_GE:
8618 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
8619 break;
8620 case BO_EQ:
8621 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
8622 break;
8623 case BO_NE:
8624 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
8625 break;
8626 default:
8627 CmpRes = Unkwn;
8628 break;
8629 }
8630
8631 if (CmpRes == AFals) {
8632 IsTrue = false;
8633 } else if (CmpRes == ATrue) {
8634 IsTrue = true;
8635 } else {
8636 return;
8637 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008638 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008639
8640 // If this is a comparison to an enum constant, include that
8641 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00008642 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008643 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
8644 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
8645
8646 SmallString<64> PrettySourceValue;
8647 llvm::raw_svector_ostream OS(PrettySourceValue);
8648 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00008649 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008650 else
8651 OS << Value;
8652
Richard Trieu0f097742014-04-04 04:13:47 +00008653 S.DiagRuntimeBehavior(
8654 E->getOperatorLoc(), E,
8655 S.PDiag(diag::warn_out_of_range_compare)
8656 << OS.str() << LiteralOrBoolConstant
8657 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
8658 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008659}
8660
John McCallcc7e5bf2010-05-06 08:58:33 +00008661/// Analyze the operands of the given comparison. Implements the
8662/// fallback case from AnalyzeComparison.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008663void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00008664 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8665 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00008666}
John McCall263a48b2010-01-04 23:31:57 +00008667
John McCallca01b222010-01-04 23:21:16 +00008668/// \brief Implements -Wsign-compare.
8669///
Richard Trieu82402a02011-09-15 21:56:47 +00008670/// \param E the binary operator to check for warnings
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008671void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008672 // The type the comparison is being performed in.
8673 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00008674
8675 // Only analyze comparison operators where both sides have been converted to
8676 // the same type.
8677 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
8678 return AnalyzeImpConvsInComparison(S, E);
8679
8680 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00008681 if (E->isValueDependent())
8682 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00008683
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008684 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
8685 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008686
8687 bool IsComparisonConstant = false;
8688
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00008689 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008690 // of 'true' or 'false'.
8691 if (T->isIntegralType(S.Context)) {
8692 llvm::APSInt RHSValue;
8693 bool IsRHSIntegralLiteral =
8694 RHS->isIntegerConstantExpr(RHSValue, S.Context);
8695 llvm::APSInt LHSValue;
8696 bool IsLHSIntegralLiteral =
8697 LHS->isIntegerConstantExpr(LHSValue, S.Context);
8698 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
8699 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
8700 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
8701 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
8702 else
8703 IsComparisonConstant =
8704 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00008705 } else if (!T->hasUnsignedIntegerRepresentation())
8706 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008707
John McCallcc7e5bf2010-05-06 08:58:33 +00008708 // We don't do anything special if this isn't an unsigned integral
8709 // comparison: we're only interested in integral comparisons, and
8710 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00008711 //
8712 // We also don't care about value-dependent expressions or expressions
8713 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008714 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00008715 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008716
John McCallcc7e5bf2010-05-06 08:58:33 +00008717 // Check to see if one of the (unmodified) operands is of different
8718 // signedness.
8719 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00008720 if (LHS->getType()->hasSignedIntegerRepresentation()) {
8721 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00008722 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00008723 signedOperand = LHS;
8724 unsignedOperand = RHS;
8725 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
8726 signedOperand = RHS;
8727 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00008728 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00008729 CheckTrivialUnsignedComparison(S, E);
8730 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00008731 }
8732
John McCallcc7e5bf2010-05-06 08:58:33 +00008733 // Otherwise, calculate the effective range of the signed operand.
8734 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00008735
John McCallcc7e5bf2010-05-06 08:58:33 +00008736 // Go ahead and analyze implicit conversions in the operands. Note
8737 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00008738 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
8739 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00008740
John McCallcc7e5bf2010-05-06 08:58:33 +00008741 // If the signed range is non-negative, -Wsign-compare won't fire,
8742 // but we should still check for comparisons which are always true
8743 // or false.
8744 if (signedRange.NonNegative)
8745 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00008746
8747 // For (in)equality comparisons, if the unsigned operand is a
8748 // constant which cannot collide with a overflowed signed operand,
8749 // then reinterpreting the signed operand as unsigned will not
8750 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00008751 if (E->isEqualityOp()) {
8752 unsigned comparisonWidth = S.Context.getIntWidth(T);
8753 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00008754
John McCallcc7e5bf2010-05-06 08:58:33 +00008755 // We should never be unable to prove that the unsigned operand is
8756 // non-negative.
8757 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
8758
8759 if (unsignedRange.Width < comparisonWidth)
8760 return;
8761 }
8762
Douglas Gregorbfb4a212012-05-01 01:53:49 +00008763 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
8764 S.PDiag(diag::warn_mixed_sign_comparison)
8765 << LHS->getType() << RHS->getType()
8766 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00008767}
8768
John McCall1f425642010-11-11 03:21:53 +00008769/// Analyzes an attempt to assign the given value to a bitfield.
8770///
8771/// Returns true if there was something fishy about the attempt.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008772bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
8773 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00008774 assert(Bitfield->isBitField());
8775 if (Bitfield->isInvalidDecl())
8776 return false;
8777
John McCalldeebbcf2010-11-11 05:33:51 +00008778 // White-list bool bitfields.
Reid Klecknerad425622016-11-16 23:40:00 +00008779 QualType BitfieldType = Bitfield->getType();
8780 if (BitfieldType->isBooleanType())
8781 return false;
8782
8783 if (BitfieldType->isEnumeralType()) {
8784 EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
8785 // If the underlying enum type was not explicitly specified as an unsigned
8786 // type and the enum contain only positive values, MSVC++ will cause an
8787 // inconsistency by storing this as a signed type.
8788 if (S.getLangOpts().CPlusPlus11 &&
8789 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
8790 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
8791 BitfieldEnumDecl->getNumNegativeBits() == 0) {
8792 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
8793 << BitfieldEnumDecl->getNameAsString();
8794 }
8795 }
8796
John McCalldeebbcf2010-11-11 05:33:51 +00008797 if (Bitfield->getType()->isBooleanType())
8798 return false;
8799
Douglas Gregor789adec2011-02-04 13:09:01 +00008800 // Ignore value- or type-dependent expressions.
8801 if (Bitfield->getBitWidth()->isValueDependent() ||
8802 Bitfield->getBitWidth()->isTypeDependent() ||
8803 Init->isValueDependent() ||
8804 Init->isTypeDependent())
8805 return false;
8806
John McCall1f425642010-11-11 03:21:53 +00008807 Expr *OriginalInit = Init->IgnoreParenImpCasts();
Reid Kleckner329f24d2017-03-14 18:01:02 +00008808 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00008809
Richard Smith5fab0c92011-12-28 19:48:30 +00008810 llvm::APSInt Value;
Reid Kleckner329f24d2017-03-14 18:01:02 +00008811 if (!OriginalInit->EvaluateAsInt(Value, S.Context,
8812 Expr::SE_AllowSideEffects)) {
8813 // The RHS is not constant. If the RHS has an enum type, make sure the
8814 // bitfield is wide enough to hold all the values of the enum without
8815 // truncation.
8816 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
8817 EnumDecl *ED = EnumTy->getDecl();
8818 bool SignedBitfield = BitfieldType->isSignedIntegerType();
8819
8820 // Enum types are implicitly signed on Windows, so check if there are any
8821 // negative enumerators to see if the enum was intended to be signed or
8822 // not.
8823 bool SignedEnum = ED->getNumNegativeBits() > 0;
8824
8825 // Check for surprising sign changes when assigning enum values to a
8826 // bitfield of different signedness. If the bitfield is signed and we
8827 // have exactly the right number of bits to store this unsigned enum,
8828 // suggest changing the enum to an unsigned type. This typically happens
8829 // on Windows where unfixed enums always use an underlying type of 'int'.
8830 unsigned DiagID = 0;
8831 if (SignedEnum && !SignedBitfield) {
8832 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
8833 } else if (SignedBitfield && !SignedEnum &&
8834 ED->getNumPositiveBits() == FieldWidth) {
8835 DiagID = diag::warn_signed_bitfield_enum_conversion;
8836 }
8837
8838 if (DiagID) {
8839 S.Diag(InitLoc, DiagID) << Bitfield << ED;
8840 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
8841 SourceRange TypeRange =
8842 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
8843 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
8844 << SignedEnum << TypeRange;
8845 }
8846
8847 // Compute the required bitwidth. If the enum has negative values, we need
8848 // one more bit than the normal number of positive bits to represent the
8849 // sign bit.
8850 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
8851 ED->getNumNegativeBits())
8852 : ED->getNumPositiveBits();
8853
8854 // Check the bitwidth.
8855 if (BitsNeeded > FieldWidth) {
8856 Expr *WidthExpr = Bitfield->getBitWidth();
8857 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
8858 << Bitfield << ED;
8859 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
8860 << BitsNeeded << ED << WidthExpr->getSourceRange();
8861 }
8862 }
8863
John McCall1f425642010-11-11 03:21:53 +00008864 return false;
Reid Kleckner329f24d2017-03-14 18:01:02 +00008865 }
John McCall1f425642010-11-11 03:21:53 +00008866
John McCall1f425642010-11-11 03:21:53 +00008867 unsigned OriginalWidth = Value.getBitWidth();
John McCall1f425642010-11-11 03:21:53 +00008868
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +00008869 if (!Value.isSigned() || Value.isNegative())
Richard Trieu7561ed02016-08-05 02:39:30 +00008870 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +00008871 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
8872 OriginalWidth = Value.getMinSignedBits();
Richard Trieu7561ed02016-08-05 02:39:30 +00008873
John McCall1f425642010-11-11 03:21:53 +00008874 if (OriginalWidth <= FieldWidth)
8875 return false;
8876
Eli Friedmanc267a322012-01-26 23:11:39 +00008877 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00008878 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Reid Klecknerad425622016-11-16 23:40:00 +00008879 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00008880
Eli Friedmanc267a322012-01-26 23:11:39 +00008881 // Check whether the stored value is equal to the original value.
8882 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00008883 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00008884 return false;
8885
Eli Friedmanc267a322012-01-26 23:11:39 +00008886 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00008887 // therefore don't strictly fit into a signed bitfield of width 1.
8888 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00008889 return false;
8890
John McCall1f425642010-11-11 03:21:53 +00008891 std::string PrettyValue = Value.toString(10);
8892 std::string PrettyTrunc = TruncatedValue.toString(10);
8893
8894 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
8895 << PrettyValue << PrettyTrunc << OriginalInit->getType()
8896 << Init->getSourceRange();
8897
8898 return true;
8899}
8900
John McCalld2a53122010-11-09 23:24:47 +00008901/// Analyze the given simple or compound assignment for warning-worthy
8902/// operations.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008903void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00008904 // Just recurse on the LHS.
8905 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8906
8907 // We want to recurse on the RHS as normal unless we're assigning to
8908 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00008909 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008910 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00008911 E->getOperatorLoc())) {
8912 // Recurse, ignoring any implicit conversions on the RHS.
8913 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
8914 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00008915 }
8916 }
8917
8918 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
8919}
8920
John McCall263a48b2010-01-04 23:31:57 +00008921/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008922void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
8923 SourceLocation CContext, unsigned diag,
8924 bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00008925 if (pruneControlFlow) {
8926 S.DiagRuntimeBehavior(E->getExprLoc(), E,
8927 S.PDiag(diag)
8928 << SourceType << T << E->getSourceRange()
8929 << SourceRange(CContext));
8930 return;
8931 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00008932 S.Diag(E->getExprLoc(), diag)
8933 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
8934}
8935
Chandler Carruth7f3654f2011-04-05 06:47:57 +00008936/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008937void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
8938 unsigned diag, bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00008939 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00008940}
8941
Richard Trieube234c32016-04-21 21:04:55 +00008942
8943/// Diagnose an implicit cast from a floating point value to an integer value.
8944void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
8945
8946 SourceLocation CContext) {
8947 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
Richard Smith51ec0cf2017-02-21 01:17:38 +00008948 const bool PruneWarnings = S.inTemplateInstantiation();
Richard Trieube234c32016-04-21 21:04:55 +00008949
8950 Expr *InnerE = E->IgnoreParenImpCasts();
8951 // We also want to warn on, e.g., "int i = -1.234"
8952 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
8953 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
8954 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
8955
8956 const bool IsLiteral =
8957 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
8958
8959 llvm::APFloat Value(0.0);
8960 bool IsConstant =
8961 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
8962 if (!IsConstant) {
Richard Trieu891f0f12016-04-22 22:14:32 +00008963 return DiagnoseImpCast(S, E, T, CContext,
8964 diag::warn_impcast_float_integer, PruneWarnings);
Richard Trieube234c32016-04-21 21:04:55 +00008965 }
8966
Chandler Carruth016ef402011-04-10 08:36:24 +00008967 bool isExact = false;
Richard Trieube234c32016-04-21 21:04:55 +00008968
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00008969 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
8970 T->hasUnsignedIntegerRepresentation());
Richard Trieube234c32016-04-21 21:04:55 +00008971 if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero,
8972 &isExact) == llvm::APFloat::opOK &&
Richard Trieu891f0f12016-04-22 22:14:32 +00008973 isExact) {
Richard Trieube234c32016-04-21 21:04:55 +00008974 if (IsLiteral) return;
8975 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
8976 PruneWarnings);
8977 }
8978
8979 unsigned DiagID = 0;
Richard Trieu891f0f12016-04-22 22:14:32 +00008980 if (IsLiteral) {
Richard Trieube234c32016-04-21 21:04:55 +00008981 // Warn on floating point literal to integer.
8982 DiagID = diag::warn_impcast_literal_float_to_integer;
8983 } else if (IntegerValue == 0) {
8984 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
8985 return DiagnoseImpCast(S, E, T, CContext,
8986 diag::warn_impcast_float_integer, PruneWarnings);
8987 }
8988 // Warn on non-zero to zero conversion.
8989 DiagID = diag::warn_impcast_float_to_integer_zero;
8990 } else {
8991 if (IntegerValue.isUnsigned()) {
8992 if (!IntegerValue.isMaxValue()) {
8993 return DiagnoseImpCast(S, E, T, CContext,
8994 diag::warn_impcast_float_integer, PruneWarnings);
8995 }
8996 } else { // IntegerValue.isSigned()
8997 if (!IntegerValue.isMaxSignedValue() &&
8998 !IntegerValue.isMinSignedValue()) {
8999 return DiagnoseImpCast(S, E, T, CContext,
9000 diag::warn_impcast_float_integer, PruneWarnings);
9001 }
9002 }
9003 // Warn on evaluatable floating point expression to integer conversion.
9004 DiagID = diag::warn_impcast_float_to_integer;
9005 }
Chandler Carruth016ef402011-04-10 08:36:24 +00009006
Eli Friedman07185912013-08-29 23:44:43 +00009007 // FIXME: Force the precision of the source value down so we don't print
9008 // digits which are usually useless (we don't really care here if we
9009 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
9010 // would automatically print the shortest representation, but it's a bit
9011 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00009012 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00009013 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
9014 precision = (precision * 59 + 195) / 196;
9015 Value.toString(PrettySourceValue, precision);
9016
David Blaikie9b88cc02012-05-15 17:18:27 +00009017 SmallString<16> PrettyTargetValue;
Richard Trieube234c32016-04-21 21:04:55 +00009018 if (IsBool)
Aaron Ballmandbc441e2015-12-30 14:26:07 +00009019 PrettyTargetValue = Value.isZero() ? "false" : "true";
David Blaikie7555b6a2012-05-15 16:56:36 +00009020 else
David Blaikie9b88cc02012-05-15 17:18:27 +00009021 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00009022
Richard Trieube234c32016-04-21 21:04:55 +00009023 if (PruneWarnings) {
9024 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9025 S.PDiag(DiagID)
9026 << E->getType() << T.getUnqualifiedType()
9027 << PrettySourceValue << PrettyTargetValue
9028 << E->getSourceRange() << SourceRange(CContext));
9029 } else {
9030 S.Diag(E->getExprLoc(), DiagID)
9031 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
9032 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
9033 }
Chandler Carruth016ef402011-04-10 08:36:24 +00009034}
9035
John McCall18a2c2c2010-11-09 22:22:12 +00009036std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
9037 if (!Range.Width) return "0";
9038
9039 llvm::APSInt ValueInRange = Value;
9040 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00009041 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00009042 return ValueInRange.toString(10);
9043}
9044
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009045bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009046 if (!isa<ImplicitCastExpr>(Ex))
9047 return false;
9048
9049 Expr *InnerE = Ex->IgnoreParenImpCasts();
9050 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
9051 const Type *Source =
9052 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
9053 if (Target->isDependentType())
9054 return false;
9055
9056 const BuiltinType *FloatCandidateBT =
9057 dyn_cast<BuiltinType>(ToBool ? Source : Target);
9058 const Type *BoolCandidateType = ToBool ? Target : Source;
9059
9060 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
9061 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
9062}
9063
9064void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
9065 SourceLocation CC) {
9066 unsigned NumArgs = TheCall->getNumArgs();
9067 for (unsigned i = 0; i < NumArgs; ++i) {
9068 Expr *CurrA = TheCall->getArg(i);
9069 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
9070 continue;
9071
9072 bool IsSwapped = ((i > 0) &&
9073 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
9074 IsSwapped |= ((i < (NumArgs - 1)) &&
9075 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
9076 if (IsSwapped) {
9077 // Warn on this floating-point to bool conversion.
9078 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
9079 CurrA->getType(), CC,
9080 diag::warn_impcast_floating_point_to_bool);
9081 }
9082 }
9083}
9084
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009085void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) {
Richard Trieu5b993502014-10-15 03:42:06 +00009086 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
9087 E->getExprLoc()))
9088 return;
9089
Richard Trieu09d6b802016-01-08 23:35:06 +00009090 // Don't warn on functions which have return type nullptr_t.
9091 if (isa<CallExpr>(E))
9092 return;
9093
Richard Trieu5b993502014-10-15 03:42:06 +00009094 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
9095 const Expr::NullPointerConstantKind NullKind =
9096 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
9097 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
9098 return;
9099
9100 // Return if target type is a safe conversion.
9101 if (T->isAnyPointerType() || T->isBlockPointerType() ||
9102 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
9103 return;
9104
9105 SourceLocation Loc = E->getSourceRange().getBegin();
9106
Richard Trieu0a5e1662016-02-13 00:58:53 +00009107 // Venture through the macro stacks to get to the source of macro arguments.
9108 // The new location is a better location than the complete location that was
9109 // passed in.
9110 while (S.SourceMgr.isMacroArgExpansion(Loc))
9111 Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc);
9112
9113 while (S.SourceMgr.isMacroArgExpansion(CC))
9114 CC = S.SourceMgr.getImmediateMacroCallerLoc(CC);
9115
Richard Trieu5b993502014-10-15 03:42:06 +00009116 // __null is usually wrapped in a macro. Go up a macro if that is the case.
Richard Trieu0a5e1662016-02-13 00:58:53 +00009117 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
9118 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
9119 Loc, S.SourceMgr, S.getLangOpts());
9120 if (MacroName == "NULL")
9121 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
Richard Trieu5b993502014-10-15 03:42:06 +00009122 }
9123
9124 // Only warn if the null and context location are in the same macro expansion.
9125 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
9126 return;
9127
9128 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
9129 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
9130 << FixItHint::CreateReplacement(Loc,
9131 S.getFixItZeroLiteralForType(T, Loc));
9132}
9133
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009134void checkObjCArrayLiteral(Sema &S, QualType TargetType,
9135 ObjCArrayLiteral *ArrayLiteral);
9136void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
9137 ObjCDictionaryLiteral *DictionaryLiteral);
Douglas Gregor5054cb02015-07-07 03:58:22 +00009138
9139/// Check a single element within a collection literal against the
9140/// target element type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009141void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType,
9142 Expr *Element, unsigned ElementKind) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00009143 // Skip a bitcast to 'id' or qualified 'id'.
9144 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
9145 if (ICE->getCastKind() == CK_BitCast &&
9146 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
9147 Element = ICE->getSubExpr();
9148 }
9149
9150 QualType ElementType = Element->getType();
9151 ExprResult ElementResult(Element);
9152 if (ElementType->getAs<ObjCObjectPointerType>() &&
9153 S.CheckSingleAssignmentConstraints(TargetElementType,
9154 ElementResult,
9155 false, false)
9156 != Sema::Compatible) {
9157 S.Diag(Element->getLocStart(),
9158 diag::warn_objc_collection_literal_element)
9159 << ElementType << ElementKind << TargetElementType
9160 << Element->getSourceRange();
9161 }
9162
9163 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
9164 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
9165 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
9166 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
9167}
9168
9169/// Check an Objective-C array literal being converted to the given
9170/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009171void checkObjCArrayLiteral(Sema &S, QualType TargetType,
9172 ObjCArrayLiteral *ArrayLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00009173 if (!S.NSArrayDecl)
9174 return;
9175
9176 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
9177 if (!TargetObjCPtr)
9178 return;
9179
9180 if (TargetObjCPtr->isUnspecialized() ||
9181 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
9182 != S.NSArrayDecl->getCanonicalDecl())
9183 return;
9184
9185 auto TypeArgs = TargetObjCPtr->getTypeArgs();
9186 if (TypeArgs.size() != 1)
9187 return;
9188
9189 QualType TargetElementType = TypeArgs[0];
9190 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
9191 checkObjCCollectionLiteralElement(S, TargetElementType,
9192 ArrayLiteral->getElement(I),
9193 0);
9194 }
9195}
9196
9197/// Check an Objective-C dictionary literal being converted to the given
9198/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009199void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
9200 ObjCDictionaryLiteral *DictionaryLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00009201 if (!S.NSDictionaryDecl)
9202 return;
9203
9204 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
9205 if (!TargetObjCPtr)
9206 return;
9207
9208 if (TargetObjCPtr->isUnspecialized() ||
9209 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
9210 != S.NSDictionaryDecl->getCanonicalDecl())
9211 return;
9212
9213 auto TypeArgs = TargetObjCPtr->getTypeArgs();
9214 if (TypeArgs.size() != 2)
9215 return;
9216
9217 QualType TargetKeyType = TypeArgs[0];
9218 QualType TargetObjectType = TypeArgs[1];
9219 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
9220 auto Element = DictionaryLiteral->getKeyValueElement(I);
9221 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
9222 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
9223 }
9224}
9225
Richard Trieufc404c72016-02-05 23:02:38 +00009226// Helper function to filter out cases for constant width constant conversion.
9227// Don't warn on char array initialization or for non-decimal values.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009228bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
9229 SourceLocation CC) {
Richard Trieufc404c72016-02-05 23:02:38 +00009230 // If initializing from a constant, and the constant starts with '0',
9231 // then it is a binary, octal, or hexadecimal. Allow these constants
9232 // to fill all the bits, even if there is a sign change.
9233 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
9234 const char FirstLiteralCharacter =
9235 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
9236 if (FirstLiteralCharacter == '0')
9237 return false;
9238 }
9239
9240 // If the CC location points to a '{', and the type is char, then assume
9241 // assume it is an array initialization.
9242 if (CC.isValid() && T->isCharType()) {
9243 const char FirstContextCharacter =
9244 S.getSourceManager().getCharacterData(CC)[0];
9245 if (FirstContextCharacter == '{')
9246 return false;
9247 }
9248
9249 return true;
9250}
9251
John McCallcc7e5bf2010-05-06 08:58:33 +00009252void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00009253 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009254 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00009255
John McCallcc7e5bf2010-05-06 08:58:33 +00009256 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
9257 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
9258 if (Source == Target) return;
9259 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00009260
Chandler Carruthc22845a2011-07-26 05:40:03 +00009261 // If the conversion context location is invalid don't complain. We also
9262 // don't want to emit a warning if the issue occurs from the expansion of
9263 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
9264 // delay this check as long as possible. Once we detect we are in that
9265 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009266 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00009267 return;
9268
Richard Trieu021baa32011-09-23 20:10:00 +00009269 // Diagnose implicit casts to bool.
9270 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
9271 if (isa<StringLiteral>(E))
9272 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00009273 // and expressions, for instance, assert(0 && "error here"), are
9274 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00009275 return DiagnoseImpCast(S, E, T, CC,
9276 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00009277 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
9278 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
9279 // This covers the literal expressions that evaluate to Objective-C
9280 // objects.
9281 return DiagnoseImpCast(S, E, T, CC,
9282 diag::warn_impcast_objective_c_literal_to_bool);
9283 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00009284 if (Source->isPointerType() || Source->canDecayToPointerType()) {
9285 // Warn on pointer to bool conversion that is always true.
9286 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
9287 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00009288 }
Richard Trieu021baa32011-09-23 20:10:00 +00009289 }
John McCall263a48b2010-01-04 23:31:57 +00009290
Douglas Gregor5054cb02015-07-07 03:58:22 +00009291 // Check implicit casts from Objective-C collection literals to specialized
9292 // collection types, e.g., NSArray<NSString *> *.
9293 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
9294 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
9295 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
9296 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
9297
John McCall263a48b2010-01-04 23:31:57 +00009298 // Strip vector types.
9299 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009300 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009301 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009302 return;
John McCallacf0ee52010-10-08 02:01:28 +00009303 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009304 }
Chris Lattneree7286f2011-06-14 04:51:15 +00009305
9306 // If the vector cast is cast between two vectors of the same size, it is
9307 // a bitcast, not a conversion.
9308 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
9309 return;
John McCall263a48b2010-01-04 23:31:57 +00009310
9311 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
9312 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
9313 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00009314 if (auto VecTy = dyn_cast<VectorType>(Target))
9315 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00009316
9317 // Strip complex types.
9318 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009319 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009320 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009321 return;
9322
John McCallacf0ee52010-10-08 02:01:28 +00009323 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009324 }
John McCall263a48b2010-01-04 23:31:57 +00009325
9326 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
9327 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
9328 }
9329
9330 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
9331 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
9332
9333 // If the source is floating point...
9334 if (SourceBT && SourceBT->isFloatingPoint()) {
9335 // ...and the target is floating point...
9336 if (TargetBT && TargetBT->isFloatingPoint()) {
9337 // ...then warn if we're dropping FP rank.
9338
9339 // Builtin FP kinds are ordered by increasing FP rank.
9340 if (SourceBT->getKind() > TargetBT->getKind()) {
9341 // Don't warn about float constants that are precisely
9342 // representable in the target type.
9343 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00009344 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00009345 // Value might be a float, a float vector, or a float complex.
9346 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00009347 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
9348 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00009349 return;
9350 }
9351
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009352 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009353 return;
9354
John McCallacf0ee52010-10-08 02:01:28 +00009355 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
George Burgess IV148e0d32015-10-29 00:28:52 +00009356 }
9357 // ... or possibly if we're increasing rank, too
9358 else if (TargetBT->getKind() > SourceBT->getKind()) {
9359 if (S.SourceMgr.isInSystemMacro(CC))
9360 return;
9361
9362 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
John McCall263a48b2010-01-04 23:31:57 +00009363 }
9364 return;
9365 }
9366
Richard Trieube234c32016-04-21 21:04:55 +00009367 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00009368 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009369 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009370 return;
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00009371
Richard Trieube234c32016-04-21 21:04:55 +00009372 DiagnoseFloatingImpCast(S, E, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00009373 }
John McCall263a48b2010-01-04 23:31:57 +00009374
Richard Smith54894fd2015-12-30 01:06:52 +00009375 // Detect the case where a call result is converted from floating-point to
9376 // to bool, and the final argument to the call is converted from bool, to
9377 // discover this typo:
9378 //
9379 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
9380 //
9381 // FIXME: This is an incredibly special case; is there some more general
9382 // way to detect this class of misplaced-parentheses bug?
9383 if (Target->isBooleanType() && isa<CallExpr>(E)) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009384 // Check last argument of function call to see if it is an
9385 // implicit cast from a type matching the type the result
9386 // is being cast to.
9387 CallExpr *CEx = cast<CallExpr>(E);
Richard Smith54894fd2015-12-30 01:06:52 +00009388 if (unsigned NumArgs = CEx->getNumArgs()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009389 Expr *LastA = CEx->getArg(NumArgs - 1);
9390 Expr *InnerE = LastA->IgnoreParenImpCasts();
Richard Smith54894fd2015-12-30 01:06:52 +00009391 if (isa<ImplicitCastExpr>(LastA) &&
9392 InnerE->getType()->isBooleanType()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009393 // Warn on this floating-point to bool conversion
9394 DiagnoseImpCast(S, E, T, CC,
9395 diag::warn_impcast_floating_point_to_bool);
9396 }
9397 }
9398 }
John McCall263a48b2010-01-04 23:31:57 +00009399 return;
9400 }
9401
Richard Trieu5b993502014-10-15 03:42:06 +00009402 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +00009403
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +00009404 S.DiscardMisalignedMemberAddress(Target, E);
9405
David Blaikie9366d2b2012-06-19 21:19:06 +00009406 if (!Source->isIntegerType() || !Target->isIntegerType())
9407 return;
9408
David Blaikie7555b6a2012-05-15 16:56:36 +00009409 // TODO: remove this early return once the false positives for constant->bool
9410 // in templates, macros, etc, are reduced or removed.
9411 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
9412 return;
9413
John McCallcc7e5bf2010-05-06 08:58:33 +00009414 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00009415 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00009416
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009417 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00009418 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009419 // TODO: this should happen for bitfield stores, too.
9420 llvm::APSInt Value(32);
Richard Trieudcb55572016-01-29 23:51:16 +00009421 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009422 if (S.SourceMgr.isInSystemMacro(CC))
9423 return;
9424
John McCall18a2c2c2010-11-09 22:22:12 +00009425 std::string PrettySourceValue = Value.toString(10);
9426 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009427
Ted Kremenek33ba9952011-10-22 02:37:33 +00009428 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9429 S.PDiag(diag::warn_impcast_integer_precision_constant)
9430 << PrettySourceValue << PrettyTargetValue
9431 << E->getType() << T << E->getSourceRange()
9432 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00009433 return;
9434 }
9435
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009436 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
9437 if (S.SourceMgr.isInSystemMacro(CC))
9438 return;
9439
David Blaikie9455da02012-04-12 22:40:54 +00009440 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00009441 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
9442 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00009443 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00009444 }
9445
Richard Trieudcb55572016-01-29 23:51:16 +00009446 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
9447 SourceRange.NonNegative && Source->isSignedIntegerType()) {
9448 // Warn when doing a signed to signed conversion, warn if the positive
9449 // source value is exactly the width of the target type, which will
9450 // cause a negative value to be stored.
9451
9452 llvm::APSInt Value;
Richard Trieufc404c72016-02-05 23:02:38 +00009453 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
9454 !S.SourceMgr.isInSystemMacro(CC)) {
9455 if (isSameWidthConstantConversion(S, E, T, CC)) {
9456 std::string PrettySourceValue = Value.toString(10);
9457 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Richard Trieudcb55572016-01-29 23:51:16 +00009458
Richard Trieufc404c72016-02-05 23:02:38 +00009459 S.DiagRuntimeBehavior(
9460 E->getExprLoc(), E,
9461 S.PDiag(diag::warn_impcast_integer_precision_constant)
9462 << PrettySourceValue << PrettyTargetValue << E->getType() << T
9463 << E->getSourceRange() << clang::SourceRange(CC));
9464 return;
Richard Trieudcb55572016-01-29 23:51:16 +00009465 }
9466 }
Richard Trieufc404c72016-02-05 23:02:38 +00009467
Richard Trieudcb55572016-01-29 23:51:16 +00009468 // Fall through for non-constants to give a sign conversion warning.
9469 }
9470
John McCallcc7e5bf2010-05-06 08:58:33 +00009471 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
9472 (!TargetRange.NonNegative && SourceRange.NonNegative &&
9473 SourceRange.Width == TargetRange.Width)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009474 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009475 return;
9476
John McCallcc7e5bf2010-05-06 08:58:33 +00009477 unsigned DiagID = diag::warn_impcast_integer_sign;
9478
9479 // Traditionally, gcc has warned about this under -Wsign-compare.
9480 // We also want to warn about it in -Wconversion.
9481 // So if -Wconversion is off, use a completely identical diagnostic
9482 // in the sign-compare group.
9483 // The conditional-checking code will
9484 if (ICContext) {
9485 DiagID = diag::warn_impcast_integer_sign_conditional;
9486 *ICContext = true;
9487 }
9488
John McCallacf0ee52010-10-08 02:01:28 +00009489 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00009490 }
9491
Douglas Gregora78f1932011-02-22 02:45:07 +00009492 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00009493 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
9494 // type, to give us better diagnostics.
9495 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00009496 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00009497 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9498 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
9499 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
9500 SourceType = S.Context.getTypeDeclType(Enum);
9501 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
9502 }
9503 }
9504
Douglas Gregora78f1932011-02-22 02:45:07 +00009505 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
9506 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00009507 if (SourceEnum->getDecl()->hasNameForLinkage() &&
9508 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009509 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009510 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009511 return;
9512
Douglas Gregor364f7db2011-03-12 00:14:31 +00009513 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00009514 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009515 }
John McCall263a48b2010-01-04 23:31:57 +00009516}
9517
David Blaikie18e9ac72012-05-15 21:57:38 +00009518void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9519 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009520
9521void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00009522 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009523 E = E->IgnoreParenImpCasts();
9524
9525 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00009526 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009527
John McCallacf0ee52010-10-08 02:01:28 +00009528 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009529 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00009530 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00009531}
9532
David Blaikie18e9ac72012-05-15 21:57:38 +00009533void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9534 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00009535 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00009536
9537 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00009538 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
9539 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00009540
9541 // If -Wconversion would have warned about either of the candidates
9542 // for a signedness conversion to the context type...
9543 if (!Suspicious) return;
9544
9545 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009546 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00009547 return;
9548
John McCallcc7e5bf2010-05-06 08:58:33 +00009549 // ...then check whether it would have warned about either of the
9550 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00009551 if (E->getType() == T) return;
9552
9553 Suspicious = false;
9554 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
9555 E->getType(), CC, &Suspicious);
9556 if (!Suspicious)
9557 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00009558 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00009559}
9560
Richard Trieu65724892014-11-15 06:37:39 +00009561/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9562/// Input argument E is a logical expression.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009563void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
Richard Trieu65724892014-11-15 06:37:39 +00009564 if (S.getLangOpts().Bool)
9565 return;
9566 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
9567}
9568
John McCallcc7e5bf2010-05-06 08:58:33 +00009569/// AnalyzeImplicitConversions - Find and report any interesting
9570/// implicit conversions in the given expression. There are a couple
9571/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00009572void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00009573 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00009574 Expr *E = OrigE->IgnoreParenImpCasts();
9575
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00009576 if (E->isTypeDependent() || E->isValueDependent())
9577 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00009578
John McCallcc7e5bf2010-05-06 08:58:33 +00009579 // For conditional operators, we analyze the arguments as if they
9580 // were being fed directly into the output.
9581 if (isa<ConditionalOperator>(E)) {
9582 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00009583 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009584 return;
9585 }
9586
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009587 // Check implicit argument conversions for function calls.
9588 if (CallExpr *Call = dyn_cast<CallExpr>(E))
9589 CheckImplicitArgumentConversions(S, Call, CC);
9590
John McCallcc7e5bf2010-05-06 08:58:33 +00009591 // Go ahead and check any implicit conversions we might have skipped.
9592 // The non-canonical typecheck is just an optimization;
9593 // CheckImplicitConversion will filter out dead implicit conversions.
9594 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00009595 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009596
9597 // Now continue drilling into this expression.
Richard Smithd7bed4d2015-11-22 02:57:17 +00009598
9599 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
9600 // The bound subexpressions in a PseudoObjectExpr are not reachable
9601 // as transitive children.
9602 // FIXME: Use a more uniform representation for this.
9603 for (auto *SE : POE->semantics())
9604 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
9605 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00009606 }
Richard Smithd7bed4d2015-11-22 02:57:17 +00009607
John McCallcc7e5bf2010-05-06 08:58:33 +00009608 // Skip past explicit casts.
9609 if (isa<ExplicitCastExpr>(E)) {
9610 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00009611 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009612 }
9613
John McCalld2a53122010-11-09 23:24:47 +00009614 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9615 // Do a somewhat different check with comparison operators.
9616 if (BO->isComparisonOp())
9617 return AnalyzeComparison(S, BO);
9618
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009619 // And with simple assignments.
9620 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00009621 return AnalyzeAssignment(S, BO);
9622 }
John McCallcc7e5bf2010-05-06 08:58:33 +00009623
9624 // These break the otherwise-useful invariant below. Fortunately,
9625 // we don't really need to recurse into them, because any internal
9626 // expressions should have been analyzed already when they were
9627 // built into statements.
9628 if (isa<StmtExpr>(E)) return;
9629
9630 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00009631 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00009632
9633 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00009634 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00009635 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00009636 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Benjamin Kramer642f1732015-07-02 21:03:14 +00009637 for (Stmt *SubStmt : E->children()) {
9638 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00009639 if (!ChildExpr)
9640 continue;
9641
Richard Trieu955231d2014-01-25 01:10:35 +00009642 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00009643 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00009644 // Ignore checking string literals that are in logical and operators.
9645 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00009646 continue;
9647 AnalyzeImplicitConversions(S, ChildExpr, CC);
9648 }
Richard Trieu791b86e2014-11-19 06:08:18 +00009649
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009650 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +00009651 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
9652 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00009653 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +00009654
9655 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
9656 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00009657 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009658 }
Richard Trieu791b86e2014-11-19 06:08:18 +00009659
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009660 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
9661 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +00009662 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009663}
9664
9665} // end anonymous namespace
9666
Anastasia Stulova0df4ac32016-11-14 17:39:58 +00009667/// Diagnose integer type and any valid implicit convertion to it.
9668static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
9669 // Taking into account implicit conversions,
9670 // allow any integer.
9671 if (!E->getType()->isIntegerType()) {
9672 S.Diag(E->getLocStart(),
9673 diag::err_opencl_enqueue_kernel_invalid_local_size_type);
9674 return true;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00009675 }
Anastasia Stulova0df4ac32016-11-14 17:39:58 +00009676 // Potentially emit standard warnings for implicit conversions if enabled
9677 // using -Wconversion.
9678 CheckImplicitConversion(S, E, IntT, E->getLocStart());
9679 return false;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00009680}
9681
Richard Trieuc1888e02014-06-28 23:25:37 +00009682// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
9683// Returns true when emitting a warning about taking the address of a reference.
9684static bool CheckForReference(Sema &SemaRef, const Expr *E,
Benjamin Kramer7320b992016-06-15 14:20:56 +00009685 const PartialDiagnostic &PD) {
Richard Trieuc1888e02014-06-28 23:25:37 +00009686 E = E->IgnoreParenImpCasts();
9687
9688 const FunctionDecl *FD = nullptr;
9689
9690 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9691 if (!DRE->getDecl()->getType()->isReferenceType())
9692 return false;
9693 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9694 if (!M->getMemberDecl()->getType()->isReferenceType())
9695 return false;
9696 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +00009697 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +00009698 return false;
9699 FD = Call->getDirectCallee();
9700 } else {
9701 return false;
9702 }
9703
9704 SemaRef.Diag(E->getExprLoc(), PD);
9705
9706 // If possible, point to location of function.
9707 if (FD) {
9708 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
9709 }
9710
9711 return true;
9712}
9713
Richard Trieu4cbff5c2014-08-08 22:41:43 +00009714// Returns true if the SourceLocation is expanded from any macro body.
9715// Returns false if the SourceLocation is invalid, is from not in a macro
9716// expansion, or is from expanded from a top-level macro argument.
9717static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
9718 if (Loc.isInvalid())
9719 return false;
9720
9721 while (Loc.isMacroID()) {
9722 if (SM.isMacroBodyExpansion(Loc))
9723 return true;
9724 Loc = SM.getImmediateMacroCallerLoc(Loc);
9725 }
9726
9727 return false;
9728}
9729
Richard Trieu3bb8b562014-02-26 02:36:06 +00009730/// \brief Diagnose pointers that are always non-null.
9731/// \param E the expression containing the pointer
9732/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
9733/// compared to a null pointer
9734/// \param IsEqual True when the comparison is equal to a null pointer
9735/// \param Range Extra SourceRange to highlight in the diagnostic
9736void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
9737 Expr::NullPointerConstantKind NullKind,
9738 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00009739 if (!E)
9740 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009741
9742 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +00009743 if (E->getExprLoc().isMacroID()) {
9744 const SourceManager &SM = getSourceManager();
9745 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
9746 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +00009747 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +00009748 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00009749 E = E->IgnoreImpCasts();
9750
9751 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
9752
Richard Trieuf7432752014-06-06 21:39:26 +00009753 if (isa<CXXThisExpr>(E)) {
9754 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
9755 : diag::warn_this_bool_conversion;
9756 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
9757 return;
9758 }
9759
Richard Trieu3bb8b562014-02-26 02:36:06 +00009760 bool IsAddressOf = false;
9761
9762 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
9763 if (UO->getOpcode() != UO_AddrOf)
9764 return;
9765 IsAddressOf = true;
9766 E = UO->getSubExpr();
9767 }
9768
Richard Trieuc1888e02014-06-28 23:25:37 +00009769 if (IsAddressOf) {
9770 unsigned DiagID = IsCompare
9771 ? diag::warn_address_of_reference_null_compare
9772 : diag::warn_address_of_reference_bool_conversion;
9773 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
9774 << IsEqual;
9775 if (CheckForReference(*this, E, PD)) {
9776 return;
9777 }
9778 }
9779
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009780 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
9781 bool IsParam = isa<NonNullAttr>(NonnullAttr);
George Burgess IV850269a2015-12-08 22:02:00 +00009782 std::string Str;
9783 llvm::raw_string_ostream S(Str);
9784 E->printPretty(S, nullptr, getPrintingPolicy());
9785 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
9786 : diag::warn_cast_nonnull_to_bool;
9787 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
9788 << E->getSourceRange() << Range << IsEqual;
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009789 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
George Burgess IV850269a2015-12-08 22:02:00 +00009790 };
9791
9792 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
9793 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
9794 if (auto *Callee = Call->getDirectCallee()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009795 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
9796 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +00009797 return;
9798 }
9799 }
9800 }
9801
Richard Trieu3bb8b562014-02-26 02:36:06 +00009802 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +00009803 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009804 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
9805 D = R->getDecl();
9806 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9807 D = M->getMemberDecl();
9808 }
9809
9810 // Weak Decls can be null.
9811 if (!D || D->isWeak())
9812 return;
George Burgess IV850269a2015-12-08 22:02:00 +00009813
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009814 // Check for parameter decl with nonnull attribute
George Burgess IV850269a2015-12-08 22:02:00 +00009815 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
9816 if (getCurFunction() &&
9817 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009818 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
9819 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +00009820 return;
9821 }
9822
9823 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
David Majnemera3debed2016-06-24 05:33:44 +00009824 auto ParamIter = llvm::find(FD->parameters(), PV);
George Burgess IV850269a2015-12-08 22:02:00 +00009825 assert(ParamIter != FD->param_end());
9826 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
9827
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009828 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
9829 if (!NonNull->args_size()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009830 ComplainAboutNonnullParamOrCall(NonNull);
George Burgess IV850269a2015-12-08 22:02:00 +00009831 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009832 }
George Burgess IV850269a2015-12-08 22:02:00 +00009833
9834 for (unsigned ArgNo : NonNull->args()) {
9835 if (ArgNo == ParamNo) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009836 ComplainAboutNonnullParamOrCall(NonNull);
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009837 return;
9838 }
George Burgess IV850269a2015-12-08 22:02:00 +00009839 }
9840 }
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009841 }
9842 }
George Burgess IV850269a2015-12-08 22:02:00 +00009843 }
9844
Richard Trieu3bb8b562014-02-26 02:36:06 +00009845 QualType T = D->getType();
9846 const bool IsArray = T->isArrayType();
9847 const bool IsFunction = T->isFunctionType();
9848
Richard Trieuc1888e02014-06-28 23:25:37 +00009849 // Address of function is used to silence the function warning.
9850 if (IsAddressOf && IsFunction) {
9851 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009852 }
9853
9854 // Found nothing.
9855 if (!IsAddressOf && !IsFunction && !IsArray)
9856 return;
9857
9858 // Pretty print the expression for the diagnostic.
9859 std::string Str;
9860 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +00009861 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +00009862
9863 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
9864 : diag::warn_impcast_pointer_to_bool;
Craig Topperfa1340f2015-12-23 05:44:46 +00009865 enum {
9866 AddressOf,
9867 FunctionPointer,
9868 ArrayPointer
9869 } DiagType;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009870 if (IsAddressOf)
9871 DiagType = AddressOf;
9872 else if (IsFunction)
9873 DiagType = FunctionPointer;
9874 else if (IsArray)
9875 DiagType = ArrayPointer;
9876 else
9877 llvm_unreachable("Could not determine diagnostic.");
9878 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
9879 << Range << IsEqual;
9880
9881 if (!IsFunction)
9882 return;
9883
9884 // Suggest '&' to silence the function warning.
9885 Diag(E->getExprLoc(), diag::note_function_warning_silence)
9886 << FixItHint::CreateInsertion(E->getLocStart(), "&");
9887
9888 // Check to see if '()' fixit should be emitted.
9889 QualType ReturnType;
9890 UnresolvedSet<4> NonTemplateOverloads;
9891 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
9892 if (ReturnType.isNull())
9893 return;
9894
9895 if (IsCompare) {
9896 // There are two cases here. If there is null constant, the only suggest
9897 // for a pointer return type. If the null is 0, then suggest if the return
9898 // type is a pointer or an integer type.
9899 if (!ReturnType->isPointerType()) {
9900 if (NullKind == Expr::NPCK_ZeroExpression ||
9901 NullKind == Expr::NPCK_ZeroLiteral) {
9902 if (!ReturnType->isIntegerType())
9903 return;
9904 } else {
9905 return;
9906 }
9907 }
9908 } else { // !IsCompare
9909 // For function to bool, only suggest if the function pointer has bool
9910 // return type.
9911 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
9912 return;
9913 }
9914 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +00009915 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +00009916}
9917
John McCallcc7e5bf2010-05-06 08:58:33 +00009918/// Diagnoses "dangerous" implicit conversions within the given
9919/// expression (which is a full expression). Implements -Wconversion
9920/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00009921///
9922/// \param CC the "context" location of the implicit conversion, i.e.
9923/// the most location of the syntactic entity requiring the implicit
9924/// conversion
9925void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009926 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00009927 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00009928 return;
9929
9930 // Don't diagnose for value- or type-dependent expressions.
9931 if (E->isTypeDependent() || E->isValueDependent())
9932 return;
9933
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009934 // Check for array bounds violations in cases where the check isn't triggered
9935 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
9936 // ArraySubscriptExpr is on the RHS of a variable initialization.
9937 CheckArrayAccess(E);
9938
John McCallacf0ee52010-10-08 02:01:28 +00009939 // This is not the right CC for (e.g.) a variable initialization.
9940 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009941}
9942
Richard Trieu65724892014-11-15 06:37:39 +00009943/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9944/// Input argument E is a logical expression.
9945void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
9946 ::CheckBoolLikeConversion(*this, E, CC);
9947}
9948
Richard Smith9f7df0c2017-06-26 23:19:32 +00009949/// Diagnose when expression is an integer constant expression and its evaluation
9950/// results in integer overflow
9951void Sema::CheckForIntOverflow (Expr *E) {
9952 // Use a work list to deal with nested struct initializers.
9953 SmallVector<Expr *, 2> Exprs(1, E);
9954
9955 do {
9956 Expr *E = Exprs.pop_back_val();
9957
9958 if (isa<BinaryOperator>(E->IgnoreParenCasts())) {
9959 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
9960 continue;
9961 }
9962
9963 if (auto InitList = dyn_cast<InitListExpr>(E))
9964 Exprs.append(InitList->inits().begin(), InitList->inits().end());
9965
9966 if (isa<ObjCBoxedExpr>(E))
9967 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
9968 } while (!Exprs.empty());
9969}
9970
Richard Smithc406cb72013-01-17 01:17:56 +00009971namespace {
9972/// \brief Visitor for expressions which looks for unsequenced operations on the
9973/// same object.
9974class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00009975 typedef EvaluatedExprVisitor<SequenceChecker> Base;
9976
Richard Smithc406cb72013-01-17 01:17:56 +00009977 /// \brief A tree of sequenced regions within an expression. Two regions are
9978 /// unsequenced if one is an ancestor or a descendent of the other. When we
9979 /// finish processing an expression with sequencing, such as a comma
9980 /// expression, we fold its tree nodes into its parent, since they are
9981 /// unsequenced with respect to nodes we will visit later.
9982 class SequenceTree {
9983 struct Value {
9984 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
9985 unsigned Parent : 31;
Aaron Ballmanaffa1c32016-07-06 18:33:01 +00009986 unsigned Merged : 1;
Richard Smithc406cb72013-01-17 01:17:56 +00009987 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009988 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00009989
9990 public:
9991 /// \brief A region within an expression which may be sequenced with respect
9992 /// to some other region.
9993 class Seq {
9994 explicit Seq(unsigned N) : Index(N) {}
9995 unsigned Index;
9996 friend class SequenceTree;
9997 public:
9998 Seq() : Index(0) {}
9999 };
10000
10001 SequenceTree() { Values.push_back(Value(0)); }
10002 Seq root() const { return Seq(0); }
10003
10004 /// \brief Create a new sequence of operations, which is an unsequenced
10005 /// subset of \p Parent. This sequence of operations is sequenced with
10006 /// respect to other children of \p Parent.
10007 Seq allocate(Seq Parent) {
10008 Values.push_back(Value(Parent.Index));
10009 return Seq(Values.size() - 1);
10010 }
10011
10012 /// \brief Merge a sequence of operations into its parent.
10013 void merge(Seq S) {
10014 Values[S.Index].Merged = true;
10015 }
10016
10017 /// \brief Determine whether two operations are unsequenced. This operation
10018 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
10019 /// should have been merged into its parent as appropriate.
10020 bool isUnsequenced(Seq Cur, Seq Old) {
10021 unsigned C = representative(Cur.Index);
10022 unsigned Target = representative(Old.Index);
10023 while (C >= Target) {
10024 if (C == Target)
10025 return true;
10026 C = Values[C].Parent;
10027 }
10028 return false;
10029 }
10030
10031 private:
10032 /// \brief Pick a representative for a sequence.
10033 unsigned representative(unsigned K) {
10034 if (Values[K].Merged)
10035 // Perform path compression as we go.
10036 return Values[K].Parent = representative(Values[K].Parent);
10037 return K;
10038 }
10039 };
10040
10041 /// An object for which we can track unsequenced uses.
10042 typedef NamedDecl *Object;
10043
10044 /// Different flavors of object usage which we track. We only track the
10045 /// least-sequenced usage of each kind.
10046 enum UsageKind {
10047 /// A read of an object. Multiple unsequenced reads are OK.
10048 UK_Use,
10049 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +000010050 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +000010051 UK_ModAsValue,
10052 /// A modification of an object which is not sequenced before the value
10053 /// computation of the expression, such as n++.
10054 UK_ModAsSideEffect,
10055
10056 UK_Count = UK_ModAsSideEffect + 1
10057 };
10058
10059 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +000010060 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +000010061 Expr *Use;
10062 SequenceTree::Seq Seq;
10063 };
10064
10065 struct UsageInfo {
10066 UsageInfo() : Diagnosed(false) {}
10067 Usage Uses[UK_Count];
10068 /// Have we issued a diagnostic for this variable already?
10069 bool Diagnosed;
10070 };
10071 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
10072
10073 Sema &SemaRef;
10074 /// Sequenced regions within the expression.
10075 SequenceTree Tree;
10076 /// Declaration modifications and references which we have seen.
10077 UsageInfoMap UsageMap;
10078 /// The region we are currently within.
10079 SequenceTree::Seq Region;
10080 /// Filled in with declarations which were modified as a side-effect
10081 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010082 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +000010083 /// Expressions to check later. We defer checking these to reduce
10084 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010085 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +000010086
10087 /// RAII object wrapping the visitation of a sequenced subexpression of an
10088 /// expression. At the end of this process, the side-effects of the evaluation
10089 /// become sequenced with respect to the value computation of the result, so
10090 /// we downgrade any UK_ModAsSideEffect within the evaluation to
10091 /// UK_ModAsValue.
10092 struct SequencedSubexpression {
10093 SequencedSubexpression(SequenceChecker &Self)
10094 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
10095 Self.ModAsSideEffect = &ModAsSideEffect;
10096 }
10097 ~SequencedSubexpression() {
David Majnemerf7e36092016-06-23 00:15:04 +000010098 for (auto &M : llvm::reverse(ModAsSideEffect)) {
10099 UsageInfo &U = Self.UsageMap[M.first];
Richard Smithe8efd992014-12-03 01:05:50 +000010100 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
David Majnemerf7e36092016-06-23 00:15:04 +000010101 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
10102 SideEffectUsage = M.second;
Richard Smithc406cb72013-01-17 01:17:56 +000010103 }
10104 Self.ModAsSideEffect = OldModAsSideEffect;
10105 }
10106
10107 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010108 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
10109 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +000010110 };
10111
Richard Smith40238f02013-06-20 22:21:56 +000010112 /// RAII object wrapping the visitation of a subexpression which we might
10113 /// choose to evaluate as a constant. If any subexpression is evaluated and
10114 /// found to be non-constant, this allows us to suppress the evaluation of
10115 /// the outer expression.
10116 class EvaluationTracker {
10117 public:
10118 EvaluationTracker(SequenceChecker &Self)
10119 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
10120 Self.EvalTracker = this;
10121 }
10122 ~EvaluationTracker() {
10123 Self.EvalTracker = Prev;
10124 if (Prev)
10125 Prev->EvalOK &= EvalOK;
10126 }
10127
10128 bool evaluate(const Expr *E, bool &Result) {
10129 if (!EvalOK || E->isValueDependent())
10130 return false;
10131 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
10132 return EvalOK;
10133 }
10134
10135 private:
10136 SequenceChecker &Self;
10137 EvaluationTracker *Prev;
10138 bool EvalOK;
10139 } *EvalTracker;
10140
Richard Smithc406cb72013-01-17 01:17:56 +000010141 /// \brief Find the object which is produced by the specified expression,
10142 /// if any.
10143 Object getObject(Expr *E, bool Mod) const {
10144 E = E->IgnoreParenCasts();
10145 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
10146 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
10147 return getObject(UO->getSubExpr(), Mod);
10148 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10149 if (BO->getOpcode() == BO_Comma)
10150 return getObject(BO->getRHS(), Mod);
10151 if (Mod && BO->isAssignmentOp())
10152 return getObject(BO->getLHS(), Mod);
10153 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
10154 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
10155 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
10156 return ME->getMemberDecl();
10157 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10158 // FIXME: If this is a reference, map through to its value.
10159 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +000010160 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +000010161 }
10162
10163 /// \brief Note that an object was modified or used by an expression.
10164 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
10165 Usage &U = UI.Uses[UK];
10166 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
10167 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
10168 ModAsSideEffect->push_back(std::make_pair(O, U));
10169 U.Use = Ref;
10170 U.Seq = Region;
10171 }
10172 }
10173 /// \brief Check whether a modification or use conflicts with a prior usage.
10174 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
10175 bool IsModMod) {
10176 if (UI.Diagnosed)
10177 return;
10178
10179 const Usage &U = UI.Uses[OtherKind];
10180 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
10181 return;
10182
10183 Expr *Mod = U.Use;
10184 Expr *ModOrUse = Ref;
10185 if (OtherKind == UK_Use)
10186 std::swap(Mod, ModOrUse);
10187
10188 SemaRef.Diag(Mod->getExprLoc(),
10189 IsModMod ? diag::warn_unsequenced_mod_mod
10190 : diag::warn_unsequenced_mod_use)
10191 << O << SourceRange(ModOrUse->getExprLoc());
10192 UI.Diagnosed = true;
10193 }
10194
10195 void notePreUse(Object O, Expr *Use) {
10196 UsageInfo &U = UsageMap[O];
10197 // Uses conflict with other modifications.
10198 checkUsage(O, U, Use, UK_ModAsValue, false);
10199 }
10200 void notePostUse(Object O, Expr *Use) {
10201 UsageInfo &U = UsageMap[O];
10202 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
10203 addUsage(U, O, Use, UK_Use);
10204 }
10205
10206 void notePreMod(Object O, Expr *Mod) {
10207 UsageInfo &U = UsageMap[O];
10208 // Modifications conflict with other modifications and with uses.
10209 checkUsage(O, U, Mod, UK_ModAsValue, true);
10210 checkUsage(O, U, Mod, UK_Use, false);
10211 }
10212 void notePostMod(Object O, Expr *Use, UsageKind UK) {
10213 UsageInfo &U = UsageMap[O];
10214 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
10215 addUsage(U, O, Use, UK);
10216 }
10217
10218public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010219 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +000010220 : Base(S.Context), SemaRef(S), Region(Tree.root()),
10221 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +000010222 Visit(E);
10223 }
10224
10225 void VisitStmt(Stmt *S) {
10226 // Skip all statements which aren't expressions for now.
10227 }
10228
10229 void VisitExpr(Expr *E) {
10230 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +000010231 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +000010232 }
10233
10234 void VisitCastExpr(CastExpr *E) {
10235 Object O = Object();
10236 if (E->getCastKind() == CK_LValueToRValue)
10237 O = getObject(E->getSubExpr(), false);
10238
10239 if (O)
10240 notePreUse(O, E);
10241 VisitExpr(E);
10242 if (O)
10243 notePostUse(O, E);
10244 }
10245
10246 void VisitBinComma(BinaryOperator *BO) {
10247 // C++11 [expr.comma]p1:
10248 // Every value computation and side effect associated with the left
10249 // expression is sequenced before every value computation and side
10250 // effect associated with the right expression.
10251 SequenceTree::Seq LHS = Tree.allocate(Region);
10252 SequenceTree::Seq RHS = Tree.allocate(Region);
10253 SequenceTree::Seq OldRegion = Region;
10254
10255 {
10256 SequencedSubexpression SeqLHS(*this);
10257 Region = LHS;
10258 Visit(BO->getLHS());
10259 }
10260
10261 Region = RHS;
10262 Visit(BO->getRHS());
10263
10264 Region = OldRegion;
10265
10266 // Forget that LHS and RHS are sequenced. They are both unsequenced
10267 // with respect to other stuff.
10268 Tree.merge(LHS);
10269 Tree.merge(RHS);
10270 }
10271
10272 void VisitBinAssign(BinaryOperator *BO) {
10273 // The modification is sequenced after the value computation of the LHS
10274 // and RHS, so check it before inspecting the operands and update the
10275 // map afterwards.
10276 Object O = getObject(BO->getLHS(), true);
10277 if (!O)
10278 return VisitExpr(BO);
10279
10280 notePreMod(O, BO);
10281
10282 // C++11 [expr.ass]p7:
10283 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
10284 // only once.
10285 //
10286 // Therefore, for a compound assignment operator, O is considered used
10287 // everywhere except within the evaluation of E1 itself.
10288 if (isa<CompoundAssignOperator>(BO))
10289 notePreUse(O, BO);
10290
10291 Visit(BO->getLHS());
10292
10293 if (isa<CompoundAssignOperator>(BO))
10294 notePostUse(O, BO);
10295
10296 Visit(BO->getRHS());
10297
Richard Smith83e37bee2013-06-26 23:16:51 +000010298 // C++11 [expr.ass]p1:
10299 // the assignment is sequenced [...] before the value computation of the
10300 // assignment expression.
10301 // C11 6.5.16/3 has no such rule.
10302 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10303 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000010304 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010305
Richard Smithc406cb72013-01-17 01:17:56 +000010306 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
10307 VisitBinAssign(CAO);
10308 }
10309
10310 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10311 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10312 void VisitUnaryPreIncDec(UnaryOperator *UO) {
10313 Object O = getObject(UO->getSubExpr(), true);
10314 if (!O)
10315 return VisitExpr(UO);
10316
10317 notePreMod(O, UO);
10318 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +000010319 // C++11 [expr.pre.incr]p1:
10320 // the expression ++x is equivalent to x+=1
10321 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10322 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000010323 }
10324
10325 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10326 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10327 void VisitUnaryPostIncDec(UnaryOperator *UO) {
10328 Object O = getObject(UO->getSubExpr(), true);
10329 if (!O)
10330 return VisitExpr(UO);
10331
10332 notePreMod(O, UO);
10333 Visit(UO->getSubExpr());
10334 notePostMod(O, UO, UK_ModAsSideEffect);
10335 }
10336
10337 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
10338 void VisitBinLOr(BinaryOperator *BO) {
10339 // The side-effects of the LHS of an '&&' are sequenced before the
10340 // value computation of the RHS, and hence before the value computation
10341 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
10342 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +000010343 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000010344 {
10345 SequencedSubexpression Sequenced(*this);
10346 Visit(BO->getLHS());
10347 }
10348
10349 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010350 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000010351 if (!Result)
10352 Visit(BO->getRHS());
10353 } else {
10354 // Check for unsequenced operations in the RHS, treating it as an
10355 // entirely separate evaluation.
10356 //
10357 // FIXME: If there are operations in the RHS which are unsequenced
10358 // with respect to operations outside the RHS, and those operations
10359 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +000010360 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000010361 }
Richard Smithc406cb72013-01-17 01:17:56 +000010362 }
10363 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +000010364 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000010365 {
10366 SequencedSubexpression Sequenced(*this);
10367 Visit(BO->getLHS());
10368 }
10369
10370 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010371 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000010372 if (Result)
10373 Visit(BO->getRHS());
10374 } else {
Richard Smithd33f5202013-01-17 23:18:09 +000010375 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000010376 }
Richard Smithc406cb72013-01-17 01:17:56 +000010377 }
10378
10379 // Only visit the condition, unless we can be sure which subexpression will
10380 // be chosen.
10381 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +000010382 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +000010383 {
10384 SequencedSubexpression Sequenced(*this);
10385 Visit(CO->getCond());
10386 }
Richard Smithc406cb72013-01-17 01:17:56 +000010387
10388 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010389 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +000010390 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000010391 else {
Richard Smithd33f5202013-01-17 23:18:09 +000010392 WorkList.push_back(CO->getTrueExpr());
10393 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000010394 }
Richard Smithc406cb72013-01-17 01:17:56 +000010395 }
10396
Richard Smithe3dbfe02013-06-30 10:40:20 +000010397 void VisitCallExpr(CallExpr *CE) {
10398 // C++11 [intro.execution]p15:
10399 // When calling a function [...], every value computation and side effect
10400 // associated with any argument expression, or with the postfix expression
10401 // designating the called function, is sequenced before execution of every
10402 // expression or statement in the body of the function [and thus before
10403 // the value computation of its result].
10404 SequencedSubexpression Sequenced(*this);
10405 Base::VisitCallExpr(CE);
10406
10407 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
10408 }
10409
Richard Smithc406cb72013-01-17 01:17:56 +000010410 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +000010411 // This is a call, so all subexpressions are sequenced before the result.
10412 SequencedSubexpression Sequenced(*this);
10413
Richard Smithc406cb72013-01-17 01:17:56 +000010414 if (!CCE->isListInitialization())
10415 return VisitExpr(CCE);
10416
10417 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010418 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000010419 SequenceTree::Seq Parent = Region;
10420 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
10421 E = CCE->arg_end();
10422 I != E; ++I) {
10423 Region = Tree.allocate(Parent);
10424 Elts.push_back(Region);
10425 Visit(*I);
10426 }
10427
10428 // Forget that the initializers are sequenced.
10429 Region = Parent;
10430 for (unsigned I = 0; I < Elts.size(); ++I)
10431 Tree.merge(Elts[I]);
10432 }
10433
10434 void VisitInitListExpr(InitListExpr *ILE) {
10435 if (!SemaRef.getLangOpts().CPlusPlus11)
10436 return VisitExpr(ILE);
10437
10438 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010439 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000010440 SequenceTree::Seq Parent = Region;
10441 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
10442 Expr *E = ILE->getInit(I);
10443 if (!E) continue;
10444 Region = Tree.allocate(Parent);
10445 Elts.push_back(Region);
10446 Visit(E);
10447 }
10448
10449 // Forget that the initializers are sequenced.
10450 Region = Parent;
10451 for (unsigned I = 0; I < Elts.size(); ++I)
10452 Tree.merge(Elts[I]);
10453 }
10454};
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010455} // end anonymous namespace
Richard Smithc406cb72013-01-17 01:17:56 +000010456
10457void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010458 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +000010459 WorkList.push_back(E);
10460 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +000010461 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +000010462 SequenceChecker(*this, Item, WorkList);
10463 }
Richard Smithc406cb72013-01-17 01:17:56 +000010464}
10465
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010466void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
10467 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +000010468 CheckImplicitConversions(E, CheckLoc);
Richard Trieu71d74d42016-08-05 21:02:34 +000010469 if (!E->isInstantiationDependent())
10470 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010471 if (!IsConstexpr && !E->isValueDependent())
Richard Smith9f7df0c2017-06-26 23:19:32 +000010472 CheckForIntOverflow(E);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000010473 DiagnoseMisalignedMembers();
Richard Smithc406cb72013-01-17 01:17:56 +000010474}
10475
John McCall1f425642010-11-11 03:21:53 +000010476void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
10477 FieldDecl *BitField,
10478 Expr *Init) {
10479 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
10480}
10481
David Majnemer61a5bbf2015-04-07 22:08:51 +000010482static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
10483 SourceLocation Loc) {
10484 if (!PType->isVariablyModifiedType())
10485 return;
10486 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
10487 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
10488 return;
10489 }
David Majnemerdf8f73f2015-04-09 19:53:25 +000010490 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
10491 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
10492 return;
10493 }
David Majnemer61a5bbf2015-04-07 22:08:51 +000010494 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
10495 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
10496 return;
10497 }
10498
10499 const ArrayType *AT = S.Context.getAsArrayType(PType);
10500 if (!AT)
10501 return;
10502
10503 if (AT->getSizeModifier() != ArrayType::Star) {
10504 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
10505 return;
10506 }
10507
10508 S.Diag(Loc, diag::err_array_star_in_function_definition);
10509}
10510
Mike Stump0c2ec772010-01-21 03:59:47 +000010511/// CheckParmsForFunctionDef - Check that the parameters of the given
10512/// function are appropriate for the definition of a function. This
10513/// takes care of any checks that cannot be performed on the
10514/// declaration itself, e.g., that the types of each of the function
10515/// parameters are complete.
David Majnemer59f77922016-06-24 04:05:48 +000010516bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
Douglas Gregorb524d902010-11-01 18:37:59 +000010517 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010518 bool HasInvalidParm = false;
David Majnemer59f77922016-06-24 04:05:48 +000010519 for (ParmVarDecl *Param : Parameters) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010520 // C99 6.7.5.3p4: the parameters in a parameter type list in a
10521 // function declarator that is part of a function definition of
10522 // that function shall not have incomplete type.
10523 //
10524 // This is also C++ [dcl.fct]p6.
10525 if (!Param->isInvalidDecl() &&
10526 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000010527 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010528 Param->setInvalidDecl();
10529 HasInvalidParm = true;
10530 }
10531
10532 // C99 6.9.1p5: If the declarator includes a parameter type list, the
10533 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +000010534 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +000010535 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +000010536 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +000010537 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +000010538 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +000010539
10540 // C99 6.7.5.3p12:
10541 // If the function declarator is not part of a definition of that
10542 // function, parameters may have incomplete type and may use the [*]
10543 // notation in their sequences of declarator specifiers to specify
10544 // variable length array types.
10545 QualType PType = Param->getOriginalType();
David Majnemer61a5bbf2015-04-07 22:08:51 +000010546 // FIXME: This diagnostic should point the '[*]' if source-location
10547 // information is added for it.
10548 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000010549
10550 // MSVC destroys objects passed by value in the callee. Therefore a
10551 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +000010552 // object's destructor. However, we don't perform any direct access check
10553 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +000010554 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
10555 .getCXXABI()
10556 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +000010557 if (!Param->isInvalidDecl()) {
10558 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
10559 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
10560 if (!ClassDecl->isInvalidDecl() &&
10561 !ClassDecl->hasIrrelevantDestructor() &&
10562 !ClassDecl->isDependentContext()) {
10563 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
10564 MarkFunctionReferenced(Param->getLocation(), Destructor);
10565 DiagnoseUseOfDecl(Destructor, Param->getLocation());
10566 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +000010567 }
10568 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000010569 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010570
10571 // Parameters with the pass_object_size attribute only need to be marked
10572 // constant at function definitions. Because we lack information about
10573 // whether we're on a declaration or definition when we're instantiating the
10574 // attribute, we need to check for constness here.
10575 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
10576 if (!Param->getType().isConstQualified())
10577 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
10578 << Attr->getSpelling() << 1;
Mike Stump0c2ec772010-01-21 03:59:47 +000010579 }
10580
10581 return HasInvalidParm;
10582}
John McCall2b5c1b22010-08-12 21:44:57 +000010583
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000010584/// A helper function to get the alignment of a Decl referred to by DeclRefExpr
10585/// or MemberExpr.
10586static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
10587 ASTContext &Context) {
10588 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
10589 return Context.getDeclAlign(DRE->getDecl());
10590
10591 if (const auto *ME = dyn_cast<MemberExpr>(E))
10592 return Context.getDeclAlign(ME->getMemberDecl());
10593
10594 return TypeAlign;
10595}
10596
John McCall2b5c1b22010-08-12 21:44:57 +000010597/// CheckCastAlign - Implements -Wcast-align, which warns when a
10598/// pointer cast increases the alignment requirements.
10599void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
10600 // This is actually a lot of work to potentially be doing on every
10601 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000010602 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +000010603 return;
10604
10605 // Ignore dependent types.
10606 if (T->isDependentType() || Op->getType()->isDependentType())
10607 return;
10608
10609 // Require that the destination be a pointer type.
10610 const PointerType *DestPtr = T->getAs<PointerType>();
10611 if (!DestPtr) return;
10612
10613 // If the destination has alignment 1, we're done.
10614 QualType DestPointee = DestPtr->getPointeeType();
10615 if (DestPointee->isIncompleteType()) return;
10616 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
10617 if (DestAlign.isOne()) return;
10618
10619 // Require that the source be a pointer type.
10620 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
10621 if (!SrcPtr) return;
10622 QualType SrcPointee = SrcPtr->getPointeeType();
10623
10624 // Whitelist casts from cv void*. We already implicitly
10625 // whitelisted casts to cv void*, since they have alignment 1.
10626 // Also whitelist casts involving incomplete types, which implicitly
10627 // includes 'void'.
10628 if (SrcPointee->isIncompleteType()) return;
10629
10630 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000010631
10632 if (auto *CE = dyn_cast<CastExpr>(Op)) {
10633 if (CE->getCastKind() == CK_ArrayToPointerDecay)
10634 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
10635 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
10636 if (UO->getOpcode() == UO_AddrOf)
10637 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
10638 }
10639
John McCall2b5c1b22010-08-12 21:44:57 +000010640 if (SrcAlign >= DestAlign) return;
10641
10642 Diag(TRange.getBegin(), diag::warn_cast_align)
10643 << Op->getType() << T
10644 << static_cast<unsigned>(SrcAlign.getQuantity())
10645 << static_cast<unsigned>(DestAlign.getQuantity())
10646 << TRange << Op->getSourceRange();
10647}
10648
Chandler Carruth28389f02011-08-05 09:10:50 +000010649/// \brief Check whether this array fits the idiom of a size-one tail padded
10650/// array member of a struct.
10651///
10652/// We avoid emitting out-of-bounds access warnings for such arrays as they are
10653/// commonly used to emulate flexible arrays in C89 code.
Benjamin Kramer7320b992016-06-15 14:20:56 +000010654static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
Chandler Carruth28389f02011-08-05 09:10:50 +000010655 const NamedDecl *ND) {
10656 if (Size != 1 || !ND) return false;
10657
10658 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
10659 if (!FD) return false;
10660
10661 // Don't consider sizes resulting from macro expansions or template argument
10662 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +000010663
10664 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000010665 while (TInfo) {
10666 TypeLoc TL = TInfo->getTypeLoc();
10667 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +000010668 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
10669 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000010670 TInfo = TDL->getTypeSourceInfo();
10671 continue;
10672 }
David Blaikie6adc78e2013-02-18 22:06:02 +000010673 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
10674 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +000010675 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
10676 return false;
10677 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +000010678 break;
Sean Callanan06a48a62012-05-04 18:22:53 +000010679 }
Chandler Carruth28389f02011-08-05 09:10:50 +000010680
10681 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +000010682 if (!RD) return false;
10683 if (RD->isUnion()) return false;
10684 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
10685 if (!CRD->isStandardLayout()) return false;
10686 }
Chandler Carruth28389f02011-08-05 09:10:50 +000010687
Benjamin Kramer8c543672011-08-06 03:04:42 +000010688 // See if this is the last field decl in the record.
10689 const Decl *D = FD;
10690 while ((D = D->getNextDeclInContext()))
10691 if (isa<FieldDecl>(D))
10692 return false;
10693 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +000010694}
10695
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010696void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010697 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +000010698 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010699 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010700 if (IndexExpr->isValueDependent())
10701 return;
10702
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000010703 const Type *EffectiveType =
10704 BaseExpr->getType()->getPointeeOrArrayElementType();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010705 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010706 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010707 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010708 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +000010709 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +000010710
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010711 llvm::APSInt index;
Richard Smith0c6124b2015-12-03 01:36:22 +000010712 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
Ted Kremenek64699be2011-02-16 01:57:07 +000010713 return;
Richard Smith13f67182011-12-16 19:31:14 +000010714 if (IndexNegated)
10715 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +000010716
Craig Topperc3ec1492014-05-26 06:22:03 +000010717 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +000010718 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
10719 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +000010720 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +000010721 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +000010722
Ted Kremeneke4b316c2011-02-23 23:06:04 +000010723 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000010724 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +000010725 if (!size.isStrictlyPositive())
10726 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010727
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000010728 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
Nico Weber7c299802011-09-17 22:59:41 +000010729 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010730 // Make sure we're comparing apples to apples when comparing index to size
10731 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
10732 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +000010733 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +000010734 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010735 if (ptrarith_typesize != array_typesize) {
10736 // There's a cast to a different size type involved
10737 uint64_t ratio = array_typesize / ptrarith_typesize;
10738 // TODO: Be smarter about handling cases where array_typesize is not a
10739 // multiple of ptrarith_typesize
10740 if (ptrarith_typesize * ratio == array_typesize)
10741 size *= llvm::APInt(size.getBitWidth(), ratio);
10742 }
10743 }
10744
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010745 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010746 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000010747 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010748 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000010749
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010750 // For array subscripting the index must be less than size, but for pointer
10751 // arithmetic also allow the index (offset) to be equal to size since
10752 // computing the next address after the end of the array is legal and
10753 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010754 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +000010755 return;
10756
10757 // Also don't warn for arrays of size 1 which are members of some
10758 // structure. These are often used to approximate flexible arrays in C89
10759 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010760 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +000010761 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010762
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010763 // Suppress the warning if the subscript expression (as identified by the
10764 // ']' location) and the index expression are both from macro expansions
10765 // within a system header.
10766 if (ASE) {
10767 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
10768 ASE->getRBracketLoc());
10769 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
10770 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
10771 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +000010772 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010773 return;
10774 }
10775 }
10776
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010777 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010778 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010779 DiagID = diag::warn_array_index_exceeds_bounds;
10780
10781 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
10782 PDiag(DiagID) << index.toString(10, true)
10783 << size.toString(10, true)
10784 << (unsigned)size.getLimitedValue(~0U)
10785 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010786 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010787 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010788 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010789 DiagID = diag::warn_ptr_arith_precedes_bounds;
10790 if (index.isNegative()) index = -index;
10791 }
10792
10793 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
10794 PDiag(DiagID) << index.toString(10, true)
10795 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +000010796 }
Chandler Carruth1af88f12011-02-17 21:10:52 +000010797
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000010798 if (!ND) {
10799 // Try harder to find a NamedDecl to point at in the note.
10800 while (const ArraySubscriptExpr *ASE =
10801 dyn_cast<ArraySubscriptExpr>(BaseExpr))
10802 BaseExpr = ASE->getBase()->IgnoreParenCasts();
10803 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
10804 ND = dyn_cast<NamedDecl>(DRE->getDecl());
10805 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
10806 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
10807 }
10808
Chandler Carruth1af88f12011-02-17 21:10:52 +000010809 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010810 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
10811 PDiag(diag::note_array_index_out_of_bounds)
10812 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +000010813}
10814
Ted Kremenekdf26df72011-03-01 18:41:00 +000010815void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010816 int AllowOnePastEnd = 0;
10817 while (expr) {
10818 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +000010819 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010820 case Stmt::ArraySubscriptExprClass: {
10821 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010822 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010823 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +000010824 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010825 }
Alexey Bataev1a3320e2015-08-25 14:24:04 +000010826 case Stmt::OMPArraySectionExprClass: {
10827 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
10828 if (ASE->getLowerBound())
10829 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
10830 /*ASE=*/nullptr, AllowOnePastEnd > 0);
10831 return;
10832 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010833 case Stmt::UnaryOperatorClass: {
10834 // Only unwrap the * and & unary operators
10835 const UnaryOperator *UO = cast<UnaryOperator>(expr);
10836 expr = UO->getSubExpr();
10837 switch (UO->getOpcode()) {
10838 case UO_AddrOf:
10839 AllowOnePastEnd++;
10840 break;
10841 case UO_Deref:
10842 AllowOnePastEnd--;
10843 break;
10844 default:
10845 return;
10846 }
10847 break;
10848 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000010849 case Stmt::ConditionalOperatorClass: {
10850 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
10851 if (const Expr *lhs = cond->getLHS())
10852 CheckArrayAccess(lhs);
10853 if (const Expr *rhs = cond->getRHS())
10854 CheckArrayAccess(rhs);
10855 return;
10856 }
Daniel Marjamaki20a209e2017-02-28 14:53:50 +000010857 case Stmt::CXXOperatorCallExprClass: {
10858 const auto *OCE = cast<CXXOperatorCallExpr>(expr);
10859 for (const auto *Arg : OCE->arguments())
10860 CheckArrayAccess(Arg);
10861 return;
10862 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000010863 default:
10864 return;
10865 }
Peter Collingbourne91147592011-04-15 00:35:48 +000010866 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000010867}
John McCall31168b02011-06-15 23:02:42 +000010868
10869//===--- CHECK: Objective-C retain cycles ----------------------------------//
10870
10871namespace {
10872 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +000010873 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +000010874 VarDecl *Variable;
10875 SourceRange Range;
10876 SourceLocation Loc;
10877 bool Indirect;
10878
10879 void setLocsFrom(Expr *e) {
10880 Loc = e->getExprLoc();
10881 Range = e->getSourceRange();
10882 }
10883 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010884} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +000010885
10886/// Consider whether capturing the given variable can possibly lead to
10887/// a retain cycle.
10888static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +000010889 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +000010890 // lifetime. In MRR, it's captured strongly if the variable is
10891 // __block and has an appropriate type.
10892 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
10893 return false;
10894
10895 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000010896 if (ref)
10897 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +000010898 return true;
10899}
10900
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010901static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +000010902 while (true) {
10903 e = e->IgnoreParens();
10904 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
10905 switch (cast->getCastKind()) {
10906 case CK_BitCast:
10907 case CK_LValueBitCast:
10908 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +000010909 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +000010910 e = cast->getSubExpr();
10911 continue;
10912
John McCall31168b02011-06-15 23:02:42 +000010913 default:
10914 return false;
10915 }
10916 }
10917
10918 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
10919 ObjCIvarDecl *ivar = ref->getDecl();
10920 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
10921 return false;
10922
10923 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010924 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +000010925 return false;
10926
10927 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
10928 owner.Indirect = true;
10929 return true;
10930 }
10931
10932 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
10933 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
10934 if (!var) return false;
10935 return considerVariable(var, ref, owner);
10936 }
10937
John McCall31168b02011-06-15 23:02:42 +000010938 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
10939 if (member->isArrow()) return false;
10940
10941 // Don't count this as an indirect ownership.
10942 e = member->getBase();
10943 continue;
10944 }
10945
John McCallfe96e0b2011-11-06 09:01:30 +000010946 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
10947 // Only pay attention to pseudo-objects on property references.
10948 ObjCPropertyRefExpr *pre
10949 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
10950 ->IgnoreParens());
10951 if (!pre) return false;
10952 if (pre->isImplicitProperty()) return false;
10953 ObjCPropertyDecl *property = pre->getExplicitProperty();
10954 if (!property->isRetaining() &&
10955 !(property->getPropertyIvarDecl() &&
10956 property->getPropertyIvarDecl()->getType()
10957 .getObjCLifetime() == Qualifiers::OCL_Strong))
10958 return false;
10959
10960 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010961 if (pre->isSuperReceiver()) {
10962 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
10963 if (!owner.Variable)
10964 return false;
10965 owner.Loc = pre->getLocation();
10966 owner.Range = pre->getSourceRange();
10967 return true;
10968 }
John McCallfe96e0b2011-11-06 09:01:30 +000010969 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
10970 ->getSourceExpr());
10971 continue;
10972 }
10973
John McCall31168b02011-06-15 23:02:42 +000010974 // Array ivars?
10975
10976 return false;
10977 }
10978}
10979
10980namespace {
10981 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
10982 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
10983 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000010984 Context(Context), Variable(variable), Capturer(nullptr),
10985 VarWillBeReased(false) {}
10986 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +000010987 VarDecl *Variable;
10988 Expr *Capturer;
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000010989 bool VarWillBeReased;
John McCall31168b02011-06-15 23:02:42 +000010990
10991 void VisitDeclRefExpr(DeclRefExpr *ref) {
10992 if (ref->getDecl() == Variable && !Capturer)
10993 Capturer = ref;
10994 }
10995
John McCall31168b02011-06-15 23:02:42 +000010996 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
10997 if (Capturer) return;
10998 Visit(ref->getBase());
10999 if (Capturer && ref->isFreeIvar())
11000 Capturer = ref;
11001 }
11002
11003 void VisitBlockExpr(BlockExpr *block) {
11004 // Look inside nested blocks
11005 if (block->getBlockDecl()->capturesVariable(Variable))
11006 Visit(block->getBlockDecl()->getBody());
11007 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +000011008
11009 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
11010 if (Capturer) return;
11011 if (OVE->getSourceExpr())
11012 Visit(OVE->getSourceExpr());
11013 }
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000011014 void VisitBinaryOperator(BinaryOperator *BinOp) {
11015 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
11016 return;
11017 Expr *LHS = BinOp->getLHS();
11018 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
11019 if (DRE->getDecl() != Variable)
11020 return;
11021 if (Expr *RHS = BinOp->getRHS()) {
11022 RHS = RHS->IgnoreParenCasts();
11023 llvm::APSInt Value;
11024 VarWillBeReased =
11025 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
11026 }
11027 }
11028 }
John McCall31168b02011-06-15 23:02:42 +000011029 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011030} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +000011031
11032/// Check whether the given argument is a block which captures a
11033/// variable.
11034static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
11035 assert(owner.Variable && owner.Loc.isValid());
11036
11037 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +000011038
11039 // Look through [^{...} copy] and Block_copy(^{...}).
11040 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
11041 Selector Cmd = ME->getSelector();
11042 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
11043 e = ME->getInstanceReceiver();
11044 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +000011045 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +000011046 e = e->IgnoreParenCasts();
11047 }
11048 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
11049 if (CE->getNumArgs() == 1) {
11050 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +000011051 if (Fn) {
11052 const IdentifierInfo *FnI = Fn->getIdentifier();
11053 if (FnI && FnI->isStr("_Block_copy")) {
11054 e = CE->getArg(0)->IgnoreParenCasts();
11055 }
11056 }
Jordan Rose67e887c2012-09-17 17:54:30 +000011057 }
11058 }
11059
John McCall31168b02011-06-15 23:02:42 +000011060 BlockExpr *block = dyn_cast<BlockExpr>(e);
11061 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +000011062 return nullptr;
John McCall31168b02011-06-15 23:02:42 +000011063
11064 FindCaptureVisitor visitor(S.Context, owner.Variable);
11065 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000011066 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +000011067}
11068
11069static void diagnoseRetainCycle(Sema &S, Expr *capturer,
11070 RetainCycleOwner &owner) {
11071 assert(capturer);
11072 assert(owner.Variable && owner.Loc.isValid());
11073
11074 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
11075 << owner.Variable << capturer->getSourceRange();
11076 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
11077 << owner.Indirect << owner.Range;
11078}
11079
11080/// Check for a keyword selector that starts with the word 'add' or
11081/// 'set'.
11082static bool isSetterLikeSelector(Selector sel) {
11083 if (sel.isUnarySelector()) return false;
11084
Chris Lattner0e62c1c2011-07-23 10:55:15 +000011085 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +000011086 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +000011087 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +000011088 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +000011089 else if (str.startswith("add")) {
11090 // Specially whitelist 'addOperationWithBlock:'.
11091 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
11092 return false;
11093 str = str.substr(3);
11094 }
John McCall31168b02011-06-15 23:02:42 +000011095 else
11096 return false;
11097
11098 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +000011099 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +000011100}
11101
Benjamin Kramer3a743452015-03-09 15:03:32 +000011102static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
11103 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011104 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
11105 Message->getReceiverInterface(),
11106 NSAPI::ClassId_NSMutableArray);
11107 if (!IsMutableArray) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011108 return None;
11109 }
11110
11111 Selector Sel = Message->getSelector();
11112
11113 Optional<NSAPI::NSArrayMethodKind> MKOpt =
11114 S.NSAPIObj->getNSArrayMethodKind(Sel);
11115 if (!MKOpt) {
11116 return None;
11117 }
11118
11119 NSAPI::NSArrayMethodKind MK = *MKOpt;
11120
11121 switch (MK) {
11122 case NSAPI::NSMutableArr_addObject:
11123 case NSAPI::NSMutableArr_insertObjectAtIndex:
11124 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
11125 return 0;
11126 case NSAPI::NSMutableArr_replaceObjectAtIndex:
11127 return 1;
11128
11129 default:
11130 return None;
11131 }
11132
11133 return None;
11134}
11135
11136static
11137Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
11138 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011139 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
11140 Message->getReceiverInterface(),
11141 NSAPI::ClassId_NSMutableDictionary);
11142 if (!IsMutableDictionary) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011143 return None;
11144 }
11145
11146 Selector Sel = Message->getSelector();
11147
11148 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
11149 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
11150 if (!MKOpt) {
11151 return None;
11152 }
11153
11154 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
11155
11156 switch (MK) {
11157 case NSAPI::NSMutableDict_setObjectForKey:
11158 case NSAPI::NSMutableDict_setValueForKey:
11159 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
11160 return 0;
11161
11162 default:
11163 return None;
11164 }
11165
11166 return None;
11167}
11168
11169static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011170 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
11171 Message->getReceiverInterface(),
11172 NSAPI::ClassId_NSMutableSet);
Alex Denisove1d882c2015-03-04 17:55:52 +000011173
Alex Denisov5dfac812015-08-06 04:51:14 +000011174 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
11175 Message->getReceiverInterface(),
11176 NSAPI::ClassId_NSMutableOrderedSet);
11177 if (!IsMutableSet && !IsMutableOrderedSet) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011178 return None;
11179 }
11180
11181 Selector Sel = Message->getSelector();
11182
11183 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
11184 if (!MKOpt) {
11185 return None;
11186 }
11187
11188 NSAPI::NSSetMethodKind MK = *MKOpt;
11189
11190 switch (MK) {
11191 case NSAPI::NSMutableSet_addObject:
11192 case NSAPI::NSOrderedSet_setObjectAtIndex:
11193 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
11194 case NSAPI::NSOrderedSet_insertObjectAtIndex:
11195 return 0;
11196 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
11197 return 1;
11198 }
11199
11200 return None;
11201}
11202
11203void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
11204 if (!Message->isInstanceMessage()) {
11205 return;
11206 }
11207
11208 Optional<int> ArgOpt;
11209
11210 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
11211 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
11212 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
11213 return;
11214 }
11215
11216 int ArgIndex = *ArgOpt;
11217
Alex Denisove1d882c2015-03-04 17:55:52 +000011218 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
11219 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
11220 Arg = OE->getSourceExpr()->IgnoreImpCasts();
11221 }
11222
Alex Denisov5dfac812015-08-06 04:51:14 +000011223 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011224 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011225 if (ArgRE->isObjCSelfExpr()) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011226 Diag(Message->getSourceRange().getBegin(),
11227 diag::warn_objc_circular_container)
Alex Denisov5dfac812015-08-06 04:51:14 +000011228 << ArgRE->getDecl()->getName() << StringRef("super");
Alex Denisove1d882c2015-03-04 17:55:52 +000011229 }
11230 }
Alex Denisov5dfac812015-08-06 04:51:14 +000011231 } else {
11232 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
11233
11234 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
11235 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
11236 }
11237
11238 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
11239 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
11240 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
11241 ValueDecl *Decl = ReceiverRE->getDecl();
11242 Diag(Message->getSourceRange().getBegin(),
11243 diag::warn_objc_circular_container)
11244 << Decl->getName() << Decl->getName();
11245 if (!ArgRE->isObjCSelfExpr()) {
11246 Diag(Decl->getLocation(),
11247 diag::note_objc_circular_container_declared_here)
11248 << Decl->getName();
11249 }
11250 }
11251 }
11252 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
11253 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
11254 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
11255 ObjCIvarDecl *Decl = IvarRE->getDecl();
11256 Diag(Message->getSourceRange().getBegin(),
11257 diag::warn_objc_circular_container)
11258 << Decl->getName() << Decl->getName();
11259 Diag(Decl->getLocation(),
11260 diag::note_objc_circular_container_declared_here)
11261 << Decl->getName();
11262 }
Alex Denisove1d882c2015-03-04 17:55:52 +000011263 }
11264 }
11265 }
Alex Denisove1d882c2015-03-04 17:55:52 +000011266}
11267
John McCall31168b02011-06-15 23:02:42 +000011268/// Check a message send to see if it's likely to cause a retain cycle.
11269void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
11270 // Only check instance methods whose selector looks like a setter.
11271 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
11272 return;
11273
11274 // Try to find a variable that the receiver is strongly owned by.
11275 RetainCycleOwner owner;
11276 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011277 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +000011278 return;
11279 } else {
11280 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
11281 owner.Variable = getCurMethodDecl()->getSelfDecl();
11282 owner.Loc = msg->getSuperLoc();
11283 owner.Range = msg->getSuperLoc();
11284 }
11285
11286 // Check whether the receiver is captured by any of the arguments.
11287 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
11288 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
11289 return diagnoseRetainCycle(*this, capturer, owner);
11290}
11291
11292/// Check a property assign to see if it's likely to cause a retain cycle.
11293void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
11294 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011295 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +000011296 return;
11297
11298 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
11299 diagnoseRetainCycle(*this, capturer, owner);
11300}
11301
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000011302void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
11303 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +000011304 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000011305 return;
11306
11307 // Because we don't have an expression for the variable, we have to set the
11308 // location explicitly here.
11309 Owner.Loc = Var->getLocation();
11310 Owner.Range = Var->getSourceRange();
11311
11312 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
11313 diagnoseRetainCycle(*this, Capturer, Owner);
11314}
11315
Ted Kremenek9304da92012-12-21 08:04:28 +000011316static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
11317 Expr *RHS, bool isProperty) {
11318 // Check if RHS is an Objective-C object literal, which also can get
11319 // immediately zapped in a weak reference. Note that we explicitly
11320 // allow ObjCStringLiterals, since those are designed to never really die.
11321 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000011322
Ted Kremenek64873352012-12-21 22:46:35 +000011323 // This enum needs to match with the 'select' in
11324 // warn_objc_arc_literal_assign (off-by-1).
11325 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
11326 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
11327 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000011328
11329 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +000011330 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +000011331 << (isProperty ? 0 : 1)
11332 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000011333
11334 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +000011335}
11336
Ted Kremenekc1f014a2012-12-21 19:45:30 +000011337static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
11338 Qualifiers::ObjCLifetime LT,
11339 Expr *RHS, bool isProperty) {
11340 // Strip off any implicit cast added to get to the one ARC-specific.
11341 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
11342 if (cast->getCastKind() == CK_ARCConsumeObject) {
11343 S.Diag(Loc, diag::warn_arc_retained_assign)
11344 << (LT == Qualifiers::OCL_ExplicitNone)
11345 << (isProperty ? 0 : 1)
11346 << RHS->getSourceRange();
11347 return true;
11348 }
11349 RHS = cast->getSubExpr();
11350 }
11351
11352 if (LT == Qualifiers::OCL_Weak &&
11353 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
11354 return true;
11355
11356 return false;
11357}
11358
Ted Kremenekb36234d2012-12-21 08:04:20 +000011359bool Sema::checkUnsafeAssigns(SourceLocation Loc,
11360 QualType LHS, Expr *RHS) {
11361 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
11362
11363 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
11364 return false;
11365
11366 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
11367 return true;
11368
11369 return false;
11370}
11371
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011372void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
11373 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011374 QualType LHSType;
11375 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +000011376 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011377 ObjCPropertyRefExpr *PRE
11378 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
11379 if (PRE && !PRE->isImplicitProperty()) {
11380 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11381 if (PD)
11382 LHSType = PD->getType();
11383 }
11384
11385 if (LHSType.isNull())
11386 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +000011387
11388 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
11389
11390 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000011391 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +000011392 getCurFunction()->markSafeWeakUse(LHS);
11393 }
11394
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011395 if (checkUnsafeAssigns(Loc, LHSType, RHS))
11396 return;
Jordan Rose657b5f42012-09-28 22:21:35 +000011397
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011398 // FIXME. Check for other life times.
11399 if (LT != Qualifiers::OCL_None)
11400 return;
11401
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011402 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011403 if (PRE->isImplicitProperty())
11404 return;
11405 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11406 if (!PD)
11407 return;
11408
Bill Wendling44426052012-12-20 19:22:21 +000011409 unsigned Attributes = PD->getPropertyAttributes();
11410 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011411 // when 'assign' attribute was not explicitly specified
11412 // by user, ignore it and rely on property type itself
11413 // for lifetime info.
11414 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
11415 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
11416 LHSType->isObjCRetainableType())
11417 return;
11418
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011419 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +000011420 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011421 Diag(Loc, diag::warn_arc_retained_property_assign)
11422 << RHS->getSourceRange();
11423 return;
11424 }
11425 RHS = cast->getSubExpr();
11426 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011427 }
Bill Wendling44426052012-12-20 19:22:21 +000011428 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +000011429 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
11430 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +000011431 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011432 }
11433}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011434
11435//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
11436
11437namespace {
11438bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
11439 SourceLocation StmtLoc,
11440 const NullStmt *Body) {
11441 // Do not warn if the body is a macro that expands to nothing, e.g:
11442 //
11443 // #define CALL(x)
11444 // if (condition)
11445 // CALL(0);
11446 //
11447 if (Body->hasLeadingEmptyMacro())
11448 return false;
11449
11450 // Get line numbers of statement and body.
11451 bool StmtLineInvalid;
Dmitri Gribenkoad80af82015-03-15 01:08:23 +000011452 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011453 &StmtLineInvalid);
11454 if (StmtLineInvalid)
11455 return false;
11456
11457 bool BodyLineInvalid;
11458 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
11459 &BodyLineInvalid);
11460 if (BodyLineInvalid)
11461 return false;
11462
11463 // Warn if null statement and body are on the same line.
11464 if (StmtLine != BodyLine)
11465 return false;
11466
11467 return true;
11468}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011469} // end anonymous namespace
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011470
11471void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
11472 const Stmt *Body,
11473 unsigned DiagID) {
11474 // Since this is a syntactic check, don't emit diagnostic for template
11475 // instantiations, this just adds noise.
11476 if (CurrentInstantiationScope)
11477 return;
11478
11479 // The body should be a null statement.
11480 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11481 if (!NBody)
11482 return;
11483
11484 // Do the usual checks.
11485 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11486 return;
11487
11488 Diag(NBody->getSemiLoc(), DiagID);
11489 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11490}
11491
11492void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
11493 const Stmt *PossibleBody) {
11494 assert(!CurrentInstantiationScope); // Ensured by caller
11495
11496 SourceLocation StmtLoc;
11497 const Stmt *Body;
11498 unsigned DiagID;
11499 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
11500 StmtLoc = FS->getRParenLoc();
11501 Body = FS->getBody();
11502 DiagID = diag::warn_empty_for_body;
11503 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
11504 StmtLoc = WS->getCond()->getSourceRange().getEnd();
11505 Body = WS->getBody();
11506 DiagID = diag::warn_empty_while_body;
11507 } else
11508 return; // Neither `for' nor `while'.
11509
11510 // The body should be a null statement.
11511 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11512 if (!NBody)
11513 return;
11514
11515 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000011516 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011517 return;
11518
11519 // Do the usual checks.
11520 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11521 return;
11522
11523 // `for(...);' and `while(...);' are popular idioms, so in order to keep
11524 // noise level low, emit diagnostics only if for/while is followed by a
11525 // CompoundStmt, e.g.:
11526 // for (int i = 0; i < n; i++);
11527 // {
11528 // a(i);
11529 // }
11530 // or if for/while is followed by a statement with more indentation
11531 // than for/while itself:
11532 // for (int i = 0; i < n; i++);
11533 // a(i);
11534 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
11535 if (!ProbableTypo) {
11536 bool BodyColInvalid;
11537 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
11538 PossibleBody->getLocStart(),
11539 &BodyColInvalid);
11540 if (BodyColInvalid)
11541 return;
11542
11543 bool StmtColInvalid;
11544 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
11545 S->getLocStart(),
11546 &StmtColInvalid);
11547 if (StmtColInvalid)
11548 return;
11549
11550 if (BodyCol > StmtCol)
11551 ProbableTypo = true;
11552 }
11553
11554 if (ProbableTypo) {
11555 Diag(NBody->getSemiLoc(), DiagID);
11556 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11557 }
11558}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011559
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011560//===--- CHECK: Warn on self move with std::move. -------------------------===//
11561
11562/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
11563void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
11564 SourceLocation OpLoc) {
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011565 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
11566 return;
11567
Richard Smith51ec0cf2017-02-21 01:17:38 +000011568 if (inTemplateInstantiation())
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011569 return;
11570
11571 // Strip parens and casts away.
11572 LHSExpr = LHSExpr->IgnoreParenImpCasts();
11573 RHSExpr = RHSExpr->IgnoreParenImpCasts();
11574
11575 // Check for a call expression
11576 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
11577 if (!CE || CE->getNumArgs() != 1)
11578 return;
11579
11580 // Check for a call to std::move
11581 const FunctionDecl *FD = CE->getDirectCallee();
11582 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
11583 !FD->getIdentifier()->isStr("move"))
11584 return;
11585
11586 // Get argument from std::move
11587 RHSExpr = CE->getArg(0);
11588
11589 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
11590 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
11591
11592 // Two DeclRefExpr's, check that the decls are the same.
11593 if (LHSDeclRef && RHSDeclRef) {
11594 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11595 return;
11596 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11597 RHSDeclRef->getDecl()->getCanonicalDecl())
11598 return;
11599
11600 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11601 << LHSExpr->getSourceRange()
11602 << RHSExpr->getSourceRange();
11603 return;
11604 }
11605
11606 // Member variables require a different approach to check for self moves.
11607 // MemberExpr's are the same if every nested MemberExpr refers to the same
11608 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
11609 // the base Expr's are CXXThisExpr's.
11610 const Expr *LHSBase = LHSExpr;
11611 const Expr *RHSBase = RHSExpr;
11612 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
11613 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
11614 if (!LHSME || !RHSME)
11615 return;
11616
11617 while (LHSME && RHSME) {
11618 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
11619 RHSME->getMemberDecl()->getCanonicalDecl())
11620 return;
11621
11622 LHSBase = LHSME->getBase();
11623 RHSBase = RHSME->getBase();
11624 LHSME = dyn_cast<MemberExpr>(LHSBase);
11625 RHSME = dyn_cast<MemberExpr>(RHSBase);
11626 }
11627
11628 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
11629 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
11630 if (LHSDeclRef && RHSDeclRef) {
11631 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11632 return;
11633 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11634 RHSDeclRef->getDecl()->getCanonicalDecl())
11635 return;
11636
11637 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11638 << LHSExpr->getSourceRange()
11639 << RHSExpr->getSourceRange();
11640 return;
11641 }
11642
11643 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
11644 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11645 << LHSExpr->getSourceRange()
11646 << RHSExpr->getSourceRange();
11647}
11648
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011649//===--- Layout compatibility ----------------------------------------------//
11650
11651namespace {
11652
11653bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
11654
11655/// \brief Check if two enumeration types are layout-compatible.
11656bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
11657 // C++11 [dcl.enum] p8:
11658 // Two enumeration types are layout-compatible if they have the same
11659 // underlying type.
11660 return ED1->isComplete() && ED2->isComplete() &&
11661 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
11662}
11663
11664/// \brief Check if two fields are layout-compatible.
11665bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
11666 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
11667 return false;
11668
11669 if (Field1->isBitField() != Field2->isBitField())
11670 return false;
11671
11672 if (Field1->isBitField()) {
11673 // Make sure that the bit-fields are the same length.
11674 unsigned Bits1 = Field1->getBitWidthValue(C);
11675 unsigned Bits2 = Field2->getBitWidthValue(C);
11676
11677 if (Bits1 != Bits2)
11678 return false;
11679 }
11680
11681 return true;
11682}
11683
11684/// \brief Check if two standard-layout structs are layout-compatible.
11685/// (C++11 [class.mem] p17)
11686bool isLayoutCompatibleStruct(ASTContext &C,
11687 RecordDecl *RD1,
11688 RecordDecl *RD2) {
11689 // If both records are C++ classes, check that base classes match.
11690 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
11691 // If one of records is a CXXRecordDecl we are in C++ mode,
11692 // thus the other one is a CXXRecordDecl, too.
11693 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
11694 // Check number of base classes.
11695 if (D1CXX->getNumBases() != D2CXX->getNumBases())
11696 return false;
11697
11698 // Check the base classes.
11699 for (CXXRecordDecl::base_class_const_iterator
11700 Base1 = D1CXX->bases_begin(),
11701 BaseEnd1 = D1CXX->bases_end(),
11702 Base2 = D2CXX->bases_begin();
11703 Base1 != BaseEnd1;
11704 ++Base1, ++Base2) {
11705 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
11706 return false;
11707 }
11708 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
11709 // If only RD2 is a C++ class, it should have zero base classes.
11710 if (D2CXX->getNumBases() > 0)
11711 return false;
11712 }
11713
11714 // Check the fields.
11715 RecordDecl::field_iterator Field2 = RD2->field_begin(),
11716 Field2End = RD2->field_end(),
11717 Field1 = RD1->field_begin(),
11718 Field1End = RD1->field_end();
11719 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
11720 if (!isLayoutCompatible(C, *Field1, *Field2))
11721 return false;
11722 }
11723 if (Field1 != Field1End || Field2 != Field2End)
11724 return false;
11725
11726 return true;
11727}
11728
11729/// \brief Check if two standard-layout unions are layout-compatible.
11730/// (C++11 [class.mem] p18)
11731bool isLayoutCompatibleUnion(ASTContext &C,
11732 RecordDecl *RD1,
11733 RecordDecl *RD2) {
11734 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011735 for (auto *Field2 : RD2->fields())
11736 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011737
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011738 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011739 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
11740 I = UnmatchedFields.begin(),
11741 E = UnmatchedFields.end();
11742
11743 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011744 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011745 bool Result = UnmatchedFields.erase(*I);
11746 (void) Result;
11747 assert(Result);
11748 break;
11749 }
11750 }
11751 if (I == E)
11752 return false;
11753 }
11754
11755 return UnmatchedFields.empty();
11756}
11757
11758bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
11759 if (RD1->isUnion() != RD2->isUnion())
11760 return false;
11761
11762 if (RD1->isUnion())
11763 return isLayoutCompatibleUnion(C, RD1, RD2);
11764 else
11765 return isLayoutCompatibleStruct(C, RD1, RD2);
11766}
11767
11768/// \brief Check if two types are layout-compatible in C++11 sense.
11769bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
11770 if (T1.isNull() || T2.isNull())
11771 return false;
11772
11773 // C++11 [basic.types] p11:
11774 // If two types T1 and T2 are the same type, then T1 and T2 are
11775 // layout-compatible types.
11776 if (C.hasSameType(T1, T2))
11777 return true;
11778
11779 T1 = T1.getCanonicalType().getUnqualifiedType();
11780 T2 = T2.getCanonicalType().getUnqualifiedType();
11781
11782 const Type::TypeClass TC1 = T1->getTypeClass();
11783 const Type::TypeClass TC2 = T2->getTypeClass();
11784
11785 if (TC1 != TC2)
11786 return false;
11787
11788 if (TC1 == Type::Enum) {
11789 return isLayoutCompatible(C,
11790 cast<EnumType>(T1)->getDecl(),
11791 cast<EnumType>(T2)->getDecl());
11792 } else if (TC1 == Type::Record) {
11793 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
11794 return false;
11795
11796 return isLayoutCompatible(C,
11797 cast<RecordType>(T1)->getDecl(),
11798 cast<RecordType>(T2)->getDecl());
11799 }
11800
11801 return false;
11802}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011803} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011804
11805//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
11806
11807namespace {
11808/// \brief Given a type tag expression find the type tag itself.
11809///
11810/// \param TypeExpr Type tag expression, as it appears in user's code.
11811///
11812/// \param VD Declaration of an identifier that appears in a type tag.
11813///
11814/// \param MagicValue Type tag magic value.
11815bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
11816 const ValueDecl **VD, uint64_t *MagicValue) {
11817 while(true) {
11818 if (!TypeExpr)
11819 return false;
11820
11821 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
11822
11823 switch (TypeExpr->getStmtClass()) {
11824 case Stmt::UnaryOperatorClass: {
11825 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
11826 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
11827 TypeExpr = UO->getSubExpr();
11828 continue;
11829 }
11830 return false;
11831 }
11832
11833 case Stmt::DeclRefExprClass: {
11834 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
11835 *VD = DRE->getDecl();
11836 return true;
11837 }
11838
11839 case Stmt::IntegerLiteralClass: {
11840 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
11841 llvm::APInt MagicValueAPInt = IL->getValue();
11842 if (MagicValueAPInt.getActiveBits() <= 64) {
11843 *MagicValue = MagicValueAPInt.getZExtValue();
11844 return true;
11845 } else
11846 return false;
11847 }
11848
11849 case Stmt::BinaryConditionalOperatorClass:
11850 case Stmt::ConditionalOperatorClass: {
11851 const AbstractConditionalOperator *ACO =
11852 cast<AbstractConditionalOperator>(TypeExpr);
11853 bool Result;
11854 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
11855 if (Result)
11856 TypeExpr = ACO->getTrueExpr();
11857 else
11858 TypeExpr = ACO->getFalseExpr();
11859 continue;
11860 }
11861 return false;
11862 }
11863
11864 case Stmt::BinaryOperatorClass: {
11865 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
11866 if (BO->getOpcode() == BO_Comma) {
11867 TypeExpr = BO->getRHS();
11868 continue;
11869 }
11870 return false;
11871 }
11872
11873 default:
11874 return false;
11875 }
11876 }
11877}
11878
11879/// \brief Retrieve the C type corresponding to type tag TypeExpr.
11880///
11881/// \param TypeExpr Expression that specifies a type tag.
11882///
11883/// \param MagicValues Registered magic values.
11884///
11885/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
11886/// kind.
11887///
11888/// \param TypeInfo Information about the corresponding C type.
11889///
11890/// \returns true if the corresponding C type was found.
11891bool GetMatchingCType(
11892 const IdentifierInfo *ArgumentKind,
11893 const Expr *TypeExpr, const ASTContext &Ctx,
11894 const llvm::DenseMap<Sema::TypeTagMagicValue,
11895 Sema::TypeTagData> *MagicValues,
11896 bool &FoundWrongKind,
11897 Sema::TypeTagData &TypeInfo) {
11898 FoundWrongKind = false;
11899
11900 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +000011901 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011902
11903 uint64_t MagicValue;
11904
11905 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
11906 return false;
11907
11908 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +000011909 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011910 if (I->getArgumentKind() != ArgumentKind) {
11911 FoundWrongKind = true;
11912 return false;
11913 }
11914 TypeInfo.Type = I->getMatchingCType();
11915 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
11916 TypeInfo.MustBeNull = I->getMustBeNull();
11917 return true;
11918 }
11919 return false;
11920 }
11921
11922 if (!MagicValues)
11923 return false;
11924
11925 llvm::DenseMap<Sema::TypeTagMagicValue,
11926 Sema::TypeTagData>::const_iterator I =
11927 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
11928 if (I == MagicValues->end())
11929 return false;
11930
11931 TypeInfo = I->second;
11932 return true;
11933}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011934} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011935
11936void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
11937 uint64_t MagicValue, QualType Type,
11938 bool LayoutCompatible,
11939 bool MustBeNull) {
11940 if (!TypeTagForDatatypeMagicValues)
11941 TypeTagForDatatypeMagicValues.reset(
11942 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
11943
11944 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
11945 (*TypeTagForDatatypeMagicValues)[Magic] =
11946 TypeTagData(Type, LayoutCompatible, MustBeNull);
11947}
11948
11949namespace {
11950bool IsSameCharType(QualType T1, QualType T2) {
11951 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
11952 if (!BT1)
11953 return false;
11954
11955 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
11956 if (!BT2)
11957 return false;
11958
11959 BuiltinType::Kind T1Kind = BT1->getKind();
11960 BuiltinType::Kind T2Kind = BT2->getKind();
11961
11962 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
11963 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
11964 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
11965 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
11966}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011967} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011968
11969void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
11970 const Expr * const *ExprArgs) {
11971 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
11972 bool IsPointerAttr = Attr->getIsPointer();
11973
11974 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
11975 bool FoundWrongKind;
11976 TypeTagData TypeInfo;
11977 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
11978 TypeTagForDatatypeMagicValues.get(),
11979 FoundWrongKind, TypeInfo)) {
11980 if (FoundWrongKind)
11981 Diag(TypeTagExpr->getExprLoc(),
11982 diag::warn_type_tag_for_datatype_wrong_kind)
11983 << TypeTagExpr->getSourceRange();
11984 return;
11985 }
11986
11987 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
11988 if (IsPointerAttr) {
11989 // Skip implicit cast of pointer to `void *' (as a function argument).
11990 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +000011991 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +000011992 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011993 ArgumentExpr = ICE->getSubExpr();
11994 }
11995 QualType ArgumentType = ArgumentExpr->getType();
11996
11997 // Passing a `void*' pointer shouldn't trigger a warning.
11998 if (IsPointerAttr && ArgumentType->isVoidPointerType())
11999 return;
12000
12001 if (TypeInfo.MustBeNull) {
12002 // Type tag with matching void type requires a null pointer.
12003 if (!ArgumentExpr->isNullPointerConstant(Context,
12004 Expr::NPC_ValueDependentIsNotNull)) {
12005 Diag(ArgumentExpr->getExprLoc(),
12006 diag::warn_type_safety_null_pointer_required)
12007 << ArgumentKind->getName()
12008 << ArgumentExpr->getSourceRange()
12009 << TypeTagExpr->getSourceRange();
12010 }
12011 return;
12012 }
12013
12014 QualType RequiredType = TypeInfo.Type;
12015 if (IsPointerAttr)
12016 RequiredType = Context.getPointerType(RequiredType);
12017
12018 bool mismatch = false;
12019 if (!TypeInfo.LayoutCompatible) {
12020 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
12021
12022 // C++11 [basic.fundamental] p1:
12023 // Plain char, signed char, and unsigned char are three distinct types.
12024 //
12025 // But we treat plain `char' as equivalent to `signed char' or `unsigned
12026 // char' depending on the current char signedness mode.
12027 if (mismatch)
12028 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
12029 RequiredType->getPointeeType())) ||
12030 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
12031 mismatch = false;
12032 } else
12033 if (IsPointerAttr)
12034 mismatch = !isLayoutCompatible(Context,
12035 ArgumentType->getPointeeType(),
12036 RequiredType->getPointeeType());
12037 else
12038 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
12039
12040 if (mismatch)
12041 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +000012042 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012043 << TypeInfo.LayoutCompatible << RequiredType
12044 << ArgumentExpr->getSourceRange()
12045 << TypeTagExpr->getSourceRange();
12046}
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012047
12048void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
12049 CharUnits Alignment) {
12050 MisalignedMembers.emplace_back(E, RD, MD, Alignment);
12051}
12052
12053void Sema::DiagnoseMisalignedMembers() {
12054 for (MisalignedMember &m : MisalignedMembers) {
Alex Lorenz014181e2016-10-05 09:27:48 +000012055 const NamedDecl *ND = m.RD;
12056 if (ND->getName().empty()) {
12057 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
12058 ND = TD;
12059 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012060 Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member)
Alex Lorenz014181e2016-10-05 09:27:48 +000012061 << m.MD << ND << m.E->getSourceRange();
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012062 }
12063 MisalignedMembers.clear();
12064}
12065
12066void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012067 E = E->IgnoreParens();
12068 if (!T->isPointerType() && !T->isIntegerType())
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012069 return;
12070 if (isa<UnaryOperator>(E) &&
12071 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
12072 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
12073 if (isa<MemberExpr>(Op)) {
12074 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
12075 MisalignedMember(Op));
12076 if (MA != MisalignedMembers.end() &&
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012077 (T->isIntegerType() ||
12078 (T->isPointerType() &&
12079 Context.getTypeAlignInChars(T->getPointeeType()) <= MA->Alignment)))
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012080 MisalignedMembers.erase(MA);
12081 }
12082 }
12083}
12084
12085void Sema::RefersToMemberWithReducedAlignment(
12086 Expr *E,
Benjamin Kramera8c3e672016-12-12 14:41:19 +000012087 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
12088 Action) {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012089 const auto *ME = dyn_cast<MemberExpr>(E);
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012090 if (!ME)
12091 return;
12092
Roger Ferrer Ibanez9f963472017-03-13 13:18:21 +000012093 // No need to check expressions with an __unaligned-qualified type.
12094 if (E->getType().getQualifiers().hasUnaligned())
12095 return;
12096
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012097 // For a chain of MemberExpr like "a.b.c.d" this list
12098 // will keep FieldDecl's like [d, c, b].
12099 SmallVector<FieldDecl *, 4> ReverseMemberChain;
12100 const MemberExpr *TopME = nullptr;
12101 bool AnyIsPacked = false;
12102 do {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012103 QualType BaseType = ME->getBase()->getType();
12104 if (ME->isArrow())
12105 BaseType = BaseType->getPointeeType();
12106 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
Olivier Goffart67049f02017-07-07 09:38:59 +000012107 if (RD->isInvalidDecl())
12108 return;
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012109
12110 ValueDecl *MD = ME->getMemberDecl();
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012111 auto *FD = dyn_cast<FieldDecl>(MD);
12112 // We do not care about non-data members.
12113 if (!FD || FD->isInvalidDecl())
12114 return;
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012115
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012116 AnyIsPacked =
12117 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
12118 ReverseMemberChain.push_back(FD);
12119
12120 TopME = ME;
12121 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
12122 } while (ME);
12123 assert(TopME && "We did not compute a topmost MemberExpr!");
12124
12125 // Not the scope of this diagnostic.
12126 if (!AnyIsPacked)
12127 return;
12128
12129 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
12130 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
12131 // TODO: The innermost base of the member expression may be too complicated.
12132 // For now, just disregard these cases. This is left for future
12133 // improvement.
12134 if (!DRE && !isa<CXXThisExpr>(TopBase))
12135 return;
12136
12137 // Alignment expected by the whole expression.
12138 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
12139
12140 // No need to do anything else with this case.
12141 if (ExpectedAlignment.isOne())
12142 return;
12143
12144 // Synthesize offset of the whole access.
12145 CharUnits Offset;
12146 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
12147 I++) {
12148 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
12149 }
12150
12151 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
12152 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
12153 ReverseMemberChain.back()->getParent()->getTypeForDecl());
12154
12155 // The base expression of the innermost MemberExpr may give
12156 // stronger guarantees than the class containing the member.
12157 if (DRE && !TopME->isArrow()) {
12158 const ValueDecl *VD = DRE->getDecl();
12159 if (!VD->getType()->isReferenceType())
12160 CompleteObjectAlignment =
12161 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
12162 }
12163
12164 // Check if the synthesized offset fulfills the alignment.
12165 if (Offset % ExpectedAlignment != 0 ||
12166 // It may fulfill the offset it but the effective alignment may still be
12167 // lower than the expected expression alignment.
12168 CompleteObjectAlignment < ExpectedAlignment) {
12169 // If this happens, we want to determine a sensible culprit of this.
12170 // Intuitively, watching the chain of member expressions from right to
12171 // left, we start with the required alignment (as required by the field
12172 // type) but some packed attribute in that chain has reduced the alignment.
12173 // It may happen that another packed structure increases it again. But if
12174 // we are here such increase has not been enough. So pointing the first
12175 // FieldDecl that either is packed or else its RecordDecl is,
12176 // seems reasonable.
12177 FieldDecl *FD = nullptr;
12178 CharUnits Alignment;
12179 for (FieldDecl *FDI : ReverseMemberChain) {
12180 if (FDI->hasAttr<PackedAttr>() ||
12181 FDI->getParent()->hasAttr<PackedAttr>()) {
12182 FD = FDI;
12183 Alignment = std::min(
12184 Context.getTypeAlignInChars(FD->getType()),
12185 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
12186 break;
12187 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012188 }
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012189 assert(FD && "We did not find a packed FieldDecl!");
12190 Action(E, FD->getParent(), FD, Alignment);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012191 }
12192}
12193
12194void Sema::CheckAddressOfPackedMember(Expr *rhs) {
12195 using namespace std::placeholders;
12196 RefersToMemberWithReducedAlignment(
12197 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
12198 _2, _3, _4));
12199}
12200