blob: 609426b1225d26e8d8f6d777277e1dc92a8b47f6 [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"
Yaxun Liu39195062017-08-04 18:16:31 +000028#include "clang/Basic/SyncScope.h"
Eric Christopher8d0c6212010-04-17 02:26:23 +000029#include "clang/Basic/TargetBuiltins.h"
Nate Begeman4904e322010-06-08 02:47:44 +000030#include "clang/Basic/TargetInfo.h"
Alp Tokerb6cc5922014-05-03 03:45:55 +000031#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
Chandler Carruth3a022472012-12-04 09:13:33 +000032#include "clang/Sema/Initialization.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000033#include "clang/Sema/Lookup.h"
34#include "clang/Sema/ScopeInfo.h"
35#include "clang/Sema/Sema.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000036#include "clang/Sema/SemaInternal.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000037#include "llvm/ADT/STLExtras.h"
Richard Smithd7293d72013-08-05 18:49:43 +000038#include "llvm/ADT/SmallBitVector.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000039#include "llvm/ADT/SmallString.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000040#include "llvm/Support/ConvertUTF.h"
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +000041#include "llvm/Support/Format.h"
42#include "llvm/Support/Locale.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000043#include "llvm/Support/raw_ostream.h"
Eugene Zelenko1ced5092016-02-12 22:53:10 +000044
Chris Lattnerb87b1b32007-08-10 20:18:51 +000045using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000046using namespace sema;
Chris Lattnerb87b1b32007-08-10 20:18:51 +000047
Chris Lattnera26fb342009-02-18 17:49:48 +000048SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
49 unsigned ByteNo) const {
Alp Tokerb6cc5922014-05-03 03:45:55 +000050 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
51 Context.getTargetInfo());
Chris Lattnera26fb342009-02-18 17:49:48 +000052}
53
John McCallbebede42011-02-26 05:39:39 +000054/// Checks that a call expression's argument count is the desired number.
55/// This is useful when doing custom type-checking. Returns true on error.
56static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
57 unsigned argCount = call->getNumArgs();
58 if (argCount == desiredArgCount) return false;
59
60 if (argCount < desiredArgCount)
61 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
62 << 0 /*function call*/ << desiredArgCount << argCount
63 << call->getSourceRange();
64
65 // Highlight all the excess arguments.
66 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
67 call->getArg(argCount - 1)->getLocEnd());
68
69 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
70 << 0 /*function call*/ << desiredArgCount << argCount
71 << call->getArg(1)->getSourceRange();
72}
73
Julien Lerouge4a5b4442012-04-28 17:39:16 +000074/// Check that the first argument to __builtin_annotation is an integer
75/// and the second argument is a non-wide string literal.
76static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
77 if (checkArgCount(S, TheCall, 2))
78 return true;
79
80 // First argument should be an integer.
81 Expr *ValArg = TheCall->getArg(0);
82 QualType Ty = ValArg->getType();
83 if (!Ty->isIntegerType()) {
84 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
85 << ValArg->getSourceRange();
Julien Lerouge5a6b6982011-09-09 22:41:49 +000086 return true;
87 }
Julien Lerouge4a5b4442012-04-28 17:39:16 +000088
89 // Second argument should be a constant string.
90 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
91 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
92 if (!Literal || !Literal->isAscii()) {
93 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
94 << StrArg->getSourceRange();
95 return true;
96 }
97
98 TheCall->setType(Ty);
Julien Lerouge5a6b6982011-09-09 22:41:49 +000099 return false;
100}
101
Reid Kleckner30701ed2017-09-05 20:27:35 +0000102static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
103 // We need at least one argument.
104 if (TheCall->getNumArgs() < 1) {
105 S.Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
106 << 0 << 1 << TheCall->getNumArgs()
107 << TheCall->getCallee()->getSourceRange();
108 return true;
109 }
110
111 // All arguments should be wide string literals.
112 for (Expr *Arg : TheCall->arguments()) {
113 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
114 if (!Literal || !Literal->isWide()) {
115 S.Diag(Arg->getLocStart(), diag::err_msvc_annotation_wide_str)
116 << Arg->getSourceRange();
117 return true;
118 }
119 }
120
121 return false;
122}
123
Richard Smith6cbd65d2013-07-11 02:27:57 +0000124/// Check that the argument to __builtin_addressof is a glvalue, and set the
125/// result type to the corresponding pointer type.
126static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
127 if (checkArgCount(S, TheCall, 1))
128 return true;
129
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000130 ExprResult Arg(TheCall->getArg(0));
Richard Smith6cbd65d2013-07-11 02:27:57 +0000131 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
132 if (ResultType.isNull())
133 return true;
134
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000135 TheCall->setArg(0, Arg.get());
Richard Smith6cbd65d2013-07-11 02:27:57 +0000136 TheCall->setType(ResultType);
137 return false;
138}
139
John McCall03107a42015-10-29 20:48:01 +0000140static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
141 if (checkArgCount(S, TheCall, 3))
142 return true;
143
144 // First two arguments should be integers.
145 for (unsigned I = 0; I < 2; ++I) {
146 Expr *Arg = TheCall->getArg(I);
147 QualType Ty = Arg->getType();
148 if (!Ty->isIntegerType()) {
149 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_int)
150 << Ty << Arg->getSourceRange();
151 return true;
152 }
153 }
154
155 // Third argument should be a pointer to a non-const integer.
156 // IRGen correctly handles volatile, restrict, and address spaces, and
157 // the other qualifiers aren't possible.
158 {
159 Expr *Arg = TheCall->getArg(2);
160 QualType Ty = Arg->getType();
161 const auto *PtrTy = Ty->getAs<PointerType>();
162 if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
163 !PtrTy->getPointeeType().isConstQualified())) {
164 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_ptr_int)
165 << Ty << Arg->getSourceRange();
166 return true;
167 }
168 }
169
170 return false;
171}
172
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000173static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
174 CallExpr *TheCall, unsigned SizeIdx,
175 unsigned DstSizeIdx) {
176 if (TheCall->getNumArgs() <= SizeIdx ||
177 TheCall->getNumArgs() <= DstSizeIdx)
178 return;
179
180 const Expr *SizeArg = TheCall->getArg(SizeIdx);
181 const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
182
183 llvm::APSInt Size, DstSize;
184
185 // find out if both sizes are known at compile time
186 if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
187 !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
188 return;
189
190 if (Size.ule(DstSize))
191 return;
192
193 // confirmed overflow so generate the diagnostic.
194 IdentifierInfo *FnName = FDecl->getIdentifier();
195 SourceLocation SL = TheCall->getLocStart();
196 SourceRange SR = TheCall->getSourceRange();
197
198 S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
199}
200
Peter Collingbournef7706832014-12-12 23:41:25 +0000201static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
202 if (checkArgCount(S, BuiltinCall, 2))
203 return true;
204
205 SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
206 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
207 Expr *Call = BuiltinCall->getArg(0);
208 Expr *Chain = BuiltinCall->getArg(1);
209
210 if (Call->getStmtClass() != Stmt::CallExprClass) {
211 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
212 << Call->getSourceRange();
213 return true;
214 }
215
216 auto CE = cast<CallExpr>(Call);
217 if (CE->getCallee()->getType()->isBlockPointerType()) {
218 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
219 << Call->getSourceRange();
220 return true;
221 }
222
223 const Decl *TargetDecl = CE->getCalleeDecl();
224 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
225 if (FD->getBuiltinID()) {
226 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
227 << Call->getSourceRange();
228 return true;
229 }
230
231 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
232 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
233 << Call->getSourceRange();
234 return true;
235 }
236
237 ExprResult ChainResult = S.UsualUnaryConversions(Chain);
238 if (ChainResult.isInvalid())
239 return true;
240 if (!ChainResult.get()->getType()->isPointerType()) {
241 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
242 << Chain->getSourceRange();
243 return true;
244 }
245
David Majnemerced8bdf2015-02-25 17:36:15 +0000246 QualType ReturnTy = CE->getCallReturnType(S.Context);
Peter Collingbournef7706832014-12-12 23:41:25 +0000247 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
248 QualType BuiltinTy = S.Context.getFunctionType(
249 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
250 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
251
252 Builtin =
253 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
254
255 BuiltinCall->setType(CE->getType());
256 BuiltinCall->setValueKind(CE->getValueKind());
257 BuiltinCall->setObjectKind(CE->getObjectKind());
258 BuiltinCall->setCallee(Builtin);
259 BuiltinCall->setArg(1, ChainResult.get());
260
261 return false;
262}
263
Reid Kleckner1d59f992015-01-22 01:36:17 +0000264static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
265 Scope::ScopeFlags NeededScopeFlags,
266 unsigned DiagID) {
267 // Scopes aren't available during instantiation. Fortunately, builtin
268 // functions cannot be template args so they cannot be formed through template
269 // instantiation. Therefore checking once during the parse is sufficient.
Richard Smith51ec0cf2017-02-21 01:17:38 +0000270 if (SemaRef.inTemplateInstantiation())
Reid Kleckner1d59f992015-01-22 01:36:17 +0000271 return false;
272
273 Scope *S = SemaRef.getCurScope();
274 while (S && !S->isSEHExceptScope())
275 S = S->getParent();
276 if (!S || !(S->getFlags() & NeededScopeFlags)) {
277 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
278 SemaRef.Diag(TheCall->getExprLoc(), DiagID)
279 << DRE->getDecl()->getIdentifier();
280 return true;
281 }
282
283 return false;
284}
285
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000286static inline bool isBlockPointer(Expr *Arg) {
287 return Arg->getType()->isBlockPointerType();
288}
289
290/// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
291/// void*, which is a requirement of device side enqueue.
292static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
293 const BlockPointerType *BPT =
294 cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
295 ArrayRef<QualType> Params =
296 BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes();
297 unsigned ArgCounter = 0;
298 bool IllegalParams = false;
299 // Iterate through the block parameters until either one is found that is not
300 // a local void*, or the block is valid.
301 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
302 I != E; ++I, ++ArgCounter) {
303 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
304 (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
305 LangAS::opencl_local) {
306 // Get the location of the error. If a block literal has been passed
307 // (BlockExpr) then we can point straight to the offending argument,
308 // else we just point to the variable reference.
309 SourceLocation ErrorLoc;
310 if (isa<BlockExpr>(BlockArg)) {
311 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
312 ErrorLoc = BD->getParamDecl(ArgCounter)->getLocStart();
313 } else if (isa<DeclRefExpr>(BlockArg)) {
314 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getLocStart();
315 }
316 S.Diag(ErrorLoc,
317 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
318 IllegalParams = true;
319 }
320 }
321
322 return IllegalParams;
323}
324
Joey Gouly84ae3362017-07-31 15:15:59 +0000325static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
326 if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) {
327 S.Diag(Call->getLocStart(), diag::err_opencl_requires_extension)
328 << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
329 return true;
330 }
331 return false;
332}
333
Joey Goulyfa76b492017-08-01 13:27:09 +0000334static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
335 if (checkArgCount(S, TheCall, 2))
336 return true;
337
338 if (checkOpenCLSubgroupExt(S, TheCall))
339 return true;
340
341 // First argument is an ndrange_t type.
342 Expr *NDRangeArg = TheCall->getArg(0);
343 if (NDRangeArg->getType().getAsString() != "ndrange_t") {
344 S.Diag(NDRangeArg->getLocStart(),
345 diag::err_opencl_builtin_expected_type)
346 << TheCall->getDirectCallee() << "'ndrange_t'";
347 return true;
348 }
349
350 Expr *BlockArg = TheCall->getArg(1);
351 if (!isBlockPointer(BlockArg)) {
352 S.Diag(BlockArg->getLocStart(),
353 diag::err_opencl_builtin_expected_type)
354 << TheCall->getDirectCallee() << "block";
355 return true;
356 }
357 return checkOpenCLBlockArgs(S, BlockArg);
358}
359
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000360/// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
361/// get_kernel_work_group_size
362/// and get_kernel_preferred_work_group_size_multiple builtin functions.
363static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
364 if (checkArgCount(S, TheCall, 1))
365 return true;
366
367 Expr *BlockArg = TheCall->getArg(0);
368 if (!isBlockPointer(BlockArg)) {
369 S.Diag(BlockArg->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000370 diag::err_opencl_builtin_expected_type)
371 << TheCall->getDirectCallee() << "block";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000372 return true;
373 }
374 return checkOpenCLBlockArgs(S, BlockArg);
375}
376
Simon Pilgrim2c518802017-03-30 14:13:19 +0000377/// Diagnose integer type and any valid implicit conversion to it.
Anastasia Stulova0df4ac32016-11-14 17:39:58 +0000378static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
379 const QualType &IntType);
380
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000381static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
Anastasia Stulova0df4ac32016-11-14 17:39:58 +0000382 unsigned Start, unsigned End) {
383 bool IllegalParams = false;
384 for (unsigned I = Start; I <= End; ++I)
385 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
386 S.Context.getSizeType());
387 return IllegalParams;
388}
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000389
390/// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
391/// 'local void*' parameter of passed block.
392static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
393 Expr *BlockArg,
394 unsigned NumNonVarArgs) {
395 const BlockPointerType *BPT =
396 cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
397 unsigned NumBlockParams =
398 BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams();
399 unsigned TotalNumArgs = TheCall->getNumArgs();
400
401 // For each argument passed to the block, a corresponding uint needs to
402 // be passed to describe the size of the local memory.
403 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
404 S.Diag(TheCall->getLocStart(),
405 diag::err_opencl_enqueue_kernel_local_size_args);
406 return true;
407 }
408
409 // Check that the sizes of the local memory are specified by integers.
410 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
411 TotalNumArgs - 1);
412}
413
414/// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
415/// overload formats specified in Table 6.13.17.1.
416/// int enqueue_kernel(queue_t queue,
417/// kernel_enqueue_flags_t flags,
418/// const ndrange_t ndrange,
419/// void (^block)(void))
420/// int enqueue_kernel(queue_t queue,
421/// kernel_enqueue_flags_t flags,
422/// const ndrange_t ndrange,
423/// uint num_events_in_wait_list,
424/// clk_event_t *event_wait_list,
425/// clk_event_t *event_ret,
426/// void (^block)(void))
427/// int enqueue_kernel(queue_t queue,
428/// kernel_enqueue_flags_t flags,
429/// const ndrange_t ndrange,
430/// void (^block)(local void*, ...),
431/// uint size0, ...)
432/// int enqueue_kernel(queue_t queue,
433/// kernel_enqueue_flags_t flags,
434/// const ndrange_t ndrange,
435/// uint num_events_in_wait_list,
436/// clk_event_t *event_wait_list,
437/// clk_event_t *event_ret,
438/// void (^block)(local void*, ...),
439/// uint size0, ...)
440static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
441 unsigned NumArgs = TheCall->getNumArgs();
442
443 if (NumArgs < 4) {
444 S.Diag(TheCall->getLocStart(), diag::err_typecheck_call_too_few_args);
445 return true;
446 }
447
448 Expr *Arg0 = TheCall->getArg(0);
449 Expr *Arg1 = TheCall->getArg(1);
450 Expr *Arg2 = TheCall->getArg(2);
451 Expr *Arg3 = TheCall->getArg(3);
452
453 // First argument always needs to be a queue_t type.
454 if (!Arg0->getType()->isQueueT()) {
455 S.Diag(TheCall->getArg(0)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000456 diag::err_opencl_builtin_expected_type)
457 << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000458 return true;
459 }
460
461 // Second argument always needs to be a kernel_enqueue_flags_t enum value.
462 if (!Arg1->getType()->isIntegerType()) {
463 S.Diag(TheCall->getArg(1)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000464 diag::err_opencl_builtin_expected_type)
465 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000466 return true;
467 }
468
469 // Third argument is always an ndrange_t type.
Anastasia Stulovab42f3c02017-04-21 15:13:24 +0000470 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000471 S.Diag(TheCall->getArg(2)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000472 diag::err_opencl_builtin_expected_type)
473 << TheCall->getDirectCallee() << "'ndrange_t'";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000474 return true;
475 }
476
477 // With four arguments, there is only one form that the function could be
478 // called in: no events and no variable arguments.
479 if (NumArgs == 4) {
480 // check that the last argument is the right block type.
481 if (!isBlockPointer(Arg3)) {
Joey Gouly6b03d952017-07-04 11:50:23 +0000482 S.Diag(Arg3->getLocStart(), diag::err_opencl_builtin_expected_type)
483 << TheCall->getDirectCallee() << "block";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000484 return true;
485 }
486 // we have a block type, check the prototype
487 const BlockPointerType *BPT =
488 cast<BlockPointerType>(Arg3->getType().getCanonicalType());
489 if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) {
490 S.Diag(Arg3->getLocStart(),
491 diag::err_opencl_enqueue_kernel_blocks_no_args);
492 return true;
493 }
494 return false;
495 }
496 // we can have block + varargs.
497 if (isBlockPointer(Arg3))
498 return (checkOpenCLBlockArgs(S, Arg3) ||
499 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
500 // last two cases with either exactly 7 args or 7 args and varargs.
501 if (NumArgs >= 7) {
502 // check common block argument.
503 Expr *Arg6 = TheCall->getArg(6);
504 if (!isBlockPointer(Arg6)) {
Joey Gouly6b03d952017-07-04 11:50:23 +0000505 S.Diag(Arg6->getLocStart(), diag::err_opencl_builtin_expected_type)
506 << TheCall->getDirectCallee() << "block";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000507 return true;
508 }
509 if (checkOpenCLBlockArgs(S, Arg6))
510 return true;
511
512 // Forth argument has to be any integer type.
513 if (!Arg3->getType()->isIntegerType()) {
514 S.Diag(TheCall->getArg(3)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000515 diag::err_opencl_builtin_expected_type)
516 << TheCall->getDirectCallee() << "integer";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000517 return true;
518 }
519 // check remaining common arguments.
520 Expr *Arg4 = TheCall->getArg(4);
521 Expr *Arg5 = TheCall->getArg(5);
522
Anastasia Stulova2b461202016-11-14 15:34:01 +0000523 // Fifth argument is always passed as a pointer to clk_event_t.
524 if (!Arg4->isNullPointerConstant(S.Context,
525 Expr::NPC_ValueDependentIsNotNull) &&
526 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000527 S.Diag(TheCall->getArg(4)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000528 diag::err_opencl_builtin_expected_type)
529 << TheCall->getDirectCallee()
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000530 << S.Context.getPointerType(S.Context.OCLClkEventTy);
531 return true;
532 }
533
Anastasia Stulova2b461202016-11-14 15:34:01 +0000534 // Sixth argument is always passed as a pointer to clk_event_t.
535 if (!Arg5->isNullPointerConstant(S.Context,
536 Expr::NPC_ValueDependentIsNotNull) &&
537 !(Arg5->getType()->isPointerType() &&
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000538 Arg5->getType()->getPointeeType()->isClkEventT())) {
539 S.Diag(TheCall->getArg(5)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000540 diag::err_opencl_builtin_expected_type)
541 << TheCall->getDirectCallee()
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000542 << S.Context.getPointerType(S.Context.OCLClkEventTy);
543 return true;
544 }
545
546 if (NumArgs == 7)
547 return false;
548
549 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
550 }
551
552 // None of the specific case has been detected, give generic error
553 S.Diag(TheCall->getLocStart(),
554 diag::err_opencl_enqueue_kernel_incorrect_args);
555 return true;
556}
557
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000558/// Returns OpenCL access qual.
Xiuli Pan11e13f62016-02-26 03:13:03 +0000559static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
Xiuli Pan11e13f62016-02-26 03:13:03 +0000560 return D->getAttr<OpenCLAccessAttr>();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000561}
562
563/// Returns true if pipe element type is different from the pointer.
564static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
565 const Expr *Arg0 = Call->getArg(0);
566 // First argument type should always be pipe.
567 if (!Arg0->getType()->isPipeType()) {
568 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000569 << Call->getDirectCallee() << Arg0->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000570 return true;
571 }
Xiuli Pan11e13f62016-02-26 03:13:03 +0000572 OpenCLAccessAttr *AccessQual =
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000573 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
574 // Validates the access qualifier is compatible with the call.
575 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
576 // read_only and write_only, and assumed to be read_only if no qualifier is
577 // specified.
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000578 switch (Call->getDirectCallee()->getBuiltinID()) {
579 case Builtin::BIread_pipe:
580 case Builtin::BIreserve_read_pipe:
581 case Builtin::BIcommit_read_pipe:
582 case Builtin::BIwork_group_reserve_read_pipe:
583 case Builtin::BIsub_group_reserve_read_pipe:
584 case Builtin::BIwork_group_commit_read_pipe:
585 case Builtin::BIsub_group_commit_read_pipe:
586 if (!(!AccessQual || AccessQual->isReadOnly())) {
587 S.Diag(Arg0->getLocStart(),
588 diag::err_opencl_builtin_pipe_invalid_access_modifier)
589 << "read_only" << Arg0->getSourceRange();
590 return true;
591 }
592 break;
593 case Builtin::BIwrite_pipe:
594 case Builtin::BIreserve_write_pipe:
595 case Builtin::BIcommit_write_pipe:
596 case Builtin::BIwork_group_reserve_write_pipe:
597 case Builtin::BIsub_group_reserve_write_pipe:
598 case Builtin::BIwork_group_commit_write_pipe:
599 case Builtin::BIsub_group_commit_write_pipe:
600 if (!(AccessQual && AccessQual->isWriteOnly())) {
601 S.Diag(Arg0->getLocStart(),
602 diag::err_opencl_builtin_pipe_invalid_access_modifier)
603 << "write_only" << Arg0->getSourceRange();
604 return true;
605 }
606 break;
607 default:
608 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000609 }
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000610 return false;
611}
612
613/// Returns true if pipe element type is different from the pointer.
614static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
615 const Expr *Arg0 = Call->getArg(0);
616 const Expr *ArgIdx = Call->getArg(Idx);
617 const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000618 const QualType EltTy = PipeTy->getElementType();
619 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000620 // The Idx argument should be a pointer and the type of the pointer and
621 // the type of pipe element should also be the same.
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000622 if (!ArgTy ||
623 !S.Context.hasSameType(
624 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000625 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000626 << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000627 << ArgIdx->getType() << ArgIdx->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000628 return true;
629 }
630 return false;
631}
632
633// \brief Performs semantic analysis for the read/write_pipe call.
634// \param S Reference to the semantic analyzer.
635// \param Call A pointer to the builtin call.
636// \return True if a semantic error has been found, false otherwise.
637static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000638 // OpenCL v2.0 s6.13.16.2 - The built-in read/write
639 // functions have two forms.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000640 switch (Call->getNumArgs()) {
641 case 2: {
642 if (checkOpenCLPipeArg(S, Call))
643 return true;
644 // The call with 2 arguments should be
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000645 // read/write_pipe(pipe T, T*).
646 // Check packet type T.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000647 if (checkOpenCLPipePacketType(S, Call, 1))
648 return true;
649 } break;
650
651 case 4: {
652 if (checkOpenCLPipeArg(S, Call))
653 return true;
654 // The call with 4 arguments should be
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000655 // read/write_pipe(pipe T, reserve_id_t, uint, T*).
656 // Check reserve_id_t.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000657 if (!Call->getArg(1)->getType()->isReserveIDT()) {
658 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000659 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000660 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000661 return true;
662 }
663
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000664 // Check the index.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000665 const Expr *Arg2 = Call->getArg(2);
666 if (!Arg2->getType()->isIntegerType() &&
667 !Arg2->getType()->isUnsignedIntegerType()) {
668 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000669 << Call->getDirectCallee() << S.Context.UnsignedIntTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000670 << Arg2->getType() << Arg2->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000671 return true;
672 }
673
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000674 // Check packet type T.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000675 if (checkOpenCLPipePacketType(S, Call, 3))
676 return true;
677 } break;
678 default:
679 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000680 << Call->getDirectCallee() << Call->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000681 return true;
682 }
683
684 return false;
685}
686
687// \brief Performs a semantic analysis on the {work_group_/sub_group_
688// /_}reserve_{read/write}_pipe
689// \param S Reference to the semantic analyzer.
690// \param Call The call to the builtin function to be analyzed.
691// \return True if a semantic error was found, false otherwise.
692static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
693 if (checkArgCount(S, Call, 2))
694 return true;
695
696 if (checkOpenCLPipeArg(S, Call))
697 return true;
698
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000699 // Check the reserve size.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000700 if (!Call->getArg(1)->getType()->isIntegerType() &&
701 !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
702 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000703 << Call->getDirectCallee() << S.Context.UnsignedIntTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000704 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000705 return true;
706 }
707
Joey Gouly922ca232017-08-09 14:52:47 +0000708 // Since return type of reserve_read/write_pipe built-in function is
709 // reserve_id_t, which is not defined in the builtin def file , we used int
710 // as return type and need to override the return type of these functions.
711 Call->setType(S.Context.OCLReserveIDTy);
712
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000713 return false;
714}
715
716// \brief Performs a semantic analysis on {work_group_/sub_group_
717// /_}commit_{read/write}_pipe
718// \param S Reference to the semantic analyzer.
719// \param Call The call to the builtin function to be analyzed.
720// \return True if a semantic error was found, false otherwise.
721static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
722 if (checkArgCount(S, Call, 2))
723 return true;
724
725 if (checkOpenCLPipeArg(S, Call))
726 return true;
727
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000728 // Check reserve_id_t.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000729 if (!Call->getArg(1)->getType()->isReserveIDT()) {
730 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000731 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000732 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000733 return true;
734 }
735
736 return false;
737}
738
739// \brief Performs a semantic analysis on the call to built-in Pipe
740// Query Functions.
741// \param S Reference to the semantic analyzer.
742// \param Call The call to the builtin function to be analyzed.
743// \return True if a semantic error was found, false otherwise.
744static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
745 if (checkArgCount(S, Call, 1))
746 return true;
747
748 if (!Call->getArg(0)->getType()->isPipeType()) {
749 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000750 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000751 return true;
752 }
753
754 return false;
755}
Anastasia Stulova7f8d6dc2016-07-04 16:07:18 +0000756// \brief OpenCL v2.0 s6.13.9 - Address space qualifier functions.
Yaxun Liuf7449a12016-05-20 19:54:38 +0000757// \brief Performs semantic analysis for the to_global/local/private call.
758// \param S Reference to the semantic analyzer.
759// \param BuiltinID ID of the builtin function.
760// \param Call A pointer to the builtin call.
761// \return True if a semantic error has been found, false otherwise.
762static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
763 CallExpr *Call) {
Yaxun Liuf7449a12016-05-20 19:54:38 +0000764 if (Call->getNumArgs() != 1) {
765 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_arg_num)
766 << Call->getDirectCallee() << Call->getSourceRange();
767 return true;
768 }
769
770 auto RT = Call->getArg(0)->getType();
771 if (!RT->isPointerType() || RT->getPointeeType()
772 .getAddressSpace() == LangAS::opencl_constant) {
773 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg)
774 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
775 return true;
776 }
777
778 RT = RT->getPointeeType();
779 auto Qual = RT.getQualifiers();
780 switch (BuiltinID) {
781 case Builtin::BIto_global:
782 Qual.setAddressSpace(LangAS::opencl_global);
783 break;
784 case Builtin::BIto_local:
785 Qual.setAddressSpace(LangAS::opencl_local);
786 break;
787 default:
788 Qual.removeAddressSpace();
789 }
790 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
791 RT.getUnqualifiedType(), Qual)));
792
793 return false;
794}
795
John McCalldadc5752010-08-24 06:29:42 +0000796ExprResult
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000797Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
798 CallExpr *TheCall) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000799 ExprResult TheCallResult(TheCall);
Douglas Gregorae2fbad2008-11-17 20:34:05 +0000800
Chris Lattner3be167f2010-10-01 23:23:24 +0000801 // Find out if any arguments are required to be integer constant expressions.
802 unsigned ICEArguments = 0;
803 ASTContext::GetBuiltinTypeError Error;
804 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
805 if (Error != ASTContext::GE_None)
806 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
807
808 // If any arguments are required to be ICE's, check and diagnose.
809 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
810 // Skip arguments not required to be ICE's.
811 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
812
813 llvm::APSInt Result;
814 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
815 return true;
816 ICEArguments &= ~(1 << ArgNo);
817 }
818
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000819 switch (BuiltinID) {
Chris Lattner43be2e62007-12-19 23:59:04 +0000820 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner08464942007-12-28 05:29:59 +0000821 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner2da14fb2007-12-20 00:26:33 +0000822 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner6436fb62009-02-18 06:01:06 +0000823 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000824 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000825 break;
Martin Storsjo022e7822017-07-17 20:49:45 +0000826 case Builtin::BI__builtin_ms_va_start:
Ted Kremeneka174c522008-07-09 17:58:53 +0000827 case Builtin::BI__builtin_stdarg_start:
Chris Lattner43be2e62007-12-19 23:59:04 +0000828 case Builtin::BI__builtin_va_start:
Reid Kleckner2b0fa122017-05-02 20:10:03 +0000829 if (SemaBuiltinVAStart(BuiltinID, TheCall))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000830 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000831 break;
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000832 case Builtin::BI__va_start: {
833 switch (Context.getTargetInfo().getTriple().getArch()) {
834 case llvm::Triple::arm:
835 case llvm::Triple::thumb:
Saleem Abdulrasool3450aa72017-09-26 20:12:04 +0000836 if (SemaBuiltinVAStartARMMicrosoft(TheCall))
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000837 return ExprError();
838 break;
839 default:
Reid Kleckner2b0fa122017-05-02 20:10:03 +0000840 if (SemaBuiltinVAStart(BuiltinID, TheCall))
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000841 return ExprError();
842 break;
843 }
844 break;
845 }
Chris Lattner2da14fb2007-12-20 00:26:33 +0000846 case Builtin::BI__builtin_isgreater:
847 case Builtin::BI__builtin_isgreaterequal:
848 case Builtin::BI__builtin_isless:
849 case Builtin::BI__builtin_islessequal:
850 case Builtin::BI__builtin_islessgreater:
851 case Builtin::BI__builtin_isunordered:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000852 if (SemaBuiltinUnorderedCompare(TheCall))
853 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000854 break;
Benjamin Kramer634fc102010-02-15 22:42:31 +0000855 case Builtin::BI__builtin_fpclassify:
856 if (SemaBuiltinFPClassification(TheCall, 6))
857 return ExprError();
858 break;
Eli Friedman7e4faac2009-08-31 20:06:00 +0000859 case Builtin::BI__builtin_isfinite:
860 case Builtin::BI__builtin_isinf:
861 case Builtin::BI__builtin_isinf_sign:
862 case Builtin::BI__builtin_isnan:
863 case Builtin::BI__builtin_isnormal:
Benjamin Kramer64aae502010-02-16 10:07:31 +0000864 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman7e4faac2009-08-31 20:06:00 +0000865 return ExprError();
866 break;
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000867 case Builtin::BI__builtin_shufflevector:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000868 return SemaBuiltinShuffleVector(TheCall);
869 // TheCall will be freed by the smart pointer here, but that's fine, since
870 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbarb7257262008-07-21 22:59:13 +0000871 case Builtin::BI__builtin_prefetch:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000872 if (SemaBuiltinPrefetch(TheCall))
873 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000874 break;
David Majnemer51169932016-10-31 05:37:48 +0000875 case Builtin::BI__builtin_alloca_with_align:
876 if (SemaBuiltinAllocaWithAlign(TheCall))
877 return ExprError();
878 break;
Hal Finkelf0417332014-07-17 14:25:55 +0000879 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +0000880 case Builtin::BI__builtin_assume:
Hal Finkelf0417332014-07-17 14:25:55 +0000881 if (SemaBuiltinAssume(TheCall))
882 return ExprError();
883 break;
Hal Finkelbcc06082014-09-07 22:58:14 +0000884 case Builtin::BI__builtin_assume_aligned:
885 if (SemaBuiltinAssumeAligned(TheCall))
886 return ExprError();
887 break;
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000888 case Builtin::BI__builtin_object_size:
Richard Sandiford28940af2014-04-16 08:47:51 +0000889 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000890 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000891 break;
Eli Friedmaneed8ad22009-05-03 04:46:36 +0000892 case Builtin::BI__builtin_longjmp:
893 if (SemaBuiltinLongjmp(TheCall))
894 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000895 break;
Joerg Sonnenberger27173282015-03-11 23:46:32 +0000896 case Builtin::BI__builtin_setjmp:
897 if (SemaBuiltinSetjmp(TheCall))
898 return ExprError();
899 break;
David Majnemerc403a1c2015-03-20 17:03:35 +0000900 case Builtin::BI_setjmp:
901 case Builtin::BI_setjmpex:
902 if (checkArgCount(*this, TheCall, 1))
903 return true;
904 break;
John McCallbebede42011-02-26 05:39:39 +0000905
906 case Builtin::BI__builtin_classify_type:
907 if (checkArgCount(*this, TheCall, 1)) return true;
908 TheCall->setType(Context.IntTy);
909 break;
Chris Lattner17c0eac2010-10-12 17:47:42 +0000910 case Builtin::BI__builtin_constant_p:
John McCallbebede42011-02-26 05:39:39 +0000911 if (checkArgCount(*this, TheCall, 1)) return true;
912 TheCall->setType(Context.IntTy);
Chris Lattner17c0eac2010-10-12 17:47:42 +0000913 break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000914 case Builtin::BI__sync_fetch_and_add:
Douglas Gregor73722482011-11-28 16:30:08 +0000915 case Builtin::BI__sync_fetch_and_add_1:
916 case Builtin::BI__sync_fetch_and_add_2:
917 case Builtin::BI__sync_fetch_and_add_4:
918 case Builtin::BI__sync_fetch_and_add_8:
919 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000920 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregor73722482011-11-28 16:30:08 +0000921 case Builtin::BI__sync_fetch_and_sub_1:
922 case Builtin::BI__sync_fetch_and_sub_2:
923 case Builtin::BI__sync_fetch_and_sub_4:
924 case Builtin::BI__sync_fetch_and_sub_8:
925 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000926 case Builtin::BI__sync_fetch_and_or:
Douglas Gregor73722482011-11-28 16:30:08 +0000927 case Builtin::BI__sync_fetch_and_or_1:
928 case Builtin::BI__sync_fetch_and_or_2:
929 case Builtin::BI__sync_fetch_and_or_4:
930 case Builtin::BI__sync_fetch_and_or_8:
931 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000932 case Builtin::BI__sync_fetch_and_and:
Douglas Gregor73722482011-11-28 16:30:08 +0000933 case Builtin::BI__sync_fetch_and_and_1:
934 case Builtin::BI__sync_fetch_and_and_2:
935 case Builtin::BI__sync_fetch_and_and_4:
936 case Builtin::BI__sync_fetch_and_and_8:
937 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000938 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregor73722482011-11-28 16:30:08 +0000939 case Builtin::BI__sync_fetch_and_xor_1:
940 case Builtin::BI__sync_fetch_and_xor_2:
941 case Builtin::BI__sync_fetch_and_xor_4:
942 case Builtin::BI__sync_fetch_and_xor_8:
943 case Builtin::BI__sync_fetch_and_xor_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000944 case Builtin::BI__sync_fetch_and_nand:
945 case Builtin::BI__sync_fetch_and_nand_1:
946 case Builtin::BI__sync_fetch_and_nand_2:
947 case Builtin::BI__sync_fetch_and_nand_4:
948 case Builtin::BI__sync_fetch_and_nand_8:
949 case Builtin::BI__sync_fetch_and_nand_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000950 case Builtin::BI__sync_add_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000951 case Builtin::BI__sync_add_and_fetch_1:
952 case Builtin::BI__sync_add_and_fetch_2:
953 case Builtin::BI__sync_add_and_fetch_4:
954 case Builtin::BI__sync_add_and_fetch_8:
955 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000956 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000957 case Builtin::BI__sync_sub_and_fetch_1:
958 case Builtin::BI__sync_sub_and_fetch_2:
959 case Builtin::BI__sync_sub_and_fetch_4:
960 case Builtin::BI__sync_sub_and_fetch_8:
961 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000962 case Builtin::BI__sync_and_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000963 case Builtin::BI__sync_and_and_fetch_1:
964 case Builtin::BI__sync_and_and_fetch_2:
965 case Builtin::BI__sync_and_and_fetch_4:
966 case Builtin::BI__sync_and_and_fetch_8:
967 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000968 case Builtin::BI__sync_or_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000969 case Builtin::BI__sync_or_and_fetch_1:
970 case Builtin::BI__sync_or_and_fetch_2:
971 case Builtin::BI__sync_or_and_fetch_4:
972 case Builtin::BI__sync_or_and_fetch_8:
973 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000974 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000975 case Builtin::BI__sync_xor_and_fetch_1:
976 case Builtin::BI__sync_xor_and_fetch_2:
977 case Builtin::BI__sync_xor_and_fetch_4:
978 case Builtin::BI__sync_xor_and_fetch_8:
979 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000980 case Builtin::BI__sync_nand_and_fetch:
981 case Builtin::BI__sync_nand_and_fetch_1:
982 case Builtin::BI__sync_nand_and_fetch_2:
983 case Builtin::BI__sync_nand_and_fetch_4:
984 case Builtin::BI__sync_nand_and_fetch_8:
985 case Builtin::BI__sync_nand_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000986 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000987 case Builtin::BI__sync_val_compare_and_swap_1:
988 case Builtin::BI__sync_val_compare_and_swap_2:
989 case Builtin::BI__sync_val_compare_and_swap_4:
990 case Builtin::BI__sync_val_compare_and_swap_8:
991 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000992 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000993 case Builtin::BI__sync_bool_compare_and_swap_1:
994 case Builtin::BI__sync_bool_compare_and_swap_2:
995 case Builtin::BI__sync_bool_compare_and_swap_4:
996 case Builtin::BI__sync_bool_compare_and_swap_8:
997 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000998 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +0000999 case Builtin::BI__sync_lock_test_and_set_1:
1000 case Builtin::BI__sync_lock_test_and_set_2:
1001 case Builtin::BI__sync_lock_test_and_set_4:
1002 case Builtin::BI__sync_lock_test_and_set_8:
1003 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001004 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00001005 case Builtin::BI__sync_lock_release_1:
1006 case Builtin::BI__sync_lock_release_2:
1007 case Builtin::BI__sync_lock_release_4:
1008 case Builtin::BI__sync_lock_release_8:
1009 case Builtin::BI__sync_lock_release_16:
Chris Lattner9cb59fa2011-04-09 03:57:26 +00001010 case Builtin::BI__sync_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001011 case Builtin::BI__sync_swap_1:
1012 case Builtin::BI__sync_swap_2:
1013 case Builtin::BI__sync_swap_4:
1014 case Builtin::BI__sync_swap_8:
1015 case Builtin::BI__sync_swap_16:
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001016 return SemaBuiltinAtomicOverloaded(TheCallResult);
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001017 case Builtin::BI__builtin_nontemporal_load:
1018 case Builtin::BI__builtin_nontemporal_store:
1019 return SemaBuiltinNontemporalOverloaded(TheCallResult);
Richard Smithfeea8832012-04-12 05:08:17 +00001020#define BUILTIN(ID, TYPE, ATTRS)
1021#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1022 case Builtin::BI##ID: \
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001023 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithfeea8832012-04-12 05:08:17 +00001024#include "clang/Basic/Builtins.def"
Reid Kleckner30701ed2017-09-05 20:27:35 +00001025 case Builtin::BI__annotation:
1026 if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1027 return ExprError();
1028 break;
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001029 case Builtin::BI__builtin_annotation:
Julien Lerouge4a5b4442012-04-28 17:39:16 +00001030 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001031 return ExprError();
1032 break;
Richard Smith6cbd65d2013-07-11 02:27:57 +00001033 case Builtin::BI__builtin_addressof:
1034 if (SemaBuiltinAddressof(*this, TheCall))
1035 return ExprError();
1036 break;
John McCall03107a42015-10-29 20:48:01 +00001037 case Builtin::BI__builtin_add_overflow:
1038 case Builtin::BI__builtin_sub_overflow:
1039 case Builtin::BI__builtin_mul_overflow:
Craig Toppera86e70d2015-11-07 06:16:14 +00001040 if (SemaBuiltinOverflow(*this, TheCall))
1041 return ExprError();
1042 break;
Richard Smith760520b2014-06-03 23:27:44 +00001043 case Builtin::BI__builtin_operator_new:
1044 case Builtin::BI__builtin_operator_delete:
1045 if (!getLangOpts().CPlusPlus) {
1046 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
1047 << (BuiltinID == Builtin::BI__builtin_operator_new
1048 ? "__builtin_operator_new"
1049 : "__builtin_operator_delete")
1050 << "C++";
1051 return ExprError();
1052 }
1053 // CodeGen assumes it can find the global new and delete to call,
1054 // so ensure that they are declared.
1055 DeclareGlobalNewDelete();
1056 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001057
1058 // check secure string manipulation functions where overflows
1059 // are detectable at compile time
1060 case Builtin::BI__builtin___memcpy_chk:
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001061 case Builtin::BI__builtin___memmove_chk:
1062 case Builtin::BI__builtin___memset_chk:
1063 case Builtin::BI__builtin___strlcat_chk:
1064 case Builtin::BI__builtin___strlcpy_chk:
1065 case Builtin::BI__builtin___strncat_chk:
1066 case Builtin::BI__builtin___strncpy_chk:
1067 case Builtin::BI__builtin___stpncpy_chk:
1068 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
1069 break;
Steven Wu566c14e2014-09-24 04:37:33 +00001070 case Builtin::BI__builtin___memccpy_chk:
1071 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
1072 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001073 case Builtin::BI__builtin___snprintf_chk:
1074 case Builtin::BI__builtin___vsnprintf_chk:
1075 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
1076 break;
Peter Collingbournef7706832014-12-12 23:41:25 +00001077 case Builtin::BI__builtin_call_with_static_chain:
1078 if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1079 return ExprError();
1080 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001081 case Builtin::BI__exception_code:
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001082 case Builtin::BI_exception_code:
Reid Kleckner1d59f992015-01-22 01:36:17 +00001083 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1084 diag::err_seh___except_block))
1085 return ExprError();
1086 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001087 case Builtin::BI__exception_info:
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001088 case Builtin::BI_exception_info:
Reid Kleckner1d59f992015-01-22 01:36:17 +00001089 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1090 diag::err_seh___except_filter))
1091 return ExprError();
1092 break;
David Majnemerba3e5ec2015-03-13 18:26:17 +00001093 case Builtin::BI__GetExceptionInfo:
1094 if (checkArgCount(*this, TheCall, 1))
1095 return ExprError();
1096
1097 if (CheckCXXThrowOperand(
1098 TheCall->getLocStart(),
1099 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1100 TheCall))
1101 return ExprError();
1102
1103 TheCall->setType(Context.VoidPtrTy);
1104 break;
Anastasia Stulova7f8d6dc2016-07-04 16:07:18 +00001105 // OpenCL v2.0, s6.13.16 - Pipe functions
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001106 case Builtin::BIread_pipe:
1107 case Builtin::BIwrite_pipe:
1108 // Since those two functions are declared with var args, we need a semantic
1109 // check for the argument.
1110 if (SemaBuiltinRWPipe(*this, TheCall))
1111 return ExprError();
Alexey Baderaf17c792016-09-07 10:32:03 +00001112 TheCall->setType(Context.IntTy);
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001113 break;
1114 case Builtin::BIreserve_read_pipe:
1115 case Builtin::BIreserve_write_pipe:
1116 case Builtin::BIwork_group_reserve_read_pipe:
1117 case Builtin::BIwork_group_reserve_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001118 if (SemaBuiltinReserveRWPipe(*this, TheCall))
1119 return ExprError();
Joey Gouly84ae3362017-07-31 15:15:59 +00001120 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001121 case Builtin::BIsub_group_reserve_read_pipe:
1122 case Builtin::BIsub_group_reserve_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001123 if (checkOpenCLSubgroupExt(*this, TheCall) ||
1124 SemaBuiltinReserveRWPipe(*this, TheCall))
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001125 return ExprError();
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001126 break;
1127 case Builtin::BIcommit_read_pipe:
1128 case Builtin::BIcommit_write_pipe:
1129 case Builtin::BIwork_group_commit_read_pipe:
1130 case Builtin::BIwork_group_commit_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001131 if (SemaBuiltinCommitRWPipe(*this, TheCall))
1132 return ExprError();
1133 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001134 case Builtin::BIsub_group_commit_read_pipe:
1135 case Builtin::BIsub_group_commit_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001136 if (checkOpenCLSubgroupExt(*this, TheCall) ||
1137 SemaBuiltinCommitRWPipe(*this, TheCall))
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001138 return ExprError();
1139 break;
1140 case Builtin::BIget_pipe_num_packets:
1141 case Builtin::BIget_pipe_max_packets:
1142 if (SemaBuiltinPipePackets(*this, TheCall))
1143 return ExprError();
Alexey Baderaf17c792016-09-07 10:32:03 +00001144 TheCall->setType(Context.UnsignedIntTy);
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001145 break;
Yaxun Liuf7449a12016-05-20 19:54:38 +00001146 case Builtin::BIto_global:
1147 case Builtin::BIto_local:
1148 case Builtin::BIto_private:
1149 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1150 return ExprError();
1151 break;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00001152 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1153 case Builtin::BIenqueue_kernel:
1154 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1155 return ExprError();
1156 break;
1157 case Builtin::BIget_kernel_work_group_size:
1158 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1159 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1160 return ExprError();
Mehdi Amini06d367c2016-10-24 20:39:34 +00001161 break;
Joey Goulyfa76b492017-08-01 13:27:09 +00001162 break;
1163 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1164 case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1165 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1166 return ExprError();
1167 break;
Mehdi Amini06d367c2016-10-24 20:39:34 +00001168 case Builtin::BI__builtin_os_log_format:
1169 case Builtin::BI__builtin_os_log_format_buffer_size:
1170 if (SemaBuiltinOSLogFormat(TheCall)) {
1171 return ExprError();
1172 }
1173 break;
Nate Begeman4904e322010-06-08 02:47:44 +00001174 }
Richard Smith760520b2014-06-03 23:27:44 +00001175
Nate Begeman4904e322010-06-08 02:47:44 +00001176 // Since the target specific builtins for each arch overlap, only check those
1177 // of the arch we are compiling for.
Artem Belevich9674a642015-09-22 17:23:05 +00001178 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001179 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +00001180 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00001181 case llvm::Triple::armeb:
Nate Begeman4904e322010-06-08 02:47:44 +00001182 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00001183 case llvm::Triple::thumbeb:
Nate Begeman4904e322010-06-08 02:47:44 +00001184 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1185 return ExprError();
1186 break;
Tim Northover25e8a672014-05-24 12:51:25 +00001187 case llvm::Triple::aarch64:
1188 case llvm::Triple::aarch64_be:
Tim Northover573cbee2014-05-24 12:52:07 +00001189 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
Tim Northovera2ee4332014-03-29 15:09:45 +00001190 return ExprError();
1191 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001192 case llvm::Triple::mips:
1193 case llvm::Triple::mipsel:
1194 case llvm::Triple::mips64:
1195 case llvm::Triple::mips64el:
1196 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1197 return ExprError();
1198 break;
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001199 case llvm::Triple::systemz:
1200 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1201 return ExprError();
1202 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001203 case llvm::Triple::x86:
1204 case llvm::Triple::x86_64:
1205 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1206 return ExprError();
1207 break;
Kit Bartone50adcb2015-03-30 19:40:59 +00001208 case llvm::Triple::ppc:
1209 case llvm::Triple::ppc64:
1210 case llvm::Triple::ppc64le:
1211 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1212 return ExprError();
1213 break;
Nate Begeman4904e322010-06-08 02:47:44 +00001214 default:
1215 break;
1216 }
1217 }
1218
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001219 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +00001220}
1221
Nate Begeman91e1fea2010-06-14 05:21:25 +00001222// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +00001223static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +00001224 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +00001225 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +00001226 switch (Type.getEltType()) {
1227 case NeonTypeFlags::Int8:
1228 case NeonTypeFlags::Poly8:
1229 return shift ? 7 : (8 << IsQuad) - 1;
1230 case NeonTypeFlags::Int16:
1231 case NeonTypeFlags::Poly16:
1232 return shift ? 15 : (4 << IsQuad) - 1;
1233 case NeonTypeFlags::Int32:
1234 return shift ? 31 : (2 << IsQuad) - 1;
1235 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +00001236 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +00001237 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +00001238 case NeonTypeFlags::Poly128:
1239 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +00001240 case NeonTypeFlags::Float16:
1241 assert(!shift && "cannot shift float types!");
1242 return (4 << IsQuad) - 1;
1243 case NeonTypeFlags::Float32:
1244 assert(!shift && "cannot shift float types!");
1245 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +00001246 case NeonTypeFlags::Float64:
1247 assert(!shift && "cannot shift float types!");
1248 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +00001249 }
David Blaikie8a40f702012-01-17 06:56:22 +00001250 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +00001251}
1252
Bob Wilsone4d77232011-11-08 05:04:11 +00001253/// getNeonEltType - Return the QualType corresponding to the elements of
1254/// the vector type specified by the NeonTypeFlags. This is used to check
1255/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +00001256static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Tim Northovera2ee4332014-03-29 15:09:45 +00001257 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilsone4d77232011-11-08 05:04:11 +00001258 switch (Flags.getEltType()) {
1259 case NeonTypeFlags::Int8:
1260 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1261 case NeonTypeFlags::Int16:
1262 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1263 case NeonTypeFlags::Int32:
1264 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1265 case NeonTypeFlags::Int64:
Tim Northovera2ee4332014-03-29 15:09:45 +00001266 if (IsInt64Long)
Kevin Qinad64f6d2014-02-24 02:45:03 +00001267 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1268 else
1269 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1270 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001271 case NeonTypeFlags::Poly8:
Tim Northovera2ee4332014-03-29 15:09:45 +00001272 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001273 case NeonTypeFlags::Poly16:
Tim Northovera2ee4332014-03-29 15:09:45 +00001274 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qincaac85e2013-11-14 03:29:16 +00001275 case NeonTypeFlags::Poly64:
Kevin Qin78b86532015-05-14 08:18:05 +00001276 if (IsInt64Long)
1277 return Context.UnsignedLongTy;
1278 else
1279 return Context.UnsignedLongLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +00001280 case NeonTypeFlags::Poly128:
1281 break;
Bob Wilsone4d77232011-11-08 05:04:11 +00001282 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +00001283 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001284 case NeonTypeFlags::Float32:
1285 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +00001286 case NeonTypeFlags::Float64:
1287 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001288 }
David Blaikie8a40f702012-01-17 06:56:22 +00001289 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +00001290}
1291
Tim Northover12670412014-02-19 10:37:05 +00001292bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +00001293 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +00001294 uint64_t mask = 0;
1295 unsigned TV = 0;
1296 int PtrArgNum = -1;
1297 bool HasConstPtr = false;
1298 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +00001299#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001300#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +00001301#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001302 }
1303
1304 // For NEON intrinsics which are overloaded on vector element type, validate
1305 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +00001306 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +00001307 if (mask) {
1308 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1309 return true;
1310
1311 TV = Result.getLimitedValue(64);
1312 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1313 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Tim Northover12670412014-02-19 10:37:05 +00001314 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +00001315 }
1316
1317 if (PtrArgNum >= 0) {
1318 // Check that pointer arguments have the specified type.
1319 Expr *Arg = TheCall->getArg(PtrArgNum);
1320 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1321 Arg = ICE->getSubExpr();
1322 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1323 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +00001324
Tim Northovera2ee4332014-03-29 15:09:45 +00001325 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Joerg Sonnenberger47006c52017-01-09 11:40:41 +00001326 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
1327 Arch == llvm::Triple::aarch64_be;
Tim Northovera2ee4332014-03-29 15:09:45 +00001328 bool IsInt64Long =
1329 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1330 QualType EltTy =
1331 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northover2fe823a2013-08-01 09:23:19 +00001332 if (HasConstPtr)
1333 EltTy = EltTy.withConst();
1334 QualType LHSTy = Context.getPointerType(EltTy);
1335 AssignConvertType ConvTy;
1336 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1337 if (RHS.isInvalid())
1338 return true;
1339 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
1340 RHS.get(), AA_Assigning))
1341 return true;
1342 }
1343
1344 // For NEON intrinsics which take an immediate value as part of the
1345 // instruction, range check them here.
1346 unsigned i = 0, l = 0, u = 0;
1347 switch (BuiltinID) {
1348 default:
1349 return false;
Tim Northover12670412014-02-19 10:37:05 +00001350#define GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001351#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +00001352#undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001353 }
Tim Northover2fe823a2013-08-01 09:23:19 +00001354
Richard Sandiford28940af2014-04-16 08:47:51 +00001355 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northover2fe823a2013-08-01 09:23:19 +00001356}
1357
Tim Northovera2ee4332014-03-29 15:09:45 +00001358bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1359 unsigned MaxWidth) {
Tim Northover6aacd492013-07-16 09:47:53 +00001360 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001361 BuiltinID == ARM::BI__builtin_arm_ldaex ||
Tim Northovera2ee4332014-03-29 15:09:45 +00001362 BuiltinID == ARM::BI__builtin_arm_strex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001363 BuiltinID == ARM::BI__builtin_arm_stlex ||
Tim Northover573cbee2014-05-24 12:52:07 +00001364 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001365 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1366 BuiltinID == AArch64::BI__builtin_arm_strex ||
1367 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
Tim Northover6aacd492013-07-16 09:47:53 +00001368 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +00001369 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001370 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1371 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1372 BuiltinID == AArch64::BI__builtin_arm_ldaex;
Tim Northover6aacd492013-07-16 09:47:53 +00001373
1374 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1375
1376 // Ensure that we have the proper number of arguments.
1377 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1378 return true;
1379
1380 // Inspect the pointer argument of the atomic builtin. This should always be
1381 // a pointer type, whose element is an integral scalar or pointer type.
1382 // Because it is a pointer type, we don't have to worry about any implicit
1383 // casts here.
1384 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1385 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1386 if (PointerArgRes.isInvalid())
1387 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001388 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001389
1390 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1391 if (!pointerType) {
1392 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1393 << PointerArg->getType() << PointerArg->getSourceRange();
1394 return true;
1395 }
1396
1397 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1398 // task is to insert the appropriate casts into the AST. First work out just
1399 // what the appropriate type is.
1400 QualType ValType = pointerType->getPointeeType();
1401 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1402 if (IsLdrex)
1403 AddrType.addConst();
1404
1405 // Issue a warning if the cast is dodgy.
1406 CastKind CastNeeded = CK_NoOp;
1407 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1408 CastNeeded = CK_BitCast;
1409 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
1410 << PointerArg->getType()
1411 << Context.getPointerType(AddrType)
1412 << AA_Passing << PointerArg->getSourceRange();
1413 }
1414
1415 // Finally, do the cast and replace the argument with the corrected version.
1416 AddrType = Context.getPointerType(AddrType);
1417 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1418 if (PointerArgRes.isInvalid())
1419 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001420 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001421
1422 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1423
1424 // In general, we allow ints, floats and pointers to be loaded and stored.
1425 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1426 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1427 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1428 << PointerArg->getType() << PointerArg->getSourceRange();
1429 return true;
1430 }
1431
1432 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +00001433 if (Context.getTypeSize(ValType) > MaxWidth) {
1434 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover6aacd492013-07-16 09:47:53 +00001435 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
1436 << PointerArg->getType() << PointerArg->getSourceRange();
1437 return true;
1438 }
1439
1440 switch (ValType.getObjCLifetime()) {
1441 case Qualifiers::OCL_None:
1442 case Qualifiers::OCL_ExplicitNone:
1443 // okay
1444 break;
1445
1446 case Qualifiers::OCL_Weak:
1447 case Qualifiers::OCL_Strong:
1448 case Qualifiers::OCL_Autoreleasing:
1449 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1450 << ValType << PointerArg->getSourceRange();
1451 return true;
1452 }
1453
Tim Northover6aacd492013-07-16 09:47:53 +00001454 if (IsLdrex) {
1455 TheCall->setType(ValType);
1456 return false;
1457 }
1458
1459 // Initialize the argument to be stored.
1460 ExprResult ValArg = TheCall->getArg(0);
1461 InitializedEntity Entity = InitializedEntity::InitializeParameter(
1462 Context, ValType, /*consume*/ false);
1463 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1464 if (ValArg.isInvalid())
1465 return true;
Tim Northover6aacd492013-07-16 09:47:53 +00001466 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +00001467
1468 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1469 // but the custom checker bypasses all default analysis.
1470 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +00001471 return false;
1472}
1473
Nate Begeman4904e322010-06-08 02:47:44 +00001474bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover6aacd492013-07-16 09:47:53 +00001475 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001476 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1477 BuiltinID == ARM::BI__builtin_arm_strex ||
1478 BuiltinID == ARM::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001479 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +00001480 }
1481
Yi Kong26d104a2014-08-13 19:18:14 +00001482 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1483 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1484 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1485 }
1486
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001487 if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1488 BuiltinID == ARM::BI__builtin_arm_wsr64)
1489 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1490
1491 if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1492 BuiltinID == ARM::BI__builtin_arm_rsrp ||
1493 BuiltinID == ARM::BI__builtin_arm_wsr ||
1494 BuiltinID == ARM::BI__builtin_arm_wsrp)
1495 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1496
Tim Northover12670412014-02-19 10:37:05 +00001497 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1498 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +00001499
Yi Kong4efadfb2014-07-03 16:01:25 +00001500 // For intrinsics which take an immediate value as part of the instruction,
1501 // range check them here.
Nate Begeman91e1fea2010-06-14 05:21:25 +00001502 unsigned i = 0, l = 0, u = 0;
Nate Begemand773fe62010-06-13 04:47:52 +00001503 switch (BuiltinID) {
1504 default: return false;
Nate Begeman1194bd22010-07-29 22:48:34 +00001505 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
1506 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begemanf568b072010-08-03 21:32:34 +00001507 case ARM::BI__builtin_arm_vcvtr_f:
1508 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Weiming Zhao87bb4922013-11-12 21:42:50 +00001509 case ARM::BI__builtin_arm_dmb:
Yi Kong4efadfb2014-07-03 16:01:25 +00001510 case ARM::BI__builtin_arm_dsb:
Yi Kong1d268af2014-08-26 12:48:06 +00001511 case ARM::BI__builtin_arm_isb:
1512 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00001513 }
Nate Begemand773fe62010-06-13 04:47:52 +00001514
Nate Begemanf568b072010-08-03 21:32:34 +00001515 // FIXME: VFP Intrinsics should error if VFP not present.
Richard Sandiford28940af2014-04-16 08:47:51 +00001516 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001517}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001518
Tim Northover573cbee2014-05-24 12:52:07 +00001519bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +00001520 CallExpr *TheCall) {
Tim Northover573cbee2014-05-24 12:52:07 +00001521 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001522 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1523 BuiltinID == AArch64::BI__builtin_arm_strex ||
1524 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001525 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1526 }
1527
Yi Konga5548432014-08-13 19:18:20 +00001528 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1529 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1530 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1531 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1532 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1533 }
1534
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001535 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1536 BuiltinID == AArch64::BI__builtin_arm_wsr64)
Tim Northover54e50002016-04-13 17:08:55 +00001537 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001538
1539 if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1540 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1541 BuiltinID == AArch64::BI__builtin_arm_wsr ||
1542 BuiltinID == AArch64::BI__builtin_arm_wsrp)
1543 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1544
Tim Northovera2ee4332014-03-29 15:09:45 +00001545 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1546 return true;
1547
Yi Kong19a29ac2014-07-17 10:52:06 +00001548 // For intrinsics which take an immediate value as part of the instruction,
1549 // range check them here.
1550 unsigned i = 0, l = 0, u = 0;
1551 switch (BuiltinID) {
1552 default: return false;
1553 case AArch64::BI__builtin_arm_dmb:
1554 case AArch64::BI__builtin_arm_dsb:
1555 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1556 }
1557
Yi Kong19a29ac2014-07-17 10:52:06 +00001558 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northovera2ee4332014-03-29 15:09:45 +00001559}
1560
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001561// CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
1562// intrinsic is correct. The switch statement is ordered by DSP, MSA. The
1563// ordering for DSP is unspecified. MSA is ordered by the data format used
1564// by the underlying instruction i.e., df/m, df/n and then by size.
1565//
1566// FIXME: The size tests here should instead be tablegen'd along with the
1567// definitions from include/clang/Basic/BuiltinsMips.def.
1568// FIXME: GCC is strict on signedness for some of these intrinsics, we should
1569// be too.
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001570bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001571 unsigned i = 0, l = 0, u = 0, m = 0;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001572 switch (BuiltinID) {
1573 default: return false;
1574 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
1575 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +00001576 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
1577 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
1578 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
1579 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
1580 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001581 // MSA instrinsics. Instructions (which the intrinsics maps to) which use the
1582 // df/m field.
1583 // These intrinsics take an unsigned 3 bit immediate.
1584 case Mips::BI__builtin_msa_bclri_b:
1585 case Mips::BI__builtin_msa_bnegi_b:
1586 case Mips::BI__builtin_msa_bseti_b:
1587 case Mips::BI__builtin_msa_sat_s_b:
1588 case Mips::BI__builtin_msa_sat_u_b:
1589 case Mips::BI__builtin_msa_slli_b:
1590 case Mips::BI__builtin_msa_srai_b:
1591 case Mips::BI__builtin_msa_srari_b:
1592 case Mips::BI__builtin_msa_srli_b:
1593 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
1594 case Mips::BI__builtin_msa_binsli_b:
1595 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
1596 // These intrinsics take an unsigned 4 bit immediate.
1597 case Mips::BI__builtin_msa_bclri_h:
1598 case Mips::BI__builtin_msa_bnegi_h:
1599 case Mips::BI__builtin_msa_bseti_h:
1600 case Mips::BI__builtin_msa_sat_s_h:
1601 case Mips::BI__builtin_msa_sat_u_h:
1602 case Mips::BI__builtin_msa_slli_h:
1603 case Mips::BI__builtin_msa_srai_h:
1604 case Mips::BI__builtin_msa_srari_h:
1605 case Mips::BI__builtin_msa_srli_h:
1606 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
1607 case Mips::BI__builtin_msa_binsli_h:
1608 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
1609 // These intrinsics take an unsigned 5 bit immedate.
1610 // The first block of intrinsics actually have an unsigned 5 bit field,
1611 // not a df/n field.
1612 case Mips::BI__builtin_msa_clei_u_b:
1613 case Mips::BI__builtin_msa_clei_u_h:
1614 case Mips::BI__builtin_msa_clei_u_w:
1615 case Mips::BI__builtin_msa_clei_u_d:
1616 case Mips::BI__builtin_msa_clti_u_b:
1617 case Mips::BI__builtin_msa_clti_u_h:
1618 case Mips::BI__builtin_msa_clti_u_w:
1619 case Mips::BI__builtin_msa_clti_u_d:
1620 case Mips::BI__builtin_msa_maxi_u_b:
1621 case Mips::BI__builtin_msa_maxi_u_h:
1622 case Mips::BI__builtin_msa_maxi_u_w:
1623 case Mips::BI__builtin_msa_maxi_u_d:
1624 case Mips::BI__builtin_msa_mini_u_b:
1625 case Mips::BI__builtin_msa_mini_u_h:
1626 case Mips::BI__builtin_msa_mini_u_w:
1627 case Mips::BI__builtin_msa_mini_u_d:
1628 case Mips::BI__builtin_msa_addvi_b:
1629 case Mips::BI__builtin_msa_addvi_h:
1630 case Mips::BI__builtin_msa_addvi_w:
1631 case Mips::BI__builtin_msa_addvi_d:
1632 case Mips::BI__builtin_msa_bclri_w:
1633 case Mips::BI__builtin_msa_bnegi_w:
1634 case Mips::BI__builtin_msa_bseti_w:
1635 case Mips::BI__builtin_msa_sat_s_w:
1636 case Mips::BI__builtin_msa_sat_u_w:
1637 case Mips::BI__builtin_msa_slli_w:
1638 case Mips::BI__builtin_msa_srai_w:
1639 case Mips::BI__builtin_msa_srari_w:
1640 case Mips::BI__builtin_msa_srli_w:
1641 case Mips::BI__builtin_msa_srlri_w:
1642 case Mips::BI__builtin_msa_subvi_b:
1643 case Mips::BI__builtin_msa_subvi_h:
1644 case Mips::BI__builtin_msa_subvi_w:
1645 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
1646 case Mips::BI__builtin_msa_binsli_w:
1647 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
1648 // These intrinsics take an unsigned 6 bit immediate.
1649 case Mips::BI__builtin_msa_bclri_d:
1650 case Mips::BI__builtin_msa_bnegi_d:
1651 case Mips::BI__builtin_msa_bseti_d:
1652 case Mips::BI__builtin_msa_sat_s_d:
1653 case Mips::BI__builtin_msa_sat_u_d:
1654 case Mips::BI__builtin_msa_slli_d:
1655 case Mips::BI__builtin_msa_srai_d:
1656 case Mips::BI__builtin_msa_srari_d:
1657 case Mips::BI__builtin_msa_srli_d:
1658 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
1659 case Mips::BI__builtin_msa_binsli_d:
1660 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
1661 // These intrinsics take a signed 5 bit immediate.
1662 case Mips::BI__builtin_msa_ceqi_b:
1663 case Mips::BI__builtin_msa_ceqi_h:
1664 case Mips::BI__builtin_msa_ceqi_w:
1665 case Mips::BI__builtin_msa_ceqi_d:
1666 case Mips::BI__builtin_msa_clti_s_b:
1667 case Mips::BI__builtin_msa_clti_s_h:
1668 case Mips::BI__builtin_msa_clti_s_w:
1669 case Mips::BI__builtin_msa_clti_s_d:
1670 case Mips::BI__builtin_msa_clei_s_b:
1671 case Mips::BI__builtin_msa_clei_s_h:
1672 case Mips::BI__builtin_msa_clei_s_w:
1673 case Mips::BI__builtin_msa_clei_s_d:
1674 case Mips::BI__builtin_msa_maxi_s_b:
1675 case Mips::BI__builtin_msa_maxi_s_h:
1676 case Mips::BI__builtin_msa_maxi_s_w:
1677 case Mips::BI__builtin_msa_maxi_s_d:
1678 case Mips::BI__builtin_msa_mini_s_b:
1679 case Mips::BI__builtin_msa_mini_s_h:
1680 case Mips::BI__builtin_msa_mini_s_w:
1681 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
1682 // These intrinsics take an unsigned 8 bit immediate.
1683 case Mips::BI__builtin_msa_andi_b:
1684 case Mips::BI__builtin_msa_nori_b:
1685 case Mips::BI__builtin_msa_ori_b:
1686 case Mips::BI__builtin_msa_shf_b:
1687 case Mips::BI__builtin_msa_shf_h:
1688 case Mips::BI__builtin_msa_shf_w:
1689 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
1690 case Mips::BI__builtin_msa_bseli_b:
1691 case Mips::BI__builtin_msa_bmnzi_b:
1692 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
1693 // df/n format
1694 // These intrinsics take an unsigned 4 bit immediate.
1695 case Mips::BI__builtin_msa_copy_s_b:
1696 case Mips::BI__builtin_msa_copy_u_b:
1697 case Mips::BI__builtin_msa_insve_b:
1698 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001699 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
1700 // These intrinsics take an unsigned 3 bit immediate.
1701 case Mips::BI__builtin_msa_copy_s_h:
1702 case Mips::BI__builtin_msa_copy_u_h:
1703 case Mips::BI__builtin_msa_insve_h:
1704 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001705 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
1706 // These intrinsics take an unsigned 2 bit immediate.
1707 case Mips::BI__builtin_msa_copy_s_w:
1708 case Mips::BI__builtin_msa_copy_u_w:
1709 case Mips::BI__builtin_msa_insve_w:
1710 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001711 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
1712 // These intrinsics take an unsigned 1 bit immediate.
1713 case Mips::BI__builtin_msa_copy_s_d:
1714 case Mips::BI__builtin_msa_copy_u_d:
1715 case Mips::BI__builtin_msa_insve_d:
1716 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001717 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
1718 // Memory offsets and immediate loads.
1719 // These intrinsics take a signed 10 bit immediate.
Petar Jovanovic9b8b9e82017-03-31 16:16:43 +00001720 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001721 case Mips::BI__builtin_msa_ldi_h:
1722 case Mips::BI__builtin_msa_ldi_w:
1723 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
1724 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break;
1725 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break;
1726 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break;
1727 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break;
1728 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break;
1729 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break;
1730 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break;
1731 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00001732 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001733
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001734 if (!m)
1735 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1736
1737 return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
1738 SemaBuiltinConstantArgMultiple(TheCall, i, m);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001739}
1740
Kit Bartone50adcb2015-03-30 19:40:59 +00001741bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1742 unsigned i = 0, l = 0, u = 0;
Nemanja Ivanovic239eec72015-04-09 23:58:16 +00001743 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
1744 BuiltinID == PPC::BI__builtin_divdeu ||
1745 BuiltinID == PPC::BI__builtin_bpermd;
1746 bool IsTarget64Bit = Context.getTargetInfo()
1747 .getTypeWidth(Context
1748 .getTargetInfo()
1749 .getIntPtrType()) == 64;
1750 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
1751 BuiltinID == PPC::BI__builtin_divweu ||
1752 BuiltinID == PPC::BI__builtin_divde ||
1753 BuiltinID == PPC::BI__builtin_divdeu;
1754
1755 if (Is64BitBltin && !IsTarget64Bit)
1756 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
1757 << TheCall->getSourceRange();
1758
1759 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
1760 (BuiltinID == PPC::BI__builtin_bpermd &&
1761 !Context.getTargetInfo().hasFeature("bpermd")))
1762 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
1763 << TheCall->getSourceRange();
1764
Kit Bartone50adcb2015-03-30 19:40:59 +00001765 switch (BuiltinID) {
1766 default: return false;
1767 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
1768 case PPC::BI__builtin_altivec_crypto_vshasigmad:
1769 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1770 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1771 case PPC::BI__builtin_tbegin:
1772 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
1773 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
1774 case PPC::BI__builtin_tabortwc:
1775 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
1776 case PPC::BI__builtin_tabortwci:
1777 case PPC::BI__builtin_tabortdci:
1778 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
1779 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
Tony Jiangbbc48e92017-05-24 15:13:32 +00001780 case PPC::BI__builtin_vsx_xxpermdi:
Tony Jiang9aa2c032017-05-24 15:54:13 +00001781 case PPC::BI__builtin_vsx_xxsldwi:
Tony Jiangbbc48e92017-05-24 15:13:32 +00001782 return SemaBuiltinVSX(TheCall);
Kit Bartone50adcb2015-03-30 19:40:59 +00001783 }
1784 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1785}
1786
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001787bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
1788 CallExpr *TheCall) {
1789 if (BuiltinID == SystemZ::BI__builtin_tabort) {
1790 Expr *Arg = TheCall->getArg(0);
1791 llvm::APSInt AbortCode(32);
1792 if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
1793 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
1794 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
1795 << Arg->getSourceRange();
1796 }
1797
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001798 // For intrinsics which take an immediate value as part of the instruction,
1799 // range check them here.
1800 unsigned i = 0, l = 0, u = 0;
1801 switch (BuiltinID) {
1802 default: return false;
1803 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
1804 case SystemZ::BI__builtin_s390_verimb:
1805 case SystemZ::BI__builtin_s390_verimh:
1806 case SystemZ::BI__builtin_s390_verimf:
1807 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
1808 case SystemZ::BI__builtin_s390_vfaeb:
1809 case SystemZ::BI__builtin_s390_vfaeh:
1810 case SystemZ::BI__builtin_s390_vfaef:
1811 case SystemZ::BI__builtin_s390_vfaebs:
1812 case SystemZ::BI__builtin_s390_vfaehs:
1813 case SystemZ::BI__builtin_s390_vfaefs:
1814 case SystemZ::BI__builtin_s390_vfaezb:
1815 case SystemZ::BI__builtin_s390_vfaezh:
1816 case SystemZ::BI__builtin_s390_vfaezf:
1817 case SystemZ::BI__builtin_s390_vfaezbs:
1818 case SystemZ::BI__builtin_s390_vfaezhs:
1819 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
Ulrich Weigandcac24ab2017-07-17 17:45:57 +00001820 case SystemZ::BI__builtin_s390_vfisb:
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001821 case SystemZ::BI__builtin_s390_vfidb:
1822 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1823 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
Ulrich Weigandcac24ab2017-07-17 17:45:57 +00001824 case SystemZ::BI__builtin_s390_vftcisb:
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001825 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
1826 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
1827 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
1828 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
1829 case SystemZ::BI__builtin_s390_vstrcb:
1830 case SystemZ::BI__builtin_s390_vstrch:
1831 case SystemZ::BI__builtin_s390_vstrcf:
1832 case SystemZ::BI__builtin_s390_vstrczb:
1833 case SystemZ::BI__builtin_s390_vstrczh:
1834 case SystemZ::BI__builtin_s390_vstrczf:
1835 case SystemZ::BI__builtin_s390_vstrcbs:
1836 case SystemZ::BI__builtin_s390_vstrchs:
1837 case SystemZ::BI__builtin_s390_vstrcfs:
1838 case SystemZ::BI__builtin_s390_vstrczbs:
1839 case SystemZ::BI__builtin_s390_vstrczhs:
1840 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
Ulrich Weigandcac24ab2017-07-17 17:45:57 +00001841 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
1842 case SystemZ::BI__builtin_s390_vfminsb:
1843 case SystemZ::BI__builtin_s390_vfmaxsb:
1844 case SystemZ::BI__builtin_s390_vfmindb:
1845 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001846 }
1847 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001848}
1849
Craig Topper5ba2c502015-11-07 08:08:31 +00001850/// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
1851/// This checks that the target supports __builtin_cpu_supports and
1852/// that the string argument is constant and valid.
1853static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
1854 Expr *Arg = TheCall->getArg(0);
1855
1856 // Check if the argument is a string literal.
1857 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1858 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1859 << Arg->getSourceRange();
1860
1861 // Check the contents of the string.
1862 StringRef Feature =
1863 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1864 if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
1865 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
1866 << Arg->getSourceRange();
1867 return false;
1868}
1869
Craig Topper699ae0c2017-08-10 20:28:30 +00001870/// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
1871/// This checks that the target supports __builtin_cpu_is and
1872/// that the string argument is constant and valid.
1873static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) {
1874 Expr *Arg = TheCall->getArg(0);
1875
1876 // Check if the argument is a string literal.
1877 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1878 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1879 << Arg->getSourceRange();
1880
1881 // Check the contents of the string.
1882 StringRef Feature =
1883 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1884 if (!S.Context.getTargetInfo().validateCpuIs(Feature))
1885 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_is)
1886 << Arg->getSourceRange();
1887 return false;
1888}
1889
Craig Toppera7e253e2016-09-23 04:48:31 +00001890// Check if the rounding mode is legal.
1891bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
1892 // Indicates if this instruction has rounding control or just SAE.
1893 bool HasRC = false;
1894
1895 unsigned ArgNum = 0;
1896 switch (BuiltinID) {
1897 default:
1898 return false;
1899 case X86::BI__builtin_ia32_vcvttsd2si32:
1900 case X86::BI__builtin_ia32_vcvttsd2si64:
1901 case X86::BI__builtin_ia32_vcvttsd2usi32:
1902 case X86::BI__builtin_ia32_vcvttsd2usi64:
1903 case X86::BI__builtin_ia32_vcvttss2si32:
1904 case X86::BI__builtin_ia32_vcvttss2si64:
1905 case X86::BI__builtin_ia32_vcvttss2usi32:
1906 case X86::BI__builtin_ia32_vcvttss2usi64:
1907 ArgNum = 1;
1908 break;
1909 case X86::BI__builtin_ia32_cvtps2pd512_mask:
1910 case X86::BI__builtin_ia32_cvttpd2dq512_mask:
1911 case X86::BI__builtin_ia32_cvttpd2qq512_mask:
1912 case X86::BI__builtin_ia32_cvttpd2udq512_mask:
1913 case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
1914 case X86::BI__builtin_ia32_cvttps2dq512_mask:
1915 case X86::BI__builtin_ia32_cvttps2qq512_mask:
1916 case X86::BI__builtin_ia32_cvttps2udq512_mask:
1917 case X86::BI__builtin_ia32_cvttps2uqq512_mask:
1918 case X86::BI__builtin_ia32_exp2pd_mask:
1919 case X86::BI__builtin_ia32_exp2ps_mask:
1920 case X86::BI__builtin_ia32_getexppd512_mask:
1921 case X86::BI__builtin_ia32_getexpps512_mask:
1922 case X86::BI__builtin_ia32_rcp28pd_mask:
1923 case X86::BI__builtin_ia32_rcp28ps_mask:
1924 case X86::BI__builtin_ia32_rsqrt28pd_mask:
1925 case X86::BI__builtin_ia32_rsqrt28ps_mask:
1926 case X86::BI__builtin_ia32_vcomisd:
1927 case X86::BI__builtin_ia32_vcomiss:
1928 case X86::BI__builtin_ia32_vcvtph2ps512_mask:
1929 ArgNum = 3;
1930 break;
1931 case X86::BI__builtin_ia32_cmppd512_mask:
1932 case X86::BI__builtin_ia32_cmpps512_mask:
1933 case X86::BI__builtin_ia32_cmpsd_mask:
1934 case X86::BI__builtin_ia32_cmpss_mask:
Craig Topper8e066312016-11-07 07:01:09 +00001935 case X86::BI__builtin_ia32_cvtss2sd_round_mask:
Craig Toppera7e253e2016-09-23 04:48:31 +00001936 case X86::BI__builtin_ia32_getexpsd128_round_mask:
1937 case X86::BI__builtin_ia32_getexpss128_round_mask:
Craig Topper8e066312016-11-07 07:01:09 +00001938 case X86::BI__builtin_ia32_maxpd512_mask:
1939 case X86::BI__builtin_ia32_maxps512_mask:
1940 case X86::BI__builtin_ia32_maxsd_round_mask:
1941 case X86::BI__builtin_ia32_maxss_round_mask:
1942 case X86::BI__builtin_ia32_minpd512_mask:
1943 case X86::BI__builtin_ia32_minps512_mask:
1944 case X86::BI__builtin_ia32_minsd_round_mask:
1945 case X86::BI__builtin_ia32_minss_round_mask:
Craig Toppera7e253e2016-09-23 04:48:31 +00001946 case X86::BI__builtin_ia32_rcp28sd_round_mask:
1947 case X86::BI__builtin_ia32_rcp28ss_round_mask:
1948 case X86::BI__builtin_ia32_reducepd512_mask:
1949 case X86::BI__builtin_ia32_reduceps512_mask:
1950 case X86::BI__builtin_ia32_rndscalepd_mask:
1951 case X86::BI__builtin_ia32_rndscaleps_mask:
1952 case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
1953 case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
1954 ArgNum = 4;
1955 break;
1956 case X86::BI__builtin_ia32_fixupimmpd512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001957 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001958 case X86::BI__builtin_ia32_fixupimmps512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001959 case X86::BI__builtin_ia32_fixupimmps512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001960 case X86::BI__builtin_ia32_fixupimmsd_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001961 case X86::BI__builtin_ia32_fixupimmsd_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001962 case X86::BI__builtin_ia32_fixupimmss_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001963 case X86::BI__builtin_ia32_fixupimmss_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001964 case X86::BI__builtin_ia32_rangepd512_mask:
1965 case X86::BI__builtin_ia32_rangeps512_mask:
1966 case X86::BI__builtin_ia32_rangesd128_round_mask:
1967 case X86::BI__builtin_ia32_rangess128_round_mask:
1968 case X86::BI__builtin_ia32_reducesd_mask:
1969 case X86::BI__builtin_ia32_reducess_mask:
1970 case X86::BI__builtin_ia32_rndscalesd_round_mask:
1971 case X86::BI__builtin_ia32_rndscaless_round_mask:
1972 ArgNum = 5;
1973 break;
Craig Topper7609f1c2016-10-01 21:03:50 +00001974 case X86::BI__builtin_ia32_vcvtsd2si64:
1975 case X86::BI__builtin_ia32_vcvtsd2si32:
1976 case X86::BI__builtin_ia32_vcvtsd2usi32:
1977 case X86::BI__builtin_ia32_vcvtsd2usi64:
1978 case X86::BI__builtin_ia32_vcvtss2si32:
1979 case X86::BI__builtin_ia32_vcvtss2si64:
1980 case X86::BI__builtin_ia32_vcvtss2usi32:
1981 case X86::BI__builtin_ia32_vcvtss2usi64:
1982 ArgNum = 1;
1983 HasRC = true;
1984 break;
Craig Topper8e066312016-11-07 07:01:09 +00001985 case X86::BI__builtin_ia32_cvtsi2sd64:
1986 case X86::BI__builtin_ia32_cvtsi2ss32:
1987 case X86::BI__builtin_ia32_cvtsi2ss64:
Craig Topper7609f1c2016-10-01 21:03:50 +00001988 case X86::BI__builtin_ia32_cvtusi2sd64:
1989 case X86::BI__builtin_ia32_cvtusi2ss32:
1990 case X86::BI__builtin_ia32_cvtusi2ss64:
1991 ArgNum = 2;
1992 HasRC = true;
1993 break;
1994 case X86::BI__builtin_ia32_cvtdq2ps512_mask:
1995 case X86::BI__builtin_ia32_cvtudq2ps512_mask:
1996 case X86::BI__builtin_ia32_cvtpd2ps512_mask:
1997 case X86::BI__builtin_ia32_cvtpd2qq512_mask:
1998 case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
1999 case X86::BI__builtin_ia32_cvtps2qq512_mask:
2000 case X86::BI__builtin_ia32_cvtps2uqq512_mask:
2001 case X86::BI__builtin_ia32_cvtqq2pd512_mask:
2002 case X86::BI__builtin_ia32_cvtqq2ps512_mask:
2003 case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
2004 case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
Craig Topper8e066312016-11-07 07:01:09 +00002005 case X86::BI__builtin_ia32_sqrtpd512_mask:
2006 case X86::BI__builtin_ia32_sqrtps512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002007 ArgNum = 3;
2008 HasRC = true;
2009 break;
2010 case X86::BI__builtin_ia32_addpd512_mask:
2011 case X86::BI__builtin_ia32_addps512_mask:
2012 case X86::BI__builtin_ia32_divpd512_mask:
2013 case X86::BI__builtin_ia32_divps512_mask:
2014 case X86::BI__builtin_ia32_mulpd512_mask:
2015 case X86::BI__builtin_ia32_mulps512_mask:
2016 case X86::BI__builtin_ia32_subpd512_mask:
2017 case X86::BI__builtin_ia32_subps512_mask:
2018 case X86::BI__builtin_ia32_addss_round_mask:
2019 case X86::BI__builtin_ia32_addsd_round_mask:
2020 case X86::BI__builtin_ia32_divss_round_mask:
2021 case X86::BI__builtin_ia32_divsd_round_mask:
2022 case X86::BI__builtin_ia32_mulss_round_mask:
2023 case X86::BI__builtin_ia32_mulsd_round_mask:
2024 case X86::BI__builtin_ia32_subss_round_mask:
2025 case X86::BI__builtin_ia32_subsd_round_mask:
2026 case X86::BI__builtin_ia32_scalefpd512_mask:
2027 case X86::BI__builtin_ia32_scalefps512_mask:
2028 case X86::BI__builtin_ia32_scalefsd_round_mask:
2029 case X86::BI__builtin_ia32_scalefss_round_mask:
2030 case X86::BI__builtin_ia32_getmantpd512_mask:
2031 case X86::BI__builtin_ia32_getmantps512_mask:
Craig Topper8e066312016-11-07 07:01:09 +00002032 case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
2033 case X86::BI__builtin_ia32_sqrtsd_round_mask:
2034 case X86::BI__builtin_ia32_sqrtss_round_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002035 case X86::BI__builtin_ia32_vfmaddpd512_mask:
2036 case X86::BI__builtin_ia32_vfmaddpd512_mask3:
2037 case X86::BI__builtin_ia32_vfmaddpd512_maskz:
2038 case X86::BI__builtin_ia32_vfmaddps512_mask:
2039 case X86::BI__builtin_ia32_vfmaddps512_mask3:
2040 case X86::BI__builtin_ia32_vfmaddps512_maskz:
2041 case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
2042 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
2043 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
2044 case X86::BI__builtin_ia32_vfmaddsubps512_mask:
2045 case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
2046 case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
2047 case X86::BI__builtin_ia32_vfmsubpd512_mask3:
2048 case X86::BI__builtin_ia32_vfmsubps512_mask3:
2049 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
2050 case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
2051 case X86::BI__builtin_ia32_vfnmaddpd512_mask:
2052 case X86::BI__builtin_ia32_vfnmaddps512_mask:
2053 case X86::BI__builtin_ia32_vfnmsubpd512_mask:
2054 case X86::BI__builtin_ia32_vfnmsubpd512_mask3:
2055 case X86::BI__builtin_ia32_vfnmsubps512_mask:
2056 case X86::BI__builtin_ia32_vfnmsubps512_mask3:
2057 case X86::BI__builtin_ia32_vfmaddsd3_mask:
2058 case X86::BI__builtin_ia32_vfmaddsd3_maskz:
2059 case X86::BI__builtin_ia32_vfmaddsd3_mask3:
2060 case X86::BI__builtin_ia32_vfmaddss3_mask:
2061 case X86::BI__builtin_ia32_vfmaddss3_maskz:
2062 case X86::BI__builtin_ia32_vfmaddss3_mask3:
2063 ArgNum = 4;
2064 HasRC = true;
2065 break;
2066 case X86::BI__builtin_ia32_getmantsd_round_mask:
2067 case X86::BI__builtin_ia32_getmantss_round_mask:
2068 ArgNum = 5;
2069 HasRC = true;
2070 break;
Craig Toppera7e253e2016-09-23 04:48:31 +00002071 }
2072
2073 llvm::APSInt Result;
2074
2075 // We can't check the value of a dependent argument.
2076 Expr *Arg = TheCall->getArg(ArgNum);
2077 if (Arg->isTypeDependent() || Arg->isValueDependent())
2078 return false;
2079
2080 // Check constant-ness first.
2081 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2082 return true;
2083
2084 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
2085 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
2086 // combined with ROUND_NO_EXC.
2087 if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
2088 Result == 8/*ROUND_NO_EXC*/ ||
2089 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
2090 return false;
2091
2092 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding)
2093 << Arg->getSourceRange();
2094}
2095
Craig Topperdf5beb22017-03-13 17:16:50 +00002096// Check if the gather/scatter scale is legal.
2097bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
2098 CallExpr *TheCall) {
2099 unsigned ArgNum = 0;
2100 switch (BuiltinID) {
2101 default:
2102 return false;
2103 case X86::BI__builtin_ia32_gatherpfdpd:
2104 case X86::BI__builtin_ia32_gatherpfdps:
2105 case X86::BI__builtin_ia32_gatherpfqpd:
2106 case X86::BI__builtin_ia32_gatherpfqps:
2107 case X86::BI__builtin_ia32_scatterpfdpd:
2108 case X86::BI__builtin_ia32_scatterpfdps:
2109 case X86::BI__builtin_ia32_scatterpfqpd:
2110 case X86::BI__builtin_ia32_scatterpfqps:
2111 ArgNum = 3;
2112 break;
2113 case X86::BI__builtin_ia32_gatherd_pd:
2114 case X86::BI__builtin_ia32_gatherd_pd256:
2115 case X86::BI__builtin_ia32_gatherq_pd:
2116 case X86::BI__builtin_ia32_gatherq_pd256:
2117 case X86::BI__builtin_ia32_gatherd_ps:
2118 case X86::BI__builtin_ia32_gatherd_ps256:
2119 case X86::BI__builtin_ia32_gatherq_ps:
2120 case X86::BI__builtin_ia32_gatherq_ps256:
2121 case X86::BI__builtin_ia32_gatherd_q:
2122 case X86::BI__builtin_ia32_gatherd_q256:
2123 case X86::BI__builtin_ia32_gatherq_q:
2124 case X86::BI__builtin_ia32_gatherq_q256:
2125 case X86::BI__builtin_ia32_gatherd_d:
2126 case X86::BI__builtin_ia32_gatherd_d256:
2127 case X86::BI__builtin_ia32_gatherq_d:
2128 case X86::BI__builtin_ia32_gatherq_d256:
2129 case X86::BI__builtin_ia32_gather3div2df:
2130 case X86::BI__builtin_ia32_gather3div2di:
2131 case X86::BI__builtin_ia32_gather3div4df:
2132 case X86::BI__builtin_ia32_gather3div4di:
2133 case X86::BI__builtin_ia32_gather3div4sf:
2134 case X86::BI__builtin_ia32_gather3div4si:
2135 case X86::BI__builtin_ia32_gather3div8sf:
2136 case X86::BI__builtin_ia32_gather3div8si:
2137 case X86::BI__builtin_ia32_gather3siv2df:
2138 case X86::BI__builtin_ia32_gather3siv2di:
2139 case X86::BI__builtin_ia32_gather3siv4df:
2140 case X86::BI__builtin_ia32_gather3siv4di:
2141 case X86::BI__builtin_ia32_gather3siv4sf:
2142 case X86::BI__builtin_ia32_gather3siv4si:
2143 case X86::BI__builtin_ia32_gather3siv8sf:
2144 case X86::BI__builtin_ia32_gather3siv8si:
2145 case X86::BI__builtin_ia32_gathersiv8df:
2146 case X86::BI__builtin_ia32_gathersiv16sf:
2147 case X86::BI__builtin_ia32_gatherdiv8df:
2148 case X86::BI__builtin_ia32_gatherdiv16sf:
2149 case X86::BI__builtin_ia32_gathersiv8di:
2150 case X86::BI__builtin_ia32_gathersiv16si:
2151 case X86::BI__builtin_ia32_gatherdiv8di:
2152 case X86::BI__builtin_ia32_gatherdiv16si:
2153 case X86::BI__builtin_ia32_scatterdiv2df:
2154 case X86::BI__builtin_ia32_scatterdiv2di:
2155 case X86::BI__builtin_ia32_scatterdiv4df:
2156 case X86::BI__builtin_ia32_scatterdiv4di:
2157 case X86::BI__builtin_ia32_scatterdiv4sf:
2158 case X86::BI__builtin_ia32_scatterdiv4si:
2159 case X86::BI__builtin_ia32_scatterdiv8sf:
2160 case X86::BI__builtin_ia32_scatterdiv8si:
2161 case X86::BI__builtin_ia32_scattersiv2df:
2162 case X86::BI__builtin_ia32_scattersiv2di:
2163 case X86::BI__builtin_ia32_scattersiv4df:
2164 case X86::BI__builtin_ia32_scattersiv4di:
2165 case X86::BI__builtin_ia32_scattersiv4sf:
2166 case X86::BI__builtin_ia32_scattersiv4si:
2167 case X86::BI__builtin_ia32_scattersiv8sf:
2168 case X86::BI__builtin_ia32_scattersiv8si:
2169 case X86::BI__builtin_ia32_scattersiv8df:
2170 case X86::BI__builtin_ia32_scattersiv16sf:
2171 case X86::BI__builtin_ia32_scatterdiv8df:
2172 case X86::BI__builtin_ia32_scatterdiv16sf:
2173 case X86::BI__builtin_ia32_scattersiv8di:
2174 case X86::BI__builtin_ia32_scattersiv16si:
2175 case X86::BI__builtin_ia32_scatterdiv8di:
2176 case X86::BI__builtin_ia32_scatterdiv16si:
2177 ArgNum = 4;
2178 break;
2179 }
2180
2181 llvm::APSInt Result;
2182
2183 // We can't check the value of a dependent argument.
2184 Expr *Arg = TheCall->getArg(ArgNum);
2185 if (Arg->isTypeDependent() || Arg->isValueDependent())
2186 return false;
2187
2188 // Check constant-ness first.
2189 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2190 return true;
2191
2192 if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
2193 return false;
2194
2195 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_scale)
2196 << Arg->getSourceRange();
2197}
2198
Craig Topperf0ddc892016-09-23 04:48:27 +00002199bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2200 if (BuiltinID == X86::BI__builtin_cpu_supports)
2201 return SemaBuiltinCpuSupports(*this, TheCall);
2202
Craig Topper699ae0c2017-08-10 20:28:30 +00002203 if (BuiltinID == X86::BI__builtin_cpu_is)
2204 return SemaBuiltinCpuIs(*this, TheCall);
2205
Craig Toppera7e253e2016-09-23 04:48:31 +00002206 // If the intrinsic has rounding or SAE make sure its valid.
2207 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
2208 return true;
2209
Craig Topperdf5beb22017-03-13 17:16:50 +00002210 // If the intrinsic has a gather/scatter scale immediate make sure its valid.
2211 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
2212 return true;
2213
Craig Topperf0ddc892016-09-23 04:48:27 +00002214 // For intrinsics which take an immediate value as part of the instruction,
2215 // range check them here.
2216 int i = 0, l = 0, u = 0;
2217 switch (BuiltinID) {
2218 default:
2219 return false;
Richard Trieucc3949d2016-02-18 22:34:54 +00002220 case X86::BI_mm_prefetch:
Craig Topper39c87102016-05-18 03:18:12 +00002221 i = 1; l = 0; u = 3;
2222 break;
Richard Trieucc3949d2016-02-18 22:34:54 +00002223 case X86::BI__builtin_ia32_sha1rnds4:
Craig Topper39c87102016-05-18 03:18:12 +00002224 case X86::BI__builtin_ia32_shuf_f32x4_256_mask:
2225 case X86::BI__builtin_ia32_shuf_f64x2_256_mask:
2226 case X86::BI__builtin_ia32_shuf_i32x4_256_mask:
2227 case X86::BI__builtin_ia32_shuf_i64x2_256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002228 i = 2; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00002229 break;
Craig Topper1a8b0472015-01-31 08:57:52 +00002230 case X86::BI__builtin_ia32_vpermil2pd:
2231 case X86::BI__builtin_ia32_vpermil2pd256:
2232 case X86::BI__builtin_ia32_vpermil2ps:
Richard Trieucc3949d2016-02-18 22:34:54 +00002233 case X86::BI__builtin_ia32_vpermil2ps256:
Craig Topper39c87102016-05-18 03:18:12 +00002234 i = 3; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00002235 break;
Craig Topper95b0d732015-01-25 23:30:05 +00002236 case X86::BI__builtin_ia32_cmpb128_mask:
2237 case X86::BI__builtin_ia32_cmpw128_mask:
2238 case X86::BI__builtin_ia32_cmpd128_mask:
2239 case X86::BI__builtin_ia32_cmpq128_mask:
2240 case X86::BI__builtin_ia32_cmpb256_mask:
2241 case X86::BI__builtin_ia32_cmpw256_mask:
2242 case X86::BI__builtin_ia32_cmpd256_mask:
2243 case X86::BI__builtin_ia32_cmpq256_mask:
2244 case X86::BI__builtin_ia32_cmpb512_mask:
2245 case X86::BI__builtin_ia32_cmpw512_mask:
2246 case X86::BI__builtin_ia32_cmpd512_mask:
2247 case X86::BI__builtin_ia32_cmpq512_mask:
2248 case X86::BI__builtin_ia32_ucmpb128_mask:
2249 case X86::BI__builtin_ia32_ucmpw128_mask:
2250 case X86::BI__builtin_ia32_ucmpd128_mask:
2251 case X86::BI__builtin_ia32_ucmpq128_mask:
2252 case X86::BI__builtin_ia32_ucmpb256_mask:
2253 case X86::BI__builtin_ia32_ucmpw256_mask:
2254 case X86::BI__builtin_ia32_ucmpd256_mask:
2255 case X86::BI__builtin_ia32_ucmpq256_mask:
2256 case X86::BI__builtin_ia32_ucmpb512_mask:
2257 case X86::BI__builtin_ia32_ucmpw512_mask:
2258 case X86::BI__builtin_ia32_ucmpd512_mask:
Richard Trieucc3949d2016-02-18 22:34:54 +00002259 case X86::BI__builtin_ia32_ucmpq512_mask:
Craig Topper8dd7d0d2015-02-13 06:04:48 +00002260 case X86::BI__builtin_ia32_vpcomub:
2261 case X86::BI__builtin_ia32_vpcomuw:
2262 case X86::BI__builtin_ia32_vpcomud:
2263 case X86::BI__builtin_ia32_vpcomuq:
2264 case X86::BI__builtin_ia32_vpcomb:
2265 case X86::BI__builtin_ia32_vpcomw:
2266 case X86::BI__builtin_ia32_vpcomd:
Richard Trieucc3949d2016-02-18 22:34:54 +00002267 case X86::BI__builtin_ia32_vpcomq:
Craig Topper39c87102016-05-18 03:18:12 +00002268 i = 2; l = 0; u = 7;
2269 break;
2270 case X86::BI__builtin_ia32_roundps:
2271 case X86::BI__builtin_ia32_roundpd:
2272 case X86::BI__builtin_ia32_roundps256:
2273 case X86::BI__builtin_ia32_roundpd256:
Craig Topper39c87102016-05-18 03:18:12 +00002274 i = 1; l = 0; u = 15;
2275 break;
2276 case X86::BI__builtin_ia32_roundss:
2277 case X86::BI__builtin_ia32_roundsd:
2278 case X86::BI__builtin_ia32_rangepd128_mask:
2279 case X86::BI__builtin_ia32_rangepd256_mask:
2280 case X86::BI__builtin_ia32_rangepd512_mask:
2281 case X86::BI__builtin_ia32_rangeps128_mask:
2282 case X86::BI__builtin_ia32_rangeps256_mask:
2283 case X86::BI__builtin_ia32_rangeps512_mask:
2284 case X86::BI__builtin_ia32_getmantsd_round_mask:
2285 case X86::BI__builtin_ia32_getmantss_round_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002286 i = 2; l = 0; u = 15;
2287 break;
2288 case X86::BI__builtin_ia32_cmpps:
2289 case X86::BI__builtin_ia32_cmpss:
2290 case X86::BI__builtin_ia32_cmppd:
2291 case X86::BI__builtin_ia32_cmpsd:
2292 case X86::BI__builtin_ia32_cmpps256:
2293 case X86::BI__builtin_ia32_cmppd256:
2294 case X86::BI__builtin_ia32_cmpps128_mask:
2295 case X86::BI__builtin_ia32_cmppd128_mask:
2296 case X86::BI__builtin_ia32_cmpps256_mask:
2297 case X86::BI__builtin_ia32_cmppd256_mask:
2298 case X86::BI__builtin_ia32_cmpps512_mask:
2299 case X86::BI__builtin_ia32_cmppd512_mask:
2300 case X86::BI__builtin_ia32_cmpsd_mask:
2301 case X86::BI__builtin_ia32_cmpss_mask:
2302 i = 2; l = 0; u = 31;
2303 break;
2304 case X86::BI__builtin_ia32_xabort:
2305 i = 0; l = -128; u = 255;
2306 break;
2307 case X86::BI__builtin_ia32_pshufw:
2308 case X86::BI__builtin_ia32_aeskeygenassist128:
2309 i = 1; l = -128; u = 255;
2310 break;
2311 case X86::BI__builtin_ia32_vcvtps2ph:
2312 case X86::BI__builtin_ia32_vcvtps2ph256:
Craig Topper39c87102016-05-18 03:18:12 +00002313 case X86::BI__builtin_ia32_rndscaleps_128_mask:
2314 case X86::BI__builtin_ia32_rndscalepd_128_mask:
2315 case X86::BI__builtin_ia32_rndscaleps_256_mask:
2316 case X86::BI__builtin_ia32_rndscalepd_256_mask:
2317 case X86::BI__builtin_ia32_rndscaleps_mask:
2318 case X86::BI__builtin_ia32_rndscalepd_mask:
2319 case X86::BI__builtin_ia32_reducepd128_mask:
2320 case X86::BI__builtin_ia32_reducepd256_mask:
2321 case X86::BI__builtin_ia32_reducepd512_mask:
2322 case X86::BI__builtin_ia32_reduceps128_mask:
2323 case X86::BI__builtin_ia32_reduceps256_mask:
2324 case X86::BI__builtin_ia32_reduceps512_mask:
2325 case X86::BI__builtin_ia32_prold512_mask:
2326 case X86::BI__builtin_ia32_prolq512_mask:
2327 case X86::BI__builtin_ia32_prold128_mask:
2328 case X86::BI__builtin_ia32_prold256_mask:
2329 case X86::BI__builtin_ia32_prolq128_mask:
2330 case X86::BI__builtin_ia32_prolq256_mask:
2331 case X86::BI__builtin_ia32_prord128_mask:
2332 case X86::BI__builtin_ia32_prord256_mask:
2333 case X86::BI__builtin_ia32_prorq128_mask:
2334 case X86::BI__builtin_ia32_prorq256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002335 case X86::BI__builtin_ia32_fpclasspd128_mask:
2336 case X86::BI__builtin_ia32_fpclasspd256_mask:
2337 case X86::BI__builtin_ia32_fpclassps128_mask:
2338 case X86::BI__builtin_ia32_fpclassps256_mask:
2339 case X86::BI__builtin_ia32_fpclassps512_mask:
2340 case X86::BI__builtin_ia32_fpclasspd512_mask:
2341 case X86::BI__builtin_ia32_fpclasssd_mask:
2342 case X86::BI__builtin_ia32_fpclassss_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002343 i = 1; l = 0; u = 255;
2344 break;
2345 case X86::BI__builtin_ia32_palignr:
2346 case X86::BI__builtin_ia32_insertps128:
2347 case X86::BI__builtin_ia32_dpps:
2348 case X86::BI__builtin_ia32_dppd:
2349 case X86::BI__builtin_ia32_dpps256:
2350 case X86::BI__builtin_ia32_mpsadbw128:
2351 case X86::BI__builtin_ia32_mpsadbw256:
2352 case X86::BI__builtin_ia32_pcmpistrm128:
2353 case X86::BI__builtin_ia32_pcmpistri128:
2354 case X86::BI__builtin_ia32_pcmpistria128:
2355 case X86::BI__builtin_ia32_pcmpistric128:
2356 case X86::BI__builtin_ia32_pcmpistrio128:
2357 case X86::BI__builtin_ia32_pcmpistris128:
2358 case X86::BI__builtin_ia32_pcmpistriz128:
2359 case X86::BI__builtin_ia32_pclmulqdq128:
2360 case X86::BI__builtin_ia32_vperm2f128_pd256:
2361 case X86::BI__builtin_ia32_vperm2f128_ps256:
2362 case X86::BI__builtin_ia32_vperm2f128_si256:
2363 case X86::BI__builtin_ia32_permti256:
2364 i = 2; l = -128; u = 255;
2365 break;
2366 case X86::BI__builtin_ia32_palignr128:
2367 case X86::BI__builtin_ia32_palignr256:
Craig Topper39c87102016-05-18 03:18:12 +00002368 case X86::BI__builtin_ia32_palignr512_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002369 case X86::BI__builtin_ia32_vcomisd:
2370 case X86::BI__builtin_ia32_vcomiss:
2371 case X86::BI__builtin_ia32_shuf_f32x4_mask:
2372 case X86::BI__builtin_ia32_shuf_f64x2_mask:
2373 case X86::BI__builtin_ia32_shuf_i32x4_mask:
2374 case X86::BI__builtin_ia32_shuf_i64x2_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002375 case X86::BI__builtin_ia32_dbpsadbw128_mask:
2376 case X86::BI__builtin_ia32_dbpsadbw256_mask:
2377 case X86::BI__builtin_ia32_dbpsadbw512_mask:
2378 i = 2; l = 0; u = 255;
2379 break;
2380 case X86::BI__builtin_ia32_fixupimmpd512_mask:
2381 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
2382 case X86::BI__builtin_ia32_fixupimmps512_mask:
2383 case X86::BI__builtin_ia32_fixupimmps512_maskz:
2384 case X86::BI__builtin_ia32_fixupimmsd_mask:
2385 case X86::BI__builtin_ia32_fixupimmsd_maskz:
2386 case X86::BI__builtin_ia32_fixupimmss_mask:
2387 case X86::BI__builtin_ia32_fixupimmss_maskz:
2388 case X86::BI__builtin_ia32_fixupimmpd128_mask:
2389 case X86::BI__builtin_ia32_fixupimmpd128_maskz:
2390 case X86::BI__builtin_ia32_fixupimmpd256_mask:
2391 case X86::BI__builtin_ia32_fixupimmpd256_maskz:
2392 case X86::BI__builtin_ia32_fixupimmps128_mask:
2393 case X86::BI__builtin_ia32_fixupimmps128_maskz:
2394 case X86::BI__builtin_ia32_fixupimmps256_mask:
2395 case X86::BI__builtin_ia32_fixupimmps256_maskz:
2396 case X86::BI__builtin_ia32_pternlogd512_mask:
2397 case X86::BI__builtin_ia32_pternlogd512_maskz:
2398 case X86::BI__builtin_ia32_pternlogq512_mask:
2399 case X86::BI__builtin_ia32_pternlogq512_maskz:
2400 case X86::BI__builtin_ia32_pternlogd128_mask:
2401 case X86::BI__builtin_ia32_pternlogd128_maskz:
2402 case X86::BI__builtin_ia32_pternlogd256_mask:
2403 case X86::BI__builtin_ia32_pternlogd256_maskz:
2404 case X86::BI__builtin_ia32_pternlogq128_mask:
2405 case X86::BI__builtin_ia32_pternlogq128_maskz:
2406 case X86::BI__builtin_ia32_pternlogq256_mask:
2407 case X86::BI__builtin_ia32_pternlogq256_maskz:
2408 i = 3; l = 0; u = 255;
2409 break;
Craig Topper9625db02017-03-12 22:19:10 +00002410 case X86::BI__builtin_ia32_gatherpfdpd:
2411 case X86::BI__builtin_ia32_gatherpfdps:
2412 case X86::BI__builtin_ia32_gatherpfqpd:
2413 case X86::BI__builtin_ia32_gatherpfqps:
2414 case X86::BI__builtin_ia32_scatterpfdpd:
2415 case X86::BI__builtin_ia32_scatterpfdps:
2416 case X86::BI__builtin_ia32_scatterpfqpd:
2417 case X86::BI__builtin_ia32_scatterpfqps:
Craig Topperf771f79b2017-03-31 17:22:30 +00002418 i = 4; l = 2; u = 3;
Craig Topper9625db02017-03-12 22:19:10 +00002419 break;
Craig Topper39c87102016-05-18 03:18:12 +00002420 case X86::BI__builtin_ia32_pcmpestrm128:
2421 case X86::BI__builtin_ia32_pcmpestri128:
2422 case X86::BI__builtin_ia32_pcmpestria128:
2423 case X86::BI__builtin_ia32_pcmpestric128:
2424 case X86::BI__builtin_ia32_pcmpestrio128:
2425 case X86::BI__builtin_ia32_pcmpestris128:
2426 case X86::BI__builtin_ia32_pcmpestriz128:
2427 i = 4; l = -128; u = 255;
2428 break;
2429 case X86::BI__builtin_ia32_rndscalesd_round_mask:
2430 case X86::BI__builtin_ia32_rndscaless_round_mask:
2431 i = 4; l = 0; u = 255;
Richard Trieucc3949d2016-02-18 22:34:54 +00002432 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002433 }
Craig Topperdd84ec52014-12-27 07:00:08 +00002434 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002435}
2436
Richard Smith55ce3522012-06-25 20:30:08 +00002437/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
2438/// parameter with the FormatAttr's correct format_idx and firstDataArg.
2439/// Returns true when the format fits the function and the FormatStringInfo has
2440/// been populated.
2441bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
2442 FormatStringInfo *FSI) {
2443 FSI->HasVAListArg = Format->getFirstArg() == 0;
2444 FSI->FormatIdx = Format->getFormatIdx() - 1;
2445 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002446
Richard Smith55ce3522012-06-25 20:30:08 +00002447 // The way the format attribute works in GCC, the implicit this argument
2448 // of member functions is counted. However, it doesn't appear in our own
2449 // lists, so decrement format_idx in that case.
2450 if (IsCXXMember) {
2451 if(FSI->FormatIdx == 0)
2452 return false;
2453 --FSI->FormatIdx;
2454 if (FSI->FirstDataArg != 0)
2455 --FSI->FirstDataArg;
2456 }
2457 return true;
2458}
Mike Stump11289f42009-09-09 15:08:12 +00002459
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002460/// Checks if a the given expression evaluates to null.
2461///
2462/// \brief Returns true if the value evaluates to null.
George Burgess IV850269a2015-12-08 22:02:00 +00002463static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002464 // If the expression has non-null type, it doesn't evaluate to null.
2465 if (auto nullability
2466 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
2467 if (*nullability == NullabilityKind::NonNull)
2468 return false;
2469 }
2470
Ted Kremeneka146db32014-01-17 06:24:47 +00002471 // As a special case, transparent unions initialized with zero are
2472 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002473 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +00002474 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2475 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002476 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +00002477 if (const InitListExpr *ILE =
2478 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002479 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +00002480 }
2481
2482 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +00002483 return (!Expr->isValueDependent() &&
2484 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
2485 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002486}
2487
2488static void CheckNonNullArgument(Sema &S,
2489 const Expr *ArgExpr,
2490 SourceLocation CallSiteLoc) {
2491 if (CheckNonNullExpr(S, ArgExpr))
Eric Fiselier18677d52015-10-09 00:17:57 +00002492 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
2493 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
Ted Kremeneka146db32014-01-17 06:24:47 +00002494}
2495
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002496bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
2497 FormatStringInfo FSI;
2498 if ((GetFormatStringType(Format) == FST_NSString) &&
2499 getFormatStringInfo(Format, false, &FSI)) {
2500 Idx = FSI.FormatIdx;
2501 return true;
2502 }
2503 return false;
2504}
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002505/// \brief Diagnose use of %s directive in an NSString which is being passed
2506/// as formatting string to formatting method.
2507static void
2508DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
2509 const NamedDecl *FDecl,
2510 Expr **Args,
2511 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002512 unsigned Idx = 0;
2513 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002514 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
2515 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002516 Idx = 2;
2517 Format = true;
2518 }
2519 else
2520 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2521 if (S.GetFormatNSStringIdx(I, Idx)) {
2522 Format = true;
2523 break;
2524 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002525 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002526 if (!Format || NumArgs <= Idx)
2527 return;
2528 const Expr *FormatExpr = Args[Idx];
2529 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
2530 FormatExpr = CSCE->getSubExpr();
2531 const StringLiteral *FormatString;
2532 if (const ObjCStringLiteral *OSL =
2533 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
2534 FormatString = OSL->getString();
2535 else
2536 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
2537 if (!FormatString)
2538 return;
2539 if (S.FormatStringHasSArg(FormatString)) {
2540 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2541 << "%s" << 1 << 1;
2542 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
2543 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002544 }
2545}
2546
Douglas Gregorb4866e82015-06-19 18:13:19 +00002547/// Determine whether the given type has a non-null nullability annotation.
2548static bool isNonNullType(ASTContext &ctx, QualType type) {
2549 if (auto nullability = type->getNullability(ctx))
2550 return *nullability == NullabilityKind::NonNull;
2551
2552 return false;
2553}
2554
Ted Kremenek2bc73332014-01-17 06:24:43 +00002555static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00002556 const NamedDecl *FDecl,
Douglas Gregorb4866e82015-06-19 18:13:19 +00002557 const FunctionProtoType *Proto,
Richard Smith588bd9b2014-08-27 04:59:42 +00002558 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00002559 SourceLocation CallSiteLoc) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002560 assert((FDecl || Proto) && "Need a function declaration or prototype");
2561
Ted Kremenek9aedc152014-01-17 06:24:56 +00002562 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00002563 llvm::SmallBitVector NonNullArgs;
Douglas Gregorb4866e82015-06-19 18:13:19 +00002564 if (FDecl) {
2565 // Handle the nonnull attribute on the function/method declaration itself.
2566 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
2567 if (!NonNull->args_size()) {
2568 // Easy case: all pointer arguments are nonnull.
2569 for (const auto *Arg : Args)
2570 if (S.isValidPointerAttrType(Arg->getType()))
2571 CheckNonNullArgument(S, Arg, CallSiteLoc);
2572 return;
2573 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002574
Douglas Gregorb4866e82015-06-19 18:13:19 +00002575 for (unsigned Val : NonNull->args()) {
2576 if (Val >= Args.size())
2577 continue;
2578 if (NonNullArgs.empty())
2579 NonNullArgs.resize(Args.size());
2580 NonNullArgs.set(Val);
2581 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002582 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00002583 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00002584
Douglas Gregorb4866e82015-06-19 18:13:19 +00002585 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
2586 // Handle the nonnull attribute on the parameters of the
2587 // function/method.
2588 ArrayRef<ParmVarDecl*> parms;
2589 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
2590 parms = FD->parameters();
2591 else
2592 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
2593
2594 unsigned ParamIndex = 0;
2595 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
2596 I != E; ++I, ++ParamIndex) {
2597 const ParmVarDecl *PVD = *I;
2598 if (PVD->hasAttr<NonNullAttr>() ||
2599 isNonNullType(S.Context, PVD->getType())) {
2600 if (NonNullArgs.empty())
2601 NonNullArgs.resize(Args.size());
Ted Kremenek9aedc152014-01-17 06:24:56 +00002602
Douglas Gregorb4866e82015-06-19 18:13:19 +00002603 NonNullArgs.set(ParamIndex);
2604 }
2605 }
2606 } else {
2607 // If we have a non-function, non-method declaration but no
2608 // function prototype, try to dig out the function prototype.
2609 if (!Proto) {
2610 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
2611 QualType type = VD->getType().getNonReferenceType();
2612 if (auto pointerType = type->getAs<PointerType>())
2613 type = pointerType->getPointeeType();
2614 else if (auto blockType = type->getAs<BlockPointerType>())
2615 type = blockType->getPointeeType();
2616 // FIXME: data member pointers?
2617
2618 // Dig out the function prototype, if there is one.
2619 Proto = type->getAs<FunctionProtoType>();
2620 }
2621 }
2622
2623 // Fill in non-null argument information from the nullability
2624 // information on the parameter types (if we have them).
2625 if (Proto) {
2626 unsigned Index = 0;
2627 for (auto paramType : Proto->getParamTypes()) {
2628 if (isNonNullType(S.Context, paramType)) {
2629 if (NonNullArgs.empty())
2630 NonNullArgs.resize(Args.size());
2631
2632 NonNullArgs.set(Index);
2633 }
2634
2635 ++Index;
2636 }
2637 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00002638 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002639
Douglas Gregorb4866e82015-06-19 18:13:19 +00002640 // Check for non-null arguments.
2641 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
2642 ArgIndex != ArgIndexEnd; ++ArgIndex) {
Richard Smith588bd9b2014-08-27 04:59:42 +00002643 if (NonNullArgs[ArgIndex])
2644 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00002645 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00002646}
2647
Richard Smith55ce3522012-06-25 20:30:08 +00002648/// Handles the checks for format strings, non-POD arguments to vararg
George Burgess IVce6284b2017-01-28 02:19:40 +00002649/// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
2650/// attributes.
Douglas Gregorb4866e82015-06-19 18:13:19 +00002651void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
George Burgess IVce6284b2017-01-28 02:19:40 +00002652 const Expr *ThisArg, ArrayRef<const Expr *> Args,
2653 bool IsMemberFunction, SourceLocation Loc,
2654 SourceRange Range, VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00002655 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00002656 if (CurContext->isDependentContext())
2657 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00002658
Ted Kremenekb8176da2010-09-09 04:33:05 +00002659 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00002660 llvm::SmallBitVector CheckedVarArgs;
2661 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002662 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00002663 // Only create vector if there are format attributes.
2664 CheckedVarArgs.resize(Args.size());
2665
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002666 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00002667 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00002668 }
Richard Smithd7293d72013-08-05 18:49:43 +00002669 }
Richard Smith55ce3522012-06-25 20:30:08 +00002670
2671 // Refuse POD arguments that weren't caught by the format string
2672 // checks above.
Richard Smith836de6b2016-12-19 23:59:34 +00002673 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
2674 if (CallType != VariadicDoesNotApply &&
2675 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002676 unsigned NumParams = Proto ? Proto->getNumParams()
2677 : FDecl && isa<FunctionDecl>(FDecl)
2678 ? cast<FunctionDecl>(FDecl)->getNumParams()
2679 : FDecl && isa<ObjCMethodDecl>(FDecl)
2680 ? cast<ObjCMethodDecl>(FDecl)->param_size()
2681 : 0;
2682
Alp Toker9cacbab2014-01-20 20:26:09 +00002683 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00002684 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00002685 if (const Expr *Arg = Args[ArgIdx]) {
2686 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
2687 checkVariadicArgument(Arg, CallType);
2688 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00002689 }
Richard Smithd7293d72013-08-05 18:49:43 +00002690 }
Mike Stump11289f42009-09-09 15:08:12 +00002691
Douglas Gregorb4866e82015-06-19 18:13:19 +00002692 if (FDecl || Proto) {
2693 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00002694
Richard Trieu41bc0992013-06-22 00:20:41 +00002695 // Type safety checking.
Douglas Gregorb4866e82015-06-19 18:13:19 +00002696 if (FDecl) {
2697 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
2698 CheckArgumentWithTypeTag(I, Args.data());
2699 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00002700 }
George Burgess IVce6284b2017-01-28 02:19:40 +00002701
2702 if (FD)
2703 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
Richard Smith55ce3522012-06-25 20:30:08 +00002704}
2705
2706/// CheckConstructorCall - Check a constructor call for correctness and safety
2707/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002708void Sema::CheckConstructorCall(FunctionDecl *FDecl,
2709 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002710 const FunctionProtoType *Proto,
2711 SourceLocation Loc) {
2712 VariadicCallType CallType =
2713 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
George Burgess IVce6284b2017-01-28 02:19:40 +00002714 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
2715 Loc, SourceRange(), CallType);
Richard Smith55ce3522012-06-25 20:30:08 +00002716}
2717
2718/// CheckFunctionCall - Check a direct function call for various correctness
2719/// and safety properties not strictly enforced by the C type system.
2720bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
2721 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00002722 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
2723 isa<CXXMethodDecl>(FDecl);
2724 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
2725 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00002726 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
2727 TheCall->getCallee());
Eli Friedman726d11c2012-10-11 00:30:58 +00002728 Expr** Args = TheCall->getArgs();
2729 unsigned NumArgs = TheCall->getNumArgs();
George Burgess IVce6284b2017-01-28 02:19:40 +00002730
2731 Expr *ImplicitThis = nullptr;
Eli Friedmanadf42182012-10-11 00:34:15 +00002732 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00002733 // If this is a call to a member operator, hide the first argument
2734 // from checkCall.
2735 // FIXME: Our choice of AST representation here is less than ideal.
George Burgess IVce6284b2017-01-28 02:19:40 +00002736 ImplicitThis = Args[0];
Eli Friedman726d11c2012-10-11 00:30:58 +00002737 ++Args;
2738 --NumArgs;
George Burgess IVce6284b2017-01-28 02:19:40 +00002739 } else if (IsMemberFunction)
2740 ImplicitThis =
2741 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
2742
2743 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
Richard Smith55ce3522012-06-25 20:30:08 +00002744 IsMemberFunction, TheCall->getRParenLoc(),
2745 TheCall->getCallee()->getSourceRange(), CallType);
2746
2747 IdentifierInfo *FnInfo = FDecl->getIdentifier();
2748 // None of the checks below are needed for functions that don't have
2749 // simple names (e.g., C++ conversion functions).
2750 if (!FnInfo)
2751 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002752
Richard Trieua7f30b12016-12-06 01:42:28 +00002753 CheckAbsoluteValueFunction(TheCall, FDecl);
2754 CheckMaxUnsignedZero(TheCall, FDecl);
Richard Trieu67c00712016-12-05 23:41:46 +00002755
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002756 if (getLangOpts().ObjC1)
2757 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00002758
Anna Zaks22122702012-01-17 00:37:07 +00002759 unsigned CMId = FDecl->getMemoryFunctionKind();
2760 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00002761 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00002762
Anna Zaks201d4892012-01-13 21:52:01 +00002763 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00002764 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00002765 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00002766 else if (CMId == Builtin::BIstrncat)
2767 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00002768 else
Anna Zaks22122702012-01-17 00:37:07 +00002769 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00002770
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002771 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00002772}
2773
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002774bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00002775 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00002776 VariadicCallType CallType =
2777 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002778
George Burgess IVce6284b2017-01-28 02:19:40 +00002779 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
2780 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
Douglas Gregorb4866e82015-06-19 18:13:19 +00002781 CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002782
2783 return false;
2784}
2785
Richard Trieu664c4c62013-06-20 21:03:13 +00002786bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
2787 const FunctionProtoType *Proto) {
Aaron Ballmanb673c652015-04-23 16:14:19 +00002788 QualType Ty;
2789 if (const auto *V = dyn_cast<VarDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00002790 Ty = V->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00002791 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00002792 Ty = F->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00002793 else
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002794 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002795
Douglas Gregorb4866e82015-06-19 18:13:19 +00002796 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
2797 !Ty->isFunctionProtoType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002798 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002799
Richard Trieu664c4c62013-06-20 21:03:13 +00002800 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00002801 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00002802 CallType = VariadicDoesNotApply;
2803 } else if (Ty->isBlockPointerType()) {
2804 CallType = VariadicBlock;
2805 } else { // Ty->isFunctionPointerType()
2806 CallType = VariadicFunction;
2807 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002808
George Burgess IVce6284b2017-01-28 02:19:40 +00002809 checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
Douglas Gregorb4866e82015-06-19 18:13:19 +00002810 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2811 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00002812 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00002813
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002814 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00002815}
2816
Richard Trieu41bc0992013-06-22 00:20:41 +00002817/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
2818/// such as function pointers returned from functions.
2819bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002820 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00002821 TheCall->getCallee());
George Burgess IVce6284b2017-01-28 02:19:40 +00002822 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
Craig Topper8c2a2a02014-08-30 16:55:39 +00002823 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Douglas Gregorb4866e82015-06-19 18:13:19 +00002824 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00002825 TheCall->getCallee()->getSourceRange(), CallType);
2826
2827 return false;
2828}
2829
Tim Northovere94a34c2014-03-11 10:49:14 +00002830static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
JF Bastiendda2cb12016-04-18 18:01:49 +00002831 if (!llvm::isValidAtomicOrderingCABI(Ordering))
Tim Northovere94a34c2014-03-11 10:49:14 +00002832 return false;
2833
JF Bastiendda2cb12016-04-18 18:01:49 +00002834 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
Tim Northovere94a34c2014-03-11 10:49:14 +00002835 switch (Op) {
2836 case AtomicExpr::AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +00002837 case AtomicExpr::AO__opencl_atomic_init:
Tim Northovere94a34c2014-03-11 10:49:14 +00002838 llvm_unreachable("There is no ordering argument for an init");
2839
2840 case AtomicExpr::AO__c11_atomic_load:
Yaxun Liu39195062017-08-04 18:16:31 +00002841 case AtomicExpr::AO__opencl_atomic_load:
Tim Northovere94a34c2014-03-11 10:49:14 +00002842 case AtomicExpr::AO__atomic_load_n:
2843 case AtomicExpr::AO__atomic_load:
JF Bastiendda2cb12016-04-18 18:01:49 +00002844 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
2845 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00002846
2847 case AtomicExpr::AO__c11_atomic_store:
Yaxun Liu39195062017-08-04 18:16:31 +00002848 case AtomicExpr::AO__opencl_atomic_store:
Tim Northovere94a34c2014-03-11 10:49:14 +00002849 case AtomicExpr::AO__atomic_store:
2850 case AtomicExpr::AO__atomic_store_n:
JF Bastiendda2cb12016-04-18 18:01:49 +00002851 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
2852 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
2853 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00002854
2855 default:
2856 return true;
2857 }
2858}
2859
Richard Smithfeea8832012-04-12 05:08:17 +00002860ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
2861 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002862 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
2863 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002864
Yaxun Liu39195062017-08-04 18:16:31 +00002865 // All the non-OpenCL operations take one of the following forms.
2866 // The OpenCL operations take the __c11 forms with one extra argument for
2867 // synchronization scope.
Richard Smithfeea8832012-04-12 05:08:17 +00002868 enum {
2869 // C __c11_atomic_init(A *, C)
2870 Init,
2871 // C __c11_atomic_load(A *, int)
2872 Load,
2873 // void __atomic_load(A *, CP, int)
Eric Fiselier8d662442016-03-30 23:39:56 +00002874 LoadCopy,
2875 // void __atomic_store(A *, CP, int)
Richard Smithfeea8832012-04-12 05:08:17 +00002876 Copy,
2877 // C __c11_atomic_add(A *, M, int)
2878 Arithmetic,
2879 // C __atomic_exchange_n(A *, CP, int)
2880 Xchg,
2881 // void __atomic_exchange(A *, C *, CP, int)
2882 GNUXchg,
2883 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
2884 C11CmpXchg,
2885 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
2886 GNUCmpXchg
2887 } Form = Init;
Yaxun Liu39195062017-08-04 18:16:31 +00002888 const unsigned NumForm = GNUCmpXchg + 1;
Eric Fiselier8d662442016-03-30 23:39:56 +00002889 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
2890 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
Richard Smithfeea8832012-04-12 05:08:17 +00002891 // where:
2892 // C is an appropriate type,
2893 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
2894 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
2895 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
2896 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002897
Yaxun Liu39195062017-08-04 18:16:31 +00002898 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
2899 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
2900 "need to update code for modified forms");
Gabor Horvath98bd0982015-03-16 09:59:54 +00002901 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
2902 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
2903 AtomicExpr::AO__atomic_load,
2904 "need to update code for modified C11 atomics");
Yaxun Liu39195062017-08-04 18:16:31 +00002905 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
2906 Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
2907 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
2908 Op <= AtomicExpr::AO__c11_atomic_fetch_xor) ||
2909 IsOpenCL;
Richard Smithfeea8832012-04-12 05:08:17 +00002910 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
2911 Op == AtomicExpr::AO__atomic_store_n ||
2912 Op == AtomicExpr::AO__atomic_exchange_n ||
2913 Op == AtomicExpr::AO__atomic_compare_exchange_n;
2914 bool IsAddSub = false;
2915
2916 switch (Op) {
2917 case AtomicExpr::AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +00002918 case AtomicExpr::AO__opencl_atomic_init:
Richard Smithfeea8832012-04-12 05:08:17 +00002919 Form = Init;
2920 break;
2921
2922 case AtomicExpr::AO__c11_atomic_load:
Yaxun Liu39195062017-08-04 18:16:31 +00002923 case AtomicExpr::AO__opencl_atomic_load:
Richard Smithfeea8832012-04-12 05:08:17 +00002924 case AtomicExpr::AO__atomic_load_n:
2925 Form = Load;
2926 break;
2927
Richard Smithfeea8832012-04-12 05:08:17 +00002928 case AtomicExpr::AO__atomic_load:
Eric Fiselier8d662442016-03-30 23:39:56 +00002929 Form = LoadCopy;
2930 break;
2931
2932 case AtomicExpr::AO__c11_atomic_store:
Yaxun Liu39195062017-08-04 18:16:31 +00002933 case AtomicExpr::AO__opencl_atomic_store:
Richard Smithfeea8832012-04-12 05:08:17 +00002934 case AtomicExpr::AO__atomic_store:
2935 case AtomicExpr::AO__atomic_store_n:
2936 Form = Copy;
2937 break;
2938
2939 case AtomicExpr::AO__c11_atomic_fetch_add:
2940 case AtomicExpr::AO__c11_atomic_fetch_sub:
Yaxun Liu39195062017-08-04 18:16:31 +00002941 case AtomicExpr::AO__opencl_atomic_fetch_add:
2942 case AtomicExpr::AO__opencl_atomic_fetch_sub:
2943 case AtomicExpr::AO__opencl_atomic_fetch_min:
2944 case AtomicExpr::AO__opencl_atomic_fetch_max:
Richard Smithfeea8832012-04-12 05:08:17 +00002945 case AtomicExpr::AO__atomic_fetch_add:
2946 case AtomicExpr::AO__atomic_fetch_sub:
2947 case AtomicExpr::AO__atomic_add_fetch:
2948 case AtomicExpr::AO__atomic_sub_fetch:
2949 IsAddSub = true;
2950 // Fall through.
2951 case AtomicExpr::AO__c11_atomic_fetch_and:
2952 case AtomicExpr::AO__c11_atomic_fetch_or:
2953 case AtomicExpr::AO__c11_atomic_fetch_xor:
Yaxun Liu39195062017-08-04 18:16:31 +00002954 case AtomicExpr::AO__opencl_atomic_fetch_and:
2955 case AtomicExpr::AO__opencl_atomic_fetch_or:
2956 case AtomicExpr::AO__opencl_atomic_fetch_xor:
Richard Smithfeea8832012-04-12 05:08:17 +00002957 case AtomicExpr::AO__atomic_fetch_and:
2958 case AtomicExpr::AO__atomic_fetch_or:
2959 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00002960 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00002961 case AtomicExpr::AO__atomic_and_fetch:
2962 case AtomicExpr::AO__atomic_or_fetch:
2963 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00002964 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00002965 Form = Arithmetic;
2966 break;
2967
2968 case AtomicExpr::AO__c11_atomic_exchange:
Yaxun Liu39195062017-08-04 18:16:31 +00002969 case AtomicExpr::AO__opencl_atomic_exchange:
Richard Smithfeea8832012-04-12 05:08:17 +00002970 case AtomicExpr::AO__atomic_exchange_n:
2971 Form = Xchg;
2972 break;
2973
2974 case AtomicExpr::AO__atomic_exchange:
2975 Form = GNUXchg;
2976 break;
2977
2978 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
2979 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
Yaxun Liu39195062017-08-04 18:16:31 +00002980 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
2981 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
Richard Smithfeea8832012-04-12 05:08:17 +00002982 Form = C11CmpXchg;
2983 break;
2984
2985 case AtomicExpr::AO__atomic_compare_exchange:
2986 case AtomicExpr::AO__atomic_compare_exchange_n:
2987 Form = GNUCmpXchg;
2988 break;
2989 }
2990
Yaxun Liu39195062017-08-04 18:16:31 +00002991 unsigned AdjustedNumArgs = NumArgs[Form];
2992 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
2993 ++AdjustedNumArgs;
Richard Smithfeea8832012-04-12 05:08:17 +00002994 // Check we have the right number of arguments.
Yaxun Liu39195062017-08-04 18:16:31 +00002995 if (TheCall->getNumArgs() < AdjustedNumArgs) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002996 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Yaxun Liu39195062017-08-04 18:16:31 +00002997 << 0 << AdjustedNumArgs << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002998 << TheCall->getCallee()->getSourceRange();
2999 return ExprError();
Yaxun Liu39195062017-08-04 18:16:31 +00003000 } else if (TheCall->getNumArgs() > AdjustedNumArgs) {
3001 Diag(TheCall->getArg(AdjustedNumArgs)->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003002 diag::err_typecheck_call_too_many_args)
Yaxun Liu39195062017-08-04 18:16:31 +00003003 << 0 << AdjustedNumArgs << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003004 << TheCall->getCallee()->getSourceRange();
3005 return ExprError();
3006 }
3007
Richard Smithfeea8832012-04-12 05:08:17 +00003008 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003009 Expr *Ptr = TheCall->getArg(0);
George Burgess IV92b43a42016-07-21 03:28:13 +00003010 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
3011 if (ConvertedPtr.isInvalid())
3012 return ExprError();
3013
3014 Ptr = ConvertedPtr.get();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003015 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
3016 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00003017 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003018 << Ptr->getType() << Ptr->getSourceRange();
3019 return ExprError();
3020 }
3021
Richard Smithfeea8832012-04-12 05:08:17 +00003022 // For a __c11 builtin, this should be a pointer to an _Atomic type.
3023 QualType AtomTy = pointerType->getPointeeType(); // 'A'
3024 QualType ValType = AtomTy; // 'C'
3025 if (IsC11) {
3026 if (!AtomTy->isAtomicType()) {
3027 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
3028 << Ptr->getType() << Ptr->getSourceRange();
3029 return ExprError();
3030 }
Yaxun Liu39195062017-08-04 18:16:31 +00003031 if (AtomTy.isConstQualified() ||
3032 AtomTy.getAddressSpace() == LangAS::opencl_constant) {
Richard Smithe00921a2012-09-15 06:09:58 +00003033 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
Yaxun Liu39195062017-08-04 18:16:31 +00003034 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
3035 << Ptr->getSourceRange();
Richard Smithe00921a2012-09-15 06:09:58 +00003036 return ExprError();
3037 }
Richard Smithfeea8832012-04-12 05:08:17 +00003038 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eric Fiselier8d662442016-03-30 23:39:56 +00003039 } else if (Form != Load && Form != LoadCopy) {
Eric Fiseliera3a7c562015-10-04 00:11:02 +00003040 if (ValType.isConstQualified()) {
3041 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
3042 << Ptr->getType() << Ptr->getSourceRange();
3043 return ExprError();
3044 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003045 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003046
Richard Smithfeea8832012-04-12 05:08:17 +00003047 // For an arithmetic operation, the implied arithmetic must be well-formed.
3048 if (Form == Arithmetic) {
3049 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
3050 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
3051 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
3052 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3053 return ExprError();
3054 }
3055 if (!IsAddSub && !ValType->isIntegerType()) {
3056 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
3057 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3058 return ExprError();
3059 }
David Majnemere85cff82015-01-28 05:48:06 +00003060 if (IsC11 && ValType->isPointerType() &&
3061 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
3062 diag::err_incomplete_type)) {
3063 return ExprError();
3064 }
Richard Smithfeea8832012-04-12 05:08:17 +00003065 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
3066 // For __atomic_*_n operations, the value type must be a scalar integral or
3067 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003068 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00003069 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3070 return ExprError();
3071 }
3072
Eli Friedmanaa769812013-09-11 03:49:34 +00003073 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
3074 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00003075 // For GNU atomics, require a trivially-copyable type. This is not part of
3076 // the GNU atomics specification, but we enforce it for sanity.
3077 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003078 << Ptr->getType() << Ptr->getSourceRange();
3079 return ExprError();
3080 }
3081
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003082 switch (ValType.getObjCLifetime()) {
3083 case Qualifiers::OCL_None:
3084 case Qualifiers::OCL_ExplicitNone:
3085 // okay
3086 break;
3087
3088 case Qualifiers::OCL_Weak:
3089 case Qualifiers::OCL_Strong:
3090 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00003091 // FIXME: Can this happen? By this point, ValType should be known
3092 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003093 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
3094 << ValType << Ptr->getSourceRange();
3095 return ExprError();
3096 }
3097
David Majnemerc6eb6502015-06-03 00:26:35 +00003098 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the
3099 // volatile-ness of the pointee-type inject itself into the result or the
Eric Fiselier8d662442016-03-30 23:39:56 +00003100 // other operands. Similarly atomic_load can take a pointer to a const 'A'.
David Majnemerc6eb6502015-06-03 00:26:35 +00003101 ValType.removeLocalVolatile();
Eric Fiselier8d662442016-03-30 23:39:56 +00003102 ValType.removeLocalConst();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003103 QualType ResultType = ValType;
Yaxun Liu39195062017-08-04 18:16:31 +00003104 if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
3105 Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003106 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00003107 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003108 ResultType = Context.BoolTy;
3109
Richard Smithfeea8832012-04-12 05:08:17 +00003110 // The type of a parameter passed 'by value'. In the GNU atomics, such
3111 // arguments are actually passed as pointers.
3112 QualType ByValType = ValType; // 'CP'
3113 if (!IsC11 && !IsN)
3114 ByValType = Ptr->getType();
3115
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003116 // The first argument --- the pointer --- has a fixed type; we
3117 // deduce the types of the rest of the arguments accordingly. Walk
3118 // the remaining arguments, converting them to the deduced value type.
Yaxun Liu39195062017-08-04 18:16:31 +00003119 for (unsigned i = 1; i != TheCall->getNumArgs(); ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003120 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00003121 if (i < NumVals[Form] + 1) {
3122 switch (i) {
3123 case 1:
3124 // The second argument is the non-atomic operand. For arithmetic, this
3125 // is always passed by value, and for a compare_exchange it is always
3126 // passed by address. For the rest, GNU uses by-address and C11 uses
3127 // by-value.
3128 assert(Form != Load);
3129 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
3130 Ty = ValType;
3131 else if (Form == Copy || Form == Xchg)
3132 Ty = ByValType;
3133 else if (Form == Arithmetic)
3134 Ty = Context.getPointerDiffType();
Anastasia Stulova76fd1052015-12-22 15:14:54 +00003135 else {
3136 Expr *ValArg = TheCall->getArg(i);
Alex Lorenz67522152016-11-23 16:57:03 +00003137 // Treat this argument as _Nonnull as we want to show a warning if
3138 // NULL is passed into it.
3139 CheckNonNullArgument(*this, ValArg, DRE->getLocStart());
Anastasia Stulova76fd1052015-12-22 15:14:54 +00003140 unsigned AS = 0;
3141 // Keep address space of non-atomic pointer type.
3142 if (const PointerType *PtrTy =
3143 ValArg->getType()->getAs<PointerType>()) {
3144 AS = PtrTy->getPointeeType().getAddressSpace();
3145 }
3146 Ty = Context.getPointerType(
3147 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
3148 }
Richard Smithfeea8832012-04-12 05:08:17 +00003149 break;
3150 case 2:
3151 // The third argument to compare_exchange / GNU exchange is a
3152 // (pointer to a) desired value.
3153 Ty = ByValType;
3154 break;
3155 case 3:
3156 // The fourth argument to GNU compare_exchange is a 'weak' flag.
3157 Ty = Context.BoolTy;
3158 break;
3159 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003160 } else {
Yaxun Liu39195062017-08-04 18:16:31 +00003161 // The order(s) and scope are always converted to int.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003162 Ty = Context.IntTy;
3163 }
Richard Smithfeea8832012-04-12 05:08:17 +00003164
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003165 InitializedEntity Entity =
3166 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00003167 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003168 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3169 if (Arg.isInvalid())
3170 return true;
3171 TheCall->setArg(i, Arg.get());
3172 }
3173
Richard Smithfeea8832012-04-12 05:08:17 +00003174 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003175 SmallVector<Expr*, 5> SubExprs;
3176 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00003177 switch (Form) {
3178 case Init:
3179 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00003180 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00003181 break;
3182 case Load:
3183 SubExprs.push_back(TheCall->getArg(1)); // Order
3184 break;
Eric Fiselier8d662442016-03-30 23:39:56 +00003185 case LoadCopy:
Richard Smithfeea8832012-04-12 05:08:17 +00003186 case Copy:
3187 case Arithmetic:
3188 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003189 SubExprs.push_back(TheCall->getArg(2)); // Order
3190 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00003191 break;
3192 case GNUXchg:
3193 // Note, AtomicExpr::getVal2() has a special case for this atomic.
3194 SubExprs.push_back(TheCall->getArg(3)); // Order
3195 SubExprs.push_back(TheCall->getArg(1)); // Val1
3196 SubExprs.push_back(TheCall->getArg(2)); // Val2
3197 break;
3198 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003199 SubExprs.push_back(TheCall->getArg(3)); // Order
3200 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003201 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00003202 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00003203 break;
3204 case GNUCmpXchg:
3205 SubExprs.push_back(TheCall->getArg(4)); // Order
3206 SubExprs.push_back(TheCall->getArg(1)); // Val1
3207 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
3208 SubExprs.push_back(TheCall->getArg(2)); // Val2
3209 SubExprs.push_back(TheCall->getArg(3)); // Weak
3210 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003211 }
Tim Northovere94a34c2014-03-11 10:49:14 +00003212
3213 if (SubExprs.size() >= 2 && Form != Init) {
3214 llvm::APSInt Result(32);
3215 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
3216 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00003217 Diag(SubExprs[1]->getLocStart(),
3218 diag::warn_atomic_op_has_invalid_memory_order)
3219 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00003220 }
3221
Yaxun Liu30d652a2017-08-15 16:02:49 +00003222 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
3223 auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1);
3224 llvm::APSInt Result(32);
3225 if (Scope->isIntegerConstantExpr(Result, Context) &&
3226 !ScopeModel->isValid(Result.getZExtValue())) {
3227 Diag(Scope->getLocStart(), diag::err_atomic_op_has_invalid_synch_scope)
3228 << Scope->getSourceRange();
3229 }
3230 SubExprs.push_back(Scope);
3231 }
3232
Fariborz Jahanian615de762013-05-28 17:37:39 +00003233 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
3234 SubExprs, ResultType, Op,
3235 TheCall->getRParenLoc());
3236
3237 if ((Op == AtomicExpr::AO__c11_atomic_load ||
Yaxun Liu39195062017-08-04 18:16:31 +00003238 Op == AtomicExpr::AO__c11_atomic_store ||
3239 Op == AtomicExpr::AO__opencl_atomic_load ||
3240 Op == AtomicExpr::AO__opencl_atomic_store ) &&
Fariborz Jahanian615de762013-05-28 17:37:39 +00003241 Context.AtomicUsesUnsupportedLibcall(AE))
Yaxun Liu39195062017-08-04 18:16:31 +00003242 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib)
3243 << ((Op == AtomicExpr::AO__c11_atomic_load ||
3244 Op == AtomicExpr::AO__opencl_atomic_load)
3245 ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003246
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003247 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003248}
3249
John McCall29ad95b2011-08-27 01:09:30 +00003250/// checkBuiltinArgument - Given a call to a builtin function, perform
3251/// normal type-checking on the given argument, updating the call in
3252/// place. This is useful when a builtin function requires custom
3253/// type-checking for some of its arguments but not necessarily all of
3254/// them.
3255///
3256/// Returns true on error.
3257static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
3258 FunctionDecl *Fn = E->getDirectCallee();
3259 assert(Fn && "builtin call without direct callee!");
3260
3261 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
3262 InitializedEntity Entity =
3263 InitializedEntity::InitializeParameter(S.Context, Param);
3264
3265 ExprResult Arg = E->getArg(0);
3266 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
3267 if (Arg.isInvalid())
3268 return true;
3269
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003270 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00003271 return false;
3272}
3273
Chris Lattnerdc046542009-05-08 06:58:22 +00003274/// SemaBuiltinAtomicOverloaded - We have a call to a function like
3275/// __sync_fetch_and_add, which is an overloaded function based on the pointer
3276/// type of its first argument. The main ActOnCallExpr routines have already
3277/// promoted the types of arguments because all of these calls are prototyped as
3278/// void(...).
3279///
3280/// This function goes through and does final semantic checking for these
3281/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00003282ExprResult
3283Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003284 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00003285 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3286 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3287
3288 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003289 if (TheCall->getNumArgs() < 1) {
3290 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3291 << 0 << 1 << TheCall->getNumArgs()
3292 << TheCall->getCallee()->getSourceRange();
3293 return ExprError();
3294 }
Mike Stump11289f42009-09-09 15:08:12 +00003295
Chris Lattnerdc046542009-05-08 06:58:22 +00003296 // Inspect the first argument of the atomic builtin. This should always be
3297 // a pointer type, whose element is an integral scalar or pointer type.
3298 // Because it is a pointer type, we don't have to worry about any implicit
3299 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003300 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00003301 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00003302 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
3303 if (FirstArgResult.isInvalid())
3304 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003305 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00003306 TheCall->setArg(0, FirstArg);
3307
John McCall31168b02011-06-15 23:02:42 +00003308 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
3309 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003310 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3311 << FirstArg->getType() << FirstArg->getSourceRange();
3312 return ExprError();
3313 }
Mike Stump11289f42009-09-09 15:08:12 +00003314
John McCall31168b02011-06-15 23:02:42 +00003315 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00003316 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003317 !ValType->isBlockPointerType()) {
3318 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
3319 << FirstArg->getType() << FirstArg->getSourceRange();
3320 return ExprError();
3321 }
Chris Lattnerdc046542009-05-08 06:58:22 +00003322
John McCall31168b02011-06-15 23:02:42 +00003323 switch (ValType.getObjCLifetime()) {
3324 case Qualifiers::OCL_None:
3325 case Qualifiers::OCL_ExplicitNone:
3326 // okay
3327 break;
3328
3329 case Qualifiers::OCL_Weak:
3330 case Qualifiers::OCL_Strong:
3331 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00003332 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00003333 << ValType << FirstArg->getSourceRange();
3334 return ExprError();
3335 }
3336
John McCallb50451a2011-10-05 07:41:44 +00003337 // Strip any qualifiers off ValType.
3338 ValType = ValType.getUnqualifiedType();
3339
Chandler Carruth3973af72010-07-18 20:54:12 +00003340 // The majority of builtins return a value, but a few have special return
3341 // types, so allow them to override appropriately below.
3342 QualType ResultType = ValType;
3343
Chris Lattnerdc046542009-05-08 06:58:22 +00003344 // We need to figure out which concrete builtin this maps onto. For example,
3345 // __sync_fetch_and_add with a 2 byte object turns into
3346 // __sync_fetch_and_add_2.
3347#define BUILTIN_ROW(x) \
3348 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
3349 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00003350
Chris Lattnerdc046542009-05-08 06:58:22 +00003351 static const unsigned BuiltinIndices[][5] = {
3352 BUILTIN_ROW(__sync_fetch_and_add),
3353 BUILTIN_ROW(__sync_fetch_and_sub),
3354 BUILTIN_ROW(__sync_fetch_and_or),
3355 BUILTIN_ROW(__sync_fetch_and_and),
3356 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00003357 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00003358
Chris Lattnerdc046542009-05-08 06:58:22 +00003359 BUILTIN_ROW(__sync_add_and_fetch),
3360 BUILTIN_ROW(__sync_sub_and_fetch),
3361 BUILTIN_ROW(__sync_and_and_fetch),
3362 BUILTIN_ROW(__sync_or_and_fetch),
3363 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00003364 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00003365
Chris Lattnerdc046542009-05-08 06:58:22 +00003366 BUILTIN_ROW(__sync_val_compare_and_swap),
3367 BUILTIN_ROW(__sync_bool_compare_and_swap),
3368 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00003369 BUILTIN_ROW(__sync_lock_release),
3370 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00003371 };
Mike Stump11289f42009-09-09 15:08:12 +00003372#undef BUILTIN_ROW
3373
Chris Lattnerdc046542009-05-08 06:58:22 +00003374 // Determine the index of the size.
3375 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00003376 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00003377 case 1: SizeIndex = 0; break;
3378 case 2: SizeIndex = 1; break;
3379 case 4: SizeIndex = 2; break;
3380 case 8: SizeIndex = 3; break;
3381 case 16: SizeIndex = 4; break;
3382 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003383 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
3384 << FirstArg->getType() << FirstArg->getSourceRange();
3385 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00003386 }
Mike Stump11289f42009-09-09 15:08:12 +00003387
Chris Lattnerdc046542009-05-08 06:58:22 +00003388 // Each of these builtins has one pointer argument, followed by some number of
3389 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
3390 // that we ignore. Find out which row of BuiltinIndices to read from as well
3391 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00003392 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00003393 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00003394 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00003395 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00003396 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00003397 case Builtin::BI__sync_fetch_and_add:
3398 case Builtin::BI__sync_fetch_and_add_1:
3399 case Builtin::BI__sync_fetch_and_add_2:
3400 case Builtin::BI__sync_fetch_and_add_4:
3401 case Builtin::BI__sync_fetch_and_add_8:
3402 case Builtin::BI__sync_fetch_and_add_16:
3403 BuiltinIndex = 0;
3404 break;
3405
3406 case Builtin::BI__sync_fetch_and_sub:
3407 case Builtin::BI__sync_fetch_and_sub_1:
3408 case Builtin::BI__sync_fetch_and_sub_2:
3409 case Builtin::BI__sync_fetch_and_sub_4:
3410 case Builtin::BI__sync_fetch_and_sub_8:
3411 case Builtin::BI__sync_fetch_and_sub_16:
3412 BuiltinIndex = 1;
3413 break;
3414
3415 case Builtin::BI__sync_fetch_and_or:
3416 case Builtin::BI__sync_fetch_and_or_1:
3417 case Builtin::BI__sync_fetch_and_or_2:
3418 case Builtin::BI__sync_fetch_and_or_4:
3419 case Builtin::BI__sync_fetch_and_or_8:
3420 case Builtin::BI__sync_fetch_and_or_16:
3421 BuiltinIndex = 2;
3422 break;
3423
3424 case Builtin::BI__sync_fetch_and_and:
3425 case Builtin::BI__sync_fetch_and_and_1:
3426 case Builtin::BI__sync_fetch_and_and_2:
3427 case Builtin::BI__sync_fetch_and_and_4:
3428 case Builtin::BI__sync_fetch_and_and_8:
3429 case Builtin::BI__sync_fetch_and_and_16:
3430 BuiltinIndex = 3;
3431 break;
Mike Stump11289f42009-09-09 15:08:12 +00003432
Douglas Gregor73722482011-11-28 16:30:08 +00003433 case Builtin::BI__sync_fetch_and_xor:
3434 case Builtin::BI__sync_fetch_and_xor_1:
3435 case Builtin::BI__sync_fetch_and_xor_2:
3436 case Builtin::BI__sync_fetch_and_xor_4:
3437 case Builtin::BI__sync_fetch_and_xor_8:
3438 case Builtin::BI__sync_fetch_and_xor_16:
3439 BuiltinIndex = 4;
3440 break;
3441
Hal Finkeld2208b52014-10-02 20:53:50 +00003442 case Builtin::BI__sync_fetch_and_nand:
3443 case Builtin::BI__sync_fetch_and_nand_1:
3444 case Builtin::BI__sync_fetch_and_nand_2:
3445 case Builtin::BI__sync_fetch_and_nand_4:
3446 case Builtin::BI__sync_fetch_and_nand_8:
3447 case Builtin::BI__sync_fetch_and_nand_16:
3448 BuiltinIndex = 5;
3449 WarnAboutSemanticsChange = true;
3450 break;
3451
Douglas Gregor73722482011-11-28 16:30:08 +00003452 case Builtin::BI__sync_add_and_fetch:
3453 case Builtin::BI__sync_add_and_fetch_1:
3454 case Builtin::BI__sync_add_and_fetch_2:
3455 case Builtin::BI__sync_add_and_fetch_4:
3456 case Builtin::BI__sync_add_and_fetch_8:
3457 case Builtin::BI__sync_add_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003458 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00003459 break;
3460
3461 case Builtin::BI__sync_sub_and_fetch:
3462 case Builtin::BI__sync_sub_and_fetch_1:
3463 case Builtin::BI__sync_sub_and_fetch_2:
3464 case Builtin::BI__sync_sub_and_fetch_4:
3465 case Builtin::BI__sync_sub_and_fetch_8:
3466 case Builtin::BI__sync_sub_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003467 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00003468 break;
3469
3470 case Builtin::BI__sync_and_and_fetch:
3471 case Builtin::BI__sync_and_and_fetch_1:
3472 case Builtin::BI__sync_and_and_fetch_2:
3473 case Builtin::BI__sync_and_and_fetch_4:
3474 case Builtin::BI__sync_and_and_fetch_8:
3475 case Builtin::BI__sync_and_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003476 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00003477 break;
3478
3479 case Builtin::BI__sync_or_and_fetch:
3480 case Builtin::BI__sync_or_and_fetch_1:
3481 case Builtin::BI__sync_or_and_fetch_2:
3482 case Builtin::BI__sync_or_and_fetch_4:
3483 case Builtin::BI__sync_or_and_fetch_8:
3484 case Builtin::BI__sync_or_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003485 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00003486 break;
3487
3488 case Builtin::BI__sync_xor_and_fetch:
3489 case Builtin::BI__sync_xor_and_fetch_1:
3490 case Builtin::BI__sync_xor_and_fetch_2:
3491 case Builtin::BI__sync_xor_and_fetch_4:
3492 case Builtin::BI__sync_xor_and_fetch_8:
3493 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003494 BuiltinIndex = 10;
3495 break;
3496
3497 case Builtin::BI__sync_nand_and_fetch:
3498 case Builtin::BI__sync_nand_and_fetch_1:
3499 case Builtin::BI__sync_nand_and_fetch_2:
3500 case Builtin::BI__sync_nand_and_fetch_4:
3501 case Builtin::BI__sync_nand_and_fetch_8:
3502 case Builtin::BI__sync_nand_and_fetch_16:
3503 BuiltinIndex = 11;
3504 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00003505 break;
Mike Stump11289f42009-09-09 15:08:12 +00003506
Chris Lattnerdc046542009-05-08 06:58:22 +00003507 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00003508 case Builtin::BI__sync_val_compare_and_swap_1:
3509 case Builtin::BI__sync_val_compare_and_swap_2:
3510 case Builtin::BI__sync_val_compare_and_swap_4:
3511 case Builtin::BI__sync_val_compare_and_swap_8:
3512 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003513 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00003514 NumFixed = 2;
3515 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003516
Chris Lattnerdc046542009-05-08 06:58:22 +00003517 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00003518 case Builtin::BI__sync_bool_compare_and_swap_1:
3519 case Builtin::BI__sync_bool_compare_and_swap_2:
3520 case Builtin::BI__sync_bool_compare_and_swap_4:
3521 case Builtin::BI__sync_bool_compare_and_swap_8:
3522 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003523 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00003524 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00003525 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00003526 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003527
3528 case Builtin::BI__sync_lock_test_and_set:
3529 case Builtin::BI__sync_lock_test_and_set_1:
3530 case Builtin::BI__sync_lock_test_and_set_2:
3531 case Builtin::BI__sync_lock_test_and_set_4:
3532 case Builtin::BI__sync_lock_test_and_set_8:
3533 case Builtin::BI__sync_lock_test_and_set_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003534 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00003535 break;
3536
Chris Lattnerdc046542009-05-08 06:58:22 +00003537 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00003538 case Builtin::BI__sync_lock_release_1:
3539 case Builtin::BI__sync_lock_release_2:
3540 case Builtin::BI__sync_lock_release_4:
3541 case Builtin::BI__sync_lock_release_8:
3542 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003543 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00003544 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00003545 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00003546 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003547
3548 case Builtin::BI__sync_swap:
3549 case Builtin::BI__sync_swap_1:
3550 case Builtin::BI__sync_swap_2:
3551 case Builtin::BI__sync_swap_4:
3552 case Builtin::BI__sync_swap_8:
3553 case Builtin::BI__sync_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003554 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00003555 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00003556 }
Mike Stump11289f42009-09-09 15:08:12 +00003557
Chris Lattnerdc046542009-05-08 06:58:22 +00003558 // Now that we know how many fixed arguments we expect, first check that we
3559 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003560 if (TheCall->getNumArgs() < 1+NumFixed) {
3561 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3562 << 0 << 1+NumFixed << TheCall->getNumArgs()
3563 << TheCall->getCallee()->getSourceRange();
3564 return ExprError();
3565 }
Mike Stump11289f42009-09-09 15:08:12 +00003566
Hal Finkeld2208b52014-10-02 20:53:50 +00003567 if (WarnAboutSemanticsChange) {
3568 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
3569 << TheCall->getCallee()->getSourceRange();
3570 }
3571
Chris Lattner5b9241b2009-05-08 15:36:58 +00003572 // Get the decl for the concrete builtin from this, we can tell what the
3573 // concrete integer type we should convert to is.
3574 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
Mehdi Amini7186a432016-10-11 19:04:24 +00003575 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00003576 FunctionDecl *NewBuiltinDecl;
3577 if (NewBuiltinID == BuiltinID)
3578 NewBuiltinDecl = FDecl;
3579 else {
3580 // Perform builtin lookup to avoid redeclaring it.
3581 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
3582 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
3583 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
3584 assert(Res.getFoundDecl());
3585 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00003586 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00003587 return ExprError();
3588 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003589
John McCallcf142162010-08-07 06:22:56 +00003590 // The first argument --- the pointer --- has a fixed type; we
3591 // deduce the types of the rest of the arguments accordingly. Walk
3592 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00003593 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00003594 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00003595
Chris Lattnerdc046542009-05-08 06:58:22 +00003596 // GCC does an implicit conversion to the pointer or integer ValType. This
3597 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00003598 // Initialize the argument.
3599 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3600 ValType, /*consume*/ false);
3601 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00003602 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003603 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003604
Chris Lattnerdc046542009-05-08 06:58:22 +00003605 // Okay, we have something that *can* be converted to the right type. Check
3606 // to see if there is a potentially weird extension going on here. This can
3607 // happen when you do an atomic operation on something like an char* and
3608 // pass in 42. The 42 gets converted to char. This is even more strange
3609 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00003610 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003611 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00003612 }
Mike Stump11289f42009-09-09 15:08:12 +00003613
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003614 ASTContext& Context = this->getASTContext();
3615
3616 // Create a new DeclRefExpr to refer to the new decl.
3617 DeclRefExpr* NewDRE = DeclRefExpr::Create(
3618 Context,
3619 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00003620 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003621 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00003622 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003623 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00003624 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003625 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00003626
Chris Lattnerdc046542009-05-08 06:58:22 +00003627 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00003628 // FIXME: This loses syntactic information.
3629 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
3630 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
3631 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003632 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00003633
Chandler Carruthbc8cab12010-07-18 07:23:17 +00003634 // Change the result type of the call to match the original value type. This
3635 // is arbitrary, but the codegen for these builtins ins design to handle it
3636 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00003637 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003638
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003639 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00003640}
3641
Michael Zolotukhin84df1232015-09-08 23:52:33 +00003642/// SemaBuiltinNontemporalOverloaded - We have a call to
3643/// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
3644/// overloaded function based on the pointer type of its last argument.
3645///
3646/// This function goes through and does final semantic checking for these
3647/// builtins.
3648ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
3649 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3650 DeclRefExpr *DRE =
3651 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3652 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3653 unsigned BuiltinID = FDecl->getBuiltinID();
3654 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
3655 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
3656 "Unexpected nontemporal load/store builtin!");
3657 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
3658 unsigned numArgs = isStore ? 2 : 1;
3659
3660 // Ensure that we have the proper number of arguments.
3661 if (checkArgCount(*this, TheCall, numArgs))
3662 return ExprError();
3663
3664 // Inspect the last argument of the nontemporal builtin. This should always
3665 // be a pointer type, from which we imply the type of the memory access.
3666 // Because it is a pointer type, we don't have to worry about any implicit
3667 // casts here.
3668 Expr *PointerArg = TheCall->getArg(numArgs - 1);
3669 ExprResult PointerArgResult =
3670 DefaultFunctionArrayLvalueConversion(PointerArg);
3671
3672 if (PointerArgResult.isInvalid())
3673 return ExprError();
3674 PointerArg = PointerArgResult.get();
3675 TheCall->setArg(numArgs - 1, PointerArg);
3676
3677 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
3678 if (!pointerType) {
3679 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
3680 << PointerArg->getType() << PointerArg->getSourceRange();
3681 return ExprError();
3682 }
3683
3684 QualType ValType = pointerType->getPointeeType();
3685
3686 // Strip any qualifiers off ValType.
3687 ValType = ValType.getUnqualifiedType();
3688 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3689 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
3690 !ValType->isVectorType()) {
3691 Diag(DRE->getLocStart(),
3692 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
3693 << PointerArg->getType() << PointerArg->getSourceRange();
3694 return ExprError();
3695 }
3696
3697 if (!isStore) {
3698 TheCall->setType(ValType);
3699 return TheCallResult;
3700 }
3701
3702 ExprResult ValArg = TheCall->getArg(0);
3703 InitializedEntity Entity = InitializedEntity::InitializeParameter(
3704 Context, ValType, /*consume*/ false);
3705 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
3706 if (ValArg.isInvalid())
3707 return ExprError();
3708
3709 TheCall->setArg(0, ValArg.get());
3710 TheCall->setType(Context.VoidTy);
3711 return TheCallResult;
3712}
3713
Chris Lattner6436fb62009-02-18 06:01:06 +00003714/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00003715/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00003716/// Note: It might also make sense to do the UTF-16 conversion here (would
3717/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00003718bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00003719 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00003720 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
3721
Douglas Gregorfb65e592011-07-27 05:40:30 +00003722 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00003723 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
3724 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00003725 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00003726 }
Mike Stump11289f42009-09-09 15:08:12 +00003727
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003728 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003729 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003730 unsigned NumBytes = String.size();
Justin Lebar90910552016-09-30 00:38:45 +00003731 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
3732 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
3733 llvm::UTF16 *ToPtr = &ToBuf[0];
3734
3735 llvm::ConversionResult Result =
3736 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
3737 ToPtr + NumBytes, llvm::strictConversion);
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003738 // Check for conversion failure.
Justin Lebar90910552016-09-30 00:38:45 +00003739 if (Result != llvm::conversionOK)
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003740 Diag(Arg->getLocStart(),
3741 diag::warn_cfstring_truncated) << Arg->getSourceRange();
3742 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00003743 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003744}
3745
Mehdi Amini06d367c2016-10-24 20:39:34 +00003746/// CheckObjCString - Checks that the format string argument to the os_log()
3747/// and os_trace() functions is correct, and converts it to const char *.
3748ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
3749 Arg = Arg->IgnoreParenCasts();
3750 auto *Literal = dyn_cast<StringLiteral>(Arg);
3751 if (!Literal) {
3752 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
3753 Literal = ObjcLiteral->getString();
3754 }
3755 }
3756
3757 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
3758 return ExprError(
3759 Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant)
3760 << Arg->getSourceRange());
3761 }
3762
3763 ExprResult Result(Literal);
3764 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
3765 InitializedEntity Entity =
3766 InitializedEntity::InitializeParameter(Context, ResultTy, false);
3767 Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
3768 return Result;
3769}
3770
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003771/// Check that the user is calling the appropriate va_start builtin for the
3772/// target and calling convention.
3773static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
3774 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
3775 bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
Martin Storsjo022e7822017-07-17 20:49:45 +00003776 bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003777 bool IsWindows = TT.isOSWindows();
Martin Storsjo022e7822017-07-17 20:49:45 +00003778 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
3779 if (IsX64 || IsAArch64) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003780 clang::CallingConv CC = CC_C;
3781 if (const FunctionDecl *FD = S.getCurFunctionDecl())
3782 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3783 if (IsMSVAStart) {
3784 // Don't allow this in System V ABI functions.
Martin Storsjo022e7822017-07-17 20:49:45 +00003785 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003786 return S.Diag(Fn->getLocStart(),
3787 diag::err_ms_va_start_used_in_sysv_function);
3788 } else {
Martin Storsjo022e7822017-07-17 20:49:45 +00003789 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003790 // On x64 Windows, don't allow this in System V ABI functions.
3791 // (Yes, that means there's no corresponding way to support variadic
3792 // System V ABI functions on Windows.)
3793 if ((IsWindows && CC == CC_X86_64SysV) ||
Martin Storsjo022e7822017-07-17 20:49:45 +00003794 (!IsWindows && CC == CC_Win64))
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003795 return S.Diag(Fn->getLocStart(),
3796 diag::err_va_start_used_in_wrong_abi_function)
3797 << !IsWindows;
3798 }
3799 return false;
3800 }
3801
3802 if (IsMSVAStart)
Martin Storsjo022e7822017-07-17 20:49:45 +00003803 return S.Diag(Fn->getLocStart(), diag::err_builtin_x64_aarch64_only);
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003804 return false;
3805}
3806
3807static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
3808 ParmVarDecl **LastParam = nullptr) {
3809 // Determine whether the current function, block, or obj-c method is variadic
3810 // and get its parameter list.
3811 bool IsVariadic = false;
3812 ArrayRef<ParmVarDecl *> Params;
Reid Klecknerf1deb832017-05-04 19:51:05 +00003813 DeclContext *Caller = S.CurContext;
3814 if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
3815 IsVariadic = Block->isVariadic();
3816 Params = Block->parameters();
3817 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003818 IsVariadic = FD->isVariadic();
3819 Params = FD->parameters();
Reid Klecknerf1deb832017-05-04 19:51:05 +00003820 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003821 IsVariadic = MD->isVariadic();
3822 // FIXME: This isn't correct for methods (results in bogus warning).
3823 Params = MD->parameters();
Reid Klecknerf1deb832017-05-04 19:51:05 +00003824 } else if (isa<CapturedDecl>(Caller)) {
3825 // We don't support va_start in a CapturedDecl.
3826 S.Diag(Fn->getLocStart(), diag::err_va_start_captured_stmt);
3827 return true;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003828 } else {
Reid Klecknerf1deb832017-05-04 19:51:05 +00003829 // This must be some other declcontext that parses exprs.
3830 S.Diag(Fn->getLocStart(), diag::err_va_start_outside_function);
3831 return true;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003832 }
3833
3834 if (!IsVariadic) {
Reid Klecknerf1deb832017-05-04 19:51:05 +00003835 S.Diag(Fn->getLocStart(), diag::err_va_start_fixed_function);
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003836 return true;
3837 }
3838
3839 if (LastParam)
3840 *LastParam = Params.empty() ? nullptr : Params.back();
3841
3842 return false;
3843}
3844
Charles Davisc7d5c942015-09-17 20:55:33 +00003845/// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
3846/// for validity. Emit an error and return true on failure; return false
3847/// on success.
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003848bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
Chris Lattner08464942007-12-28 05:29:59 +00003849 Expr *Fn = TheCall->getCallee();
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003850
3851 if (checkVAStartABI(*this, BuiltinID, Fn))
3852 return true;
3853
Chris Lattner08464942007-12-28 05:29:59 +00003854 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00003855 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003856 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003857 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3858 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00003859 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003860 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00003861 return true;
3862 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00003863
3864 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00003865 return Diag(TheCall->getLocEnd(),
3866 diag::err_typecheck_call_too_few_args_at_least)
3867 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00003868 }
3869
John McCall29ad95b2011-08-27 01:09:30 +00003870 // Type-check the first argument normally.
3871 if (checkBuiltinArgument(*this, TheCall, 0))
3872 return true;
3873
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003874 // Check that the current function is variadic, and get its last parameter.
3875 ParmVarDecl *LastParam;
3876 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
Chris Lattner43be2e62007-12-19 23:59:04 +00003877 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003878
Chris Lattner43be2e62007-12-19 23:59:04 +00003879 // Verify that the second argument to the builtin is the last argument of the
3880 // current function or method.
3881 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00003882 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00003883
Nico Weber9eea7642013-05-24 23:31:57 +00003884 // These are valid if SecondArgIsLastNamedArgument is false after the next
3885 // block.
3886 QualType Type;
3887 SourceLocation ParamLoc;
Aaron Ballman1de59c52016-04-24 13:30:21 +00003888 bool IsCRegister = false;
Nico Weber9eea7642013-05-24 23:31:57 +00003889
Anders Carlsson6a8350b2008-02-11 04:20:54 +00003890 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
3891 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003892 SecondArgIsLastNamedArgument = PV == LastParam;
Nico Weber9eea7642013-05-24 23:31:57 +00003893
3894 Type = PV->getType();
3895 ParamLoc = PV->getLocation();
Aaron Ballman1de59c52016-04-24 13:30:21 +00003896 IsCRegister =
3897 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
Chris Lattner43be2e62007-12-19 23:59:04 +00003898 }
3899 }
Mike Stump11289f42009-09-09 15:08:12 +00003900
Chris Lattner43be2e62007-12-19 23:59:04 +00003901 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00003902 Diag(TheCall->getArg(1)->getLocStart(),
Aaron Ballman05164812016-04-18 18:10:53 +00003903 diag::warn_second_arg_of_va_start_not_last_named_param);
Aaron Ballman1de59c52016-04-24 13:30:21 +00003904 else if (IsCRegister || Type->isReferenceType() ||
Aaron Ballmana4f597f2016-09-15 18:07:51 +00003905 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
3906 // Promotable integers are UB, but enumerations need a bit of
3907 // extra checking to see what their promotable type actually is.
3908 if (!Type->isPromotableIntegerType())
3909 return false;
3910 if (!Type->isEnumeralType())
3911 return true;
3912 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3913 return !(ED &&
3914 Context.typesAreCompatible(ED->getPromotionType(), Type));
3915 }()) {
Aaron Ballman1de59c52016-04-24 13:30:21 +00003916 unsigned Reason = 0;
3917 if (Type->isReferenceType()) Reason = 1;
3918 else if (IsCRegister) Reason = 2;
3919 Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
Nico Weber9eea7642013-05-24 23:31:57 +00003920 Diag(ParamLoc, diag::note_parameter_type) << Type;
3921 }
3922
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00003923 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00003924 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00003925}
Chris Lattner43be2e62007-12-19 23:59:04 +00003926
Saleem Abdulrasool3450aa72017-09-26 20:12:04 +00003927bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00003928 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
3929 // const char *named_addr);
3930
3931 Expr *Func = Call->getCallee();
3932
3933 if (Call->getNumArgs() < 3)
3934 return Diag(Call->getLocEnd(),
3935 diag::err_typecheck_call_too_few_args_at_least)
3936 << 0 /*function call*/ << 3 << Call->getNumArgs();
3937
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00003938 // Type-check the first argument normally.
3939 if (checkBuiltinArgument(*this, Call, 0))
3940 return true;
3941
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003942 // Check that the current function is variadic.
3943 if (checkVAStartIsInVariadicFunction(*this, Func))
3944 return true;
3945
Saleem Abdulrasool448e8ad2017-09-26 17:44:10 +00003946 // __va_start on Windows does not validate the parameter qualifiers
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00003947
Saleem Abdulrasool448e8ad2017-09-26 17:44:10 +00003948 const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
3949 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
3950
3951 const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
3952 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
3953
3954 const QualType &ConstCharPtrTy =
3955 Context.getPointerType(Context.CharTy.withConst());
3956 if (!Arg1Ty->isPointerType() ||
3957 Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
3958 Diag(Arg1->getLocStart(), diag::err_typecheck_convert_incompatible)
3959 << Arg1->getType() << ConstCharPtrTy
3960 << 1 /* different class */
3961 << 0 /* qualifier difference */
3962 << 3 /* parameter mismatch */
3963 << 2 << Arg1->getType() << ConstCharPtrTy;
3964
3965 const QualType SizeTy = Context.getSizeType();
3966 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
3967 Diag(Arg2->getLocStart(), diag::err_typecheck_convert_incompatible)
3968 << Arg2->getType() << SizeTy
3969 << 1 /* different class */
3970 << 0 /* qualifier difference */
3971 << 3 /* parameter mismatch */
3972 << 3 << Arg2->getType() << SizeTy;
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00003973
3974 return false;
3975}
3976
Chris Lattner2da14fb2007-12-20 00:26:33 +00003977/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
3978/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00003979bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
3980 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00003981 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00003982 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00003983 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00003984 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003985 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003986 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00003987 << SourceRange(TheCall->getArg(2)->getLocStart(),
3988 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00003989
John Wiegley01296292011-04-08 18:41:53 +00003990 ExprResult OrigArg0 = TheCall->getArg(0);
3991 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00003992
Chris Lattner2da14fb2007-12-20 00:26:33 +00003993 // Do standard promotions between the two arguments, returning their common
3994 // type.
Chris Lattner08464942007-12-28 05:29:59 +00003995 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00003996 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
3997 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00003998
3999 // Make sure any conversions are pushed back into the call; this is
4000 // type safe since unordered compare builtins are declared as "_Bool
4001 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00004002 TheCall->setArg(0, OrigArg0.get());
4003 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00004004
John Wiegley01296292011-04-08 18:41:53 +00004005 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00004006 return false;
4007
Chris Lattner2da14fb2007-12-20 00:26:33 +00004008 // If the common type isn't a real floating type, then the arguments were
4009 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00004010 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00004011 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004012 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00004013 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
4014 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00004015
Chris Lattner2da14fb2007-12-20 00:26:33 +00004016 return false;
4017}
4018
Benjamin Kramer634fc102010-02-15 22:42:31 +00004019/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
4020/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00004021/// to check everything. We expect the last argument to be a floating point
4022/// value.
4023bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
4024 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00004025 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00004026 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00004027 if (TheCall->getNumArgs() > NumArgs)
4028 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00004029 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004030 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00004031 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00004032 (*(TheCall->arg_end()-1))->getLocEnd());
4033
Benjamin Kramer64aae502010-02-16 10:07:31 +00004034 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00004035
Eli Friedman7e4faac2009-08-31 20:06:00 +00004036 if (OrigArg->isTypeDependent())
4037 return false;
4038
Chris Lattner68784ef2010-05-06 05:50:07 +00004039 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00004040 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00004041 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00004042 diag::err_typecheck_call_invalid_unary_fp)
4043 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00004044
Neil Hickey88c0fac2016-12-13 16:22:50 +00004045 // If this is an implicit conversion from float -> float or double, remove it.
Chris Lattner68784ef2010-05-06 05:50:07 +00004046 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
Neil Hickey7b5ddab2016-12-14 13:18:48 +00004047 // Only remove standard FloatCasts, leaving other casts inplace
4048 if (Cast->getCastKind() == CK_FloatingCast) {
4049 Expr *CastArg = Cast->getSubExpr();
4050 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
4051 assert((Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
4052 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float)) &&
4053 "promotion from float to either float or double is the only expected cast here");
4054 Cast->setSubExpr(nullptr);
4055 TheCall->setArg(NumArgs-1, CastArg);
4056 }
Chris Lattner68784ef2010-05-06 05:50:07 +00004057 }
4058 }
4059
Eli Friedman7e4faac2009-08-31 20:06:00 +00004060 return false;
4061}
4062
Tony Jiangbbc48e92017-05-24 15:13:32 +00004063// Customized Sema Checking for VSX builtins that have the following signature:
4064// vector [...] builtinName(vector [...], vector [...], const int);
4065// Which takes the same type of vectors (any legal vector type) for the first
4066// two arguments and takes compile time constant for the third argument.
4067// Example builtins are :
4068// vector double vec_xxpermdi(vector double, vector double, int);
4069// vector short vec_xxsldwi(vector short, vector short, int);
4070bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
4071 unsigned ExpectedNumArgs = 3;
4072 if (TheCall->getNumArgs() < ExpectedNumArgs)
4073 return Diag(TheCall->getLocEnd(),
4074 diag::err_typecheck_call_too_few_args_at_least)
4075 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
4076 << TheCall->getSourceRange();
4077
4078 if (TheCall->getNumArgs() > ExpectedNumArgs)
4079 return Diag(TheCall->getLocEnd(),
4080 diag::err_typecheck_call_too_many_args_at_most)
4081 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
4082 << TheCall->getSourceRange();
4083
4084 // Check the third argument is a compile time constant
4085 llvm::APSInt Value;
4086 if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
4087 return Diag(TheCall->getLocStart(),
4088 diag::err_vsx_builtin_nonconstant_argument)
4089 << 3 /* argument index */ << TheCall->getDirectCallee()
4090 << SourceRange(TheCall->getArg(2)->getLocStart(),
4091 TheCall->getArg(2)->getLocEnd());
4092
4093 QualType Arg1Ty = TheCall->getArg(0)->getType();
4094 QualType Arg2Ty = TheCall->getArg(1)->getType();
4095
4096 // Check the type of argument 1 and argument 2 are vectors.
4097 SourceLocation BuiltinLoc = TheCall->getLocStart();
4098 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
4099 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
4100 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
4101 << TheCall->getDirectCallee()
4102 << SourceRange(TheCall->getArg(0)->getLocStart(),
4103 TheCall->getArg(1)->getLocEnd());
4104 }
4105
4106 // Check the first two arguments are the same type.
4107 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
4108 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
4109 << TheCall->getDirectCallee()
4110 << SourceRange(TheCall->getArg(0)->getLocStart(),
4111 TheCall->getArg(1)->getLocEnd());
4112 }
4113
4114 // When default clang type checking is turned off and the customized type
4115 // checking is used, the returning type of the function must be explicitly
4116 // set. Otherwise it is _Bool by default.
4117 TheCall->setType(Arg1Ty);
4118
4119 return false;
4120}
4121
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004122/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
4123// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00004124ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00004125 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004126 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00004127 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00004128 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
4129 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004130
Nate Begemana0110022010-06-08 00:16:34 +00004131 // Determine which of the following types of shufflevector we're checking:
4132 // 1) unary, vector mask: (lhs, mask)
Craig Topperb3174a82016-05-18 04:11:25 +00004133 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
Nate Begemana0110022010-06-08 00:16:34 +00004134 QualType resType = TheCall->getArg(0)->getType();
4135 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00004136
Douglas Gregorc25f7662009-05-19 22:10:17 +00004137 if (!TheCall->getArg(0)->isTypeDependent() &&
4138 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00004139 QualType LHSType = TheCall->getArg(0)->getType();
4140 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00004141
Craig Topperbaca3892013-07-29 06:47:04 +00004142 if (!LHSType->isVectorType() || !RHSType->isVectorType())
4143 return ExprError(Diag(TheCall->getLocStart(),
Tony Jiangedc78492017-05-24 14:45:57 +00004144 diag::err_vec_builtin_non_vector)
4145 << TheCall->getDirectCallee()
Craig Topperbaca3892013-07-29 06:47:04 +00004146 << SourceRange(TheCall->getArg(0)->getLocStart(),
4147 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00004148
Nate Begemana0110022010-06-08 00:16:34 +00004149 numElements = LHSType->getAs<VectorType>()->getNumElements();
4150 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00004151
Nate Begemana0110022010-06-08 00:16:34 +00004152 // Check to see if we have a call with 2 vector arguments, the unary shuffle
4153 // with mask. If so, verify that RHS is an integer vector type with the
4154 // same number of elts as lhs.
4155 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00004156 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00004157 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00004158 return ExprError(Diag(TheCall->getLocStart(),
Tony Jiangedc78492017-05-24 14:45:57 +00004159 diag::err_vec_builtin_incompatible_vector)
4160 << TheCall->getDirectCallee()
Craig Topperbaca3892013-07-29 06:47:04 +00004161 << SourceRange(TheCall->getArg(1)->getLocStart(),
4162 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00004163 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00004164 return ExprError(Diag(TheCall->getLocStart(),
Tony Jiangedc78492017-05-24 14:45:57 +00004165 diag::err_vec_builtin_incompatible_vector)
4166 << TheCall->getDirectCallee()
Craig Topperbaca3892013-07-29 06:47:04 +00004167 << SourceRange(TheCall->getArg(0)->getLocStart(),
4168 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00004169 } else if (numElements != numResElements) {
4170 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00004171 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00004172 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00004173 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004174 }
4175
4176 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00004177 if (TheCall->getArg(i)->isTypeDependent() ||
4178 TheCall->getArg(i)->isValueDependent())
4179 continue;
4180
Nate Begemana0110022010-06-08 00:16:34 +00004181 llvm::APSInt Result(32);
4182 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
4183 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00004184 diag::err_shufflevector_nonconstant_argument)
4185 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004186
Craig Topper50ad5b72013-08-03 17:40:38 +00004187 // Allow -1 which will be translated to undef in the IR.
4188 if (Result.isSigned() && Result.isAllOnesValue())
4189 continue;
4190
Chris Lattner7ab824e2008-08-10 02:05:13 +00004191 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004192 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00004193 diag::err_shufflevector_argument_too_large)
4194 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004195 }
4196
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004197 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004198
Chris Lattner7ab824e2008-08-10 02:05:13 +00004199 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004200 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00004201 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004202 }
4203
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004204 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
4205 TheCall->getCallee()->getLocStart(),
4206 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004207}
Chris Lattner43be2e62007-12-19 23:59:04 +00004208
Hal Finkelc4d7c822013-09-18 03:29:45 +00004209/// SemaConvertVectorExpr - Handle __builtin_convertvector
4210ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
4211 SourceLocation BuiltinLoc,
4212 SourceLocation RParenLoc) {
4213 ExprValueKind VK = VK_RValue;
4214 ExprObjectKind OK = OK_Ordinary;
4215 QualType DstTy = TInfo->getType();
4216 QualType SrcTy = E->getType();
4217
4218 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
4219 return ExprError(Diag(BuiltinLoc,
4220 diag::err_convertvector_non_vector)
4221 << E->getSourceRange());
4222 if (!DstTy->isVectorType() && !DstTy->isDependentType())
4223 return ExprError(Diag(BuiltinLoc,
4224 diag::err_convertvector_non_vector_type));
4225
4226 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
4227 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
4228 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
4229 if (SrcElts != DstElts)
4230 return ExprError(Diag(BuiltinLoc,
4231 diag::err_convertvector_incompatible_vector)
4232 << E->getSourceRange());
4233 }
4234
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004235 return new (Context)
4236 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00004237}
4238
Daniel Dunbarb7257262008-07-21 22:59:13 +00004239/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
4240// This is declared to take (const void*, ...) and can take two
4241// optional constant int args.
4242bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00004243 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00004244
Chris Lattner3b054132008-11-19 05:08:23 +00004245 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004246 return Diag(TheCall->getLocEnd(),
4247 diag::err_typecheck_call_too_many_args_at_most)
4248 << 0 /*function call*/ << 3 << NumArgs
4249 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00004250
4251 // Argument 0 is checked for us and the remaining arguments must be
4252 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00004253 for (unsigned i = 1; i != NumArgs; ++i)
4254 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00004255 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004256
Warren Hunt20e4a5d2014-02-21 23:08:53 +00004257 return false;
4258}
4259
Hal Finkelf0417332014-07-17 14:25:55 +00004260/// SemaBuiltinAssume - Handle __assume (MS Extension).
4261// __assume does not evaluate its arguments, and should warn if its argument
4262// has side effects.
4263bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
4264 Expr *Arg = TheCall->getArg(0);
4265 if (Arg->isInstantiationDependent()) return false;
4266
4267 if (Arg->HasSideEffects(Context))
David Majnemer51236642015-02-26 00:57:33 +00004268 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00004269 << Arg->getSourceRange()
4270 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
4271
4272 return false;
4273}
4274
David Majnemer86b1bfa2016-10-31 18:07:57 +00004275/// Handle __builtin_alloca_with_align. This is declared
David Majnemer51169932016-10-31 05:37:48 +00004276/// as (size_t, size_t) where the second size_t must be a power of 2 greater
4277/// than 8.
4278bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
4279 // The alignment must be a constant integer.
4280 Expr *Arg = TheCall->getArg(1);
4281
4282 // We can't check the value of a dependent argument.
4283 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
David Majnemer86b1bfa2016-10-31 18:07:57 +00004284 if (const auto *UE =
4285 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
4286 if (UE->getKind() == UETT_AlignOf)
4287 Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof)
4288 << Arg->getSourceRange();
4289
David Majnemer51169932016-10-31 05:37:48 +00004290 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
4291
4292 if (!Result.isPowerOf2())
4293 return Diag(TheCall->getLocStart(),
4294 diag::err_alignment_not_power_of_two)
4295 << Arg->getSourceRange();
4296
4297 if (Result < Context.getCharWidth())
4298 return Diag(TheCall->getLocStart(), diag::err_alignment_too_small)
4299 << (unsigned)Context.getCharWidth()
4300 << Arg->getSourceRange();
4301
4302 if (Result > INT32_MAX)
4303 return Diag(TheCall->getLocStart(), diag::err_alignment_too_big)
4304 << INT32_MAX
4305 << Arg->getSourceRange();
4306 }
4307
4308 return false;
4309}
4310
4311/// Handle __builtin_assume_aligned. This is declared
Hal Finkelbcc06082014-09-07 22:58:14 +00004312/// as (const void*, size_t, ...) and can take one optional constant int arg.
4313bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
4314 unsigned NumArgs = TheCall->getNumArgs();
4315
4316 if (NumArgs > 3)
4317 return Diag(TheCall->getLocEnd(),
4318 diag::err_typecheck_call_too_many_args_at_most)
4319 << 0 /*function call*/ << 3 << NumArgs
4320 << TheCall->getSourceRange();
4321
4322 // The alignment must be a constant integer.
4323 Expr *Arg = TheCall->getArg(1);
4324
4325 // We can't check the value of a dependent argument.
4326 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
4327 llvm::APSInt Result;
4328 if (SemaBuiltinConstantArg(TheCall, 1, Result))
4329 return true;
4330
4331 if (!Result.isPowerOf2())
4332 return Diag(TheCall->getLocStart(),
4333 diag::err_alignment_not_power_of_two)
4334 << Arg->getSourceRange();
4335 }
4336
4337 if (NumArgs > 2) {
4338 ExprResult Arg(TheCall->getArg(2));
4339 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
4340 Context.getSizeType(), false);
4341 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4342 if (Arg.isInvalid()) return true;
4343 TheCall->setArg(2, Arg.get());
4344 }
Hal Finkelf0417332014-07-17 14:25:55 +00004345
4346 return false;
4347}
4348
Mehdi Amini06d367c2016-10-24 20:39:34 +00004349bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
4350 unsigned BuiltinID =
4351 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
4352 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
4353
4354 unsigned NumArgs = TheCall->getNumArgs();
4355 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
4356 if (NumArgs < NumRequiredArgs) {
4357 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4358 << 0 /* function call */ << NumRequiredArgs << NumArgs
4359 << TheCall->getSourceRange();
4360 }
4361 if (NumArgs >= NumRequiredArgs + 0x100) {
4362 return Diag(TheCall->getLocEnd(),
4363 diag::err_typecheck_call_too_many_args_at_most)
4364 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
4365 << TheCall->getSourceRange();
4366 }
4367 unsigned i = 0;
4368
4369 // For formatting call, check buffer arg.
4370 if (!IsSizeCall) {
4371 ExprResult Arg(TheCall->getArg(i));
4372 InitializedEntity Entity = InitializedEntity::InitializeParameter(
4373 Context, Context.VoidPtrTy, false);
4374 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4375 if (Arg.isInvalid())
4376 return true;
4377 TheCall->setArg(i, Arg.get());
4378 i++;
4379 }
4380
4381 // Check string literal arg.
4382 unsigned FormatIdx = i;
4383 {
4384 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
4385 if (Arg.isInvalid())
4386 return true;
4387 TheCall->setArg(i, Arg.get());
4388 i++;
4389 }
4390
4391 // Make sure variadic args are scalar.
4392 unsigned FirstDataArg = i;
4393 while (i < NumArgs) {
4394 ExprResult Arg = DefaultVariadicArgumentPromotion(
4395 TheCall->getArg(i), VariadicFunction, nullptr);
4396 if (Arg.isInvalid())
4397 return true;
4398 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
4399 if (ArgSize.getQuantity() >= 0x100) {
4400 return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big)
4401 << i << (int)ArgSize.getQuantity() << 0xff
4402 << TheCall->getSourceRange();
4403 }
4404 TheCall->setArg(i, Arg.get());
4405 i++;
4406 }
4407
4408 // Check formatting specifiers. NOTE: We're only doing this for the non-size
4409 // call to avoid duplicate diagnostics.
4410 if (!IsSizeCall) {
4411 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
4412 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
4413 bool Success = CheckFormatArguments(
4414 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
4415 VariadicFunction, TheCall->getLocStart(), SourceRange(),
4416 CheckedVarArgs);
4417 if (!Success)
4418 return true;
4419 }
4420
4421 if (IsSizeCall) {
4422 TheCall->setType(Context.getSizeType());
4423 } else {
4424 TheCall->setType(Context.VoidPtrTy);
4425 }
4426 return false;
4427}
4428
Eric Christopher8d0c6212010-04-17 02:26:23 +00004429/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
4430/// TheCall is a constant expression.
4431bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
4432 llvm::APSInt &Result) {
4433 Expr *Arg = TheCall->getArg(ArgNum);
4434 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4435 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4436
4437 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
4438
4439 if (!Arg->isIntegerConstantExpr(Result, Context))
4440 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00004441 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00004442
Chris Lattnerd545ad12009-09-23 06:06:36 +00004443 return false;
4444}
4445
Richard Sandiford28940af2014-04-16 08:47:51 +00004446/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
4447/// TheCall is a constant expression in the range [Low, High].
4448bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
4449 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00004450 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00004451
4452 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00004453 Expr *Arg = TheCall->getArg(ArgNum);
4454 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00004455 return false;
4456
Eric Christopher8d0c6212010-04-17 02:26:23 +00004457 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00004458 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00004459 return true;
4460
Richard Sandiford28940af2014-04-16 08:47:51 +00004461 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00004462 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00004463 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00004464
4465 return false;
4466}
4467
Simon Dardis1f90f2d2016-10-19 17:50:52 +00004468/// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
4469/// TheCall is a constant expression is a multiple of Num..
4470bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
4471 unsigned Num) {
4472 llvm::APSInt Result;
4473
4474 // We can't check the value of a dependent argument.
4475 Expr *Arg = TheCall->getArg(ArgNum);
4476 if (Arg->isTypeDependent() || Arg->isValueDependent())
4477 return false;
4478
4479 // Check constant-ness first.
4480 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4481 return true;
4482
4483 if (Result.getSExtValue() % Num != 0)
4484 return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple)
4485 << Num << Arg->getSourceRange();
4486
4487 return false;
4488}
4489
Luke Cheeseman59b2d832015-06-15 17:51:01 +00004490/// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
4491/// TheCall is an ARM/AArch64 special register string literal.
4492bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
4493 int ArgNum, unsigned ExpectedFieldNum,
4494 bool AllowName) {
4495 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
4496 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
4497 BuiltinID == ARM::BI__builtin_arm_rsr ||
4498 BuiltinID == ARM::BI__builtin_arm_rsrp ||
4499 BuiltinID == ARM::BI__builtin_arm_wsr ||
4500 BuiltinID == ARM::BI__builtin_arm_wsrp;
4501 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
4502 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
4503 BuiltinID == AArch64::BI__builtin_arm_rsr ||
4504 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
4505 BuiltinID == AArch64::BI__builtin_arm_wsr ||
4506 BuiltinID == AArch64::BI__builtin_arm_wsrp;
4507 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
4508
4509 // We can't check the value of a dependent argument.
4510 Expr *Arg = TheCall->getArg(ArgNum);
4511 if (Arg->isTypeDependent() || Arg->isValueDependent())
4512 return false;
4513
4514 // Check if the argument is a string literal.
4515 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4516 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
4517 << Arg->getSourceRange();
4518
4519 // Check the type of special register given.
4520 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4521 SmallVector<StringRef, 6> Fields;
4522 Reg.split(Fields, ":");
4523
4524 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
4525 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4526 << Arg->getSourceRange();
4527
4528 // If the string is the name of a register then we cannot check that it is
4529 // valid here but if the string is of one the forms described in ACLE then we
4530 // can check that the supplied fields are integers and within the valid
4531 // ranges.
4532 if (Fields.size() > 1) {
4533 bool FiveFields = Fields.size() == 5;
4534
4535 bool ValidString = true;
4536 if (IsARMBuiltin) {
4537 ValidString &= Fields[0].startswith_lower("cp") ||
4538 Fields[0].startswith_lower("p");
4539 if (ValidString)
4540 Fields[0] =
4541 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
4542
4543 ValidString &= Fields[2].startswith_lower("c");
4544 if (ValidString)
4545 Fields[2] = Fields[2].drop_front(1);
4546
4547 if (FiveFields) {
4548 ValidString &= Fields[3].startswith_lower("c");
4549 if (ValidString)
4550 Fields[3] = Fields[3].drop_front(1);
4551 }
4552 }
4553
4554 SmallVector<int, 5> Ranges;
4555 if (FiveFields)
Oleg Ranevskyy85d93a82016-11-18 21:00:08 +00004556 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
Luke Cheeseman59b2d832015-06-15 17:51:01 +00004557 else
4558 Ranges.append({15, 7, 15});
4559
4560 for (unsigned i=0; i<Fields.size(); ++i) {
4561 int IntField;
4562 ValidString &= !Fields[i].getAsInteger(10, IntField);
4563 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
4564 }
4565
4566 if (!ValidString)
4567 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4568 << Arg->getSourceRange();
4569
4570 } else if (IsAArch64Builtin && Fields.size() == 1) {
4571 // If the register name is one of those that appear in the condition below
4572 // and the special register builtin being used is one of the write builtins,
4573 // then we require that the argument provided for writing to the register
4574 // is an integer constant expression. This is because it will be lowered to
4575 // an MSR (immediate) instruction, so we need to know the immediate at
4576 // compile time.
4577 if (TheCall->getNumArgs() != 2)
4578 return false;
4579
4580 std::string RegLower = Reg.lower();
4581 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
4582 RegLower != "pan" && RegLower != "uao")
4583 return false;
4584
4585 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
4586 }
4587
4588 return false;
4589}
4590
Eli Friedmanc97d0142009-05-03 06:04:26 +00004591/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004592/// This checks that the target supports __builtin_longjmp and
4593/// that val is a constant 1.
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004594bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004595 if (!Context.getTargetInfo().hasSjLjLowering())
4596 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
4597 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4598
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004599 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00004600 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00004601
Eric Christopher8d0c6212010-04-17 02:26:23 +00004602 // TODO: This is less than ideal. Overload this to take a value.
4603 if (SemaBuiltinConstantArg(TheCall, 1, Result))
4604 return true;
4605
4606 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004607 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
4608 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
4609
4610 return false;
4611}
4612
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004613/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
4614/// This checks that the target supports __builtin_setjmp.
4615bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
4616 if (!Context.getTargetInfo().hasSjLjLowering())
4617 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
4618 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4619 return false;
4620}
4621
Richard Smithd7293d72013-08-05 18:49:43 +00004622namespace {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004623class UncoveredArgHandler {
4624 enum { Unknown = -1, AllCovered = -2 };
4625 signed FirstUncoveredArg;
4626 SmallVector<const Expr *, 4> DiagnosticExprs;
4627
4628public:
4629 UncoveredArgHandler() : FirstUncoveredArg(Unknown) { }
4630
4631 bool hasUncoveredArg() const {
4632 return (FirstUncoveredArg >= 0);
4633 }
4634
4635 unsigned getUncoveredArg() const {
4636 assert(hasUncoveredArg() && "no uncovered argument");
4637 return FirstUncoveredArg;
4638 }
4639
4640 void setAllCovered() {
4641 // A string has been found with all arguments covered, so clear out
4642 // the diagnostics.
4643 DiagnosticExprs.clear();
4644 FirstUncoveredArg = AllCovered;
4645 }
4646
4647 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
4648 assert(NewFirstUncoveredArg >= 0 && "Outside range");
4649
4650 // Don't update if a previous string covers all arguments.
4651 if (FirstUncoveredArg == AllCovered)
4652 return;
4653
4654 // UncoveredArgHandler tracks the highest uncovered argument index
4655 // and with it all the strings that match this index.
4656 if (NewFirstUncoveredArg == FirstUncoveredArg)
4657 DiagnosticExprs.push_back(StrExpr);
4658 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
4659 DiagnosticExprs.clear();
4660 DiagnosticExprs.push_back(StrExpr);
4661 FirstUncoveredArg = NewFirstUncoveredArg;
4662 }
4663 }
4664
4665 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
4666};
4667
Richard Smithd7293d72013-08-05 18:49:43 +00004668enum StringLiteralCheckType {
4669 SLCT_NotALiteral,
4670 SLCT_UncheckedLiteral,
4671 SLCT_CheckedLiteral
4672};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004673} // end anonymous namespace
Richard Smithd7293d72013-08-05 18:49:43 +00004674
Stephen Hines648c3692016-09-16 01:07:04 +00004675static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
4676 BinaryOperatorKind BinOpKind,
4677 bool AddendIsRight) {
4678 unsigned BitWidth = Offset.getBitWidth();
4679 unsigned AddendBitWidth = Addend.getBitWidth();
4680 // There might be negative interim results.
4681 if (Addend.isUnsigned()) {
4682 Addend = Addend.zext(++AddendBitWidth);
4683 Addend.setIsSigned(true);
4684 }
4685 // Adjust the bit width of the APSInts.
4686 if (AddendBitWidth > BitWidth) {
4687 Offset = Offset.sext(AddendBitWidth);
4688 BitWidth = AddendBitWidth;
4689 } else if (BitWidth > AddendBitWidth) {
4690 Addend = Addend.sext(BitWidth);
4691 }
4692
4693 bool Ov = false;
4694 llvm::APSInt ResOffset = Offset;
4695 if (BinOpKind == BO_Add)
4696 ResOffset = Offset.sadd_ov(Addend, Ov);
4697 else {
4698 assert(AddendIsRight && BinOpKind == BO_Sub &&
4699 "operator must be add or sub with addend on the right");
4700 ResOffset = Offset.ssub_ov(Addend, Ov);
4701 }
4702
4703 // We add an offset to a pointer here so we should support an offset as big as
4704 // possible.
4705 if (Ov) {
4706 assert(BitWidth <= UINT_MAX / 2 && "index (intermediate) result too big");
Stephen Hinesfec73ad2016-09-16 07:21:24 +00004707 Offset = Offset.sext(2 * BitWidth);
Stephen Hines648c3692016-09-16 01:07:04 +00004708 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
4709 return;
4710 }
4711
4712 Offset = ResOffset;
4713}
4714
4715namespace {
4716// This is a wrapper class around StringLiteral to support offsetted string
4717// literals as format strings. It takes the offset into account when returning
4718// the string and its length or the source locations to display notes correctly.
4719class FormatStringLiteral {
4720 const StringLiteral *FExpr;
4721 int64_t Offset;
4722
4723 public:
4724 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
4725 : FExpr(fexpr), Offset(Offset) {}
4726
4727 StringRef getString() const {
4728 return FExpr->getString().drop_front(Offset);
4729 }
4730
4731 unsigned getByteLength() const {
4732 return FExpr->getByteLength() - getCharByteWidth() * Offset;
4733 }
4734 unsigned getLength() const { return FExpr->getLength() - Offset; }
4735 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
4736
4737 StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
4738
4739 QualType getType() const { return FExpr->getType(); }
4740
4741 bool isAscii() const { return FExpr->isAscii(); }
4742 bool isWide() const { return FExpr->isWide(); }
4743 bool isUTF8() const { return FExpr->isUTF8(); }
4744 bool isUTF16() const { return FExpr->isUTF16(); }
4745 bool isUTF32() const { return FExpr->isUTF32(); }
4746 bool isPascal() const { return FExpr->isPascal(); }
4747
4748 SourceLocation getLocationOfByte(
4749 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
4750 const TargetInfo &Target, unsigned *StartToken = nullptr,
4751 unsigned *StartTokenByteOffset = nullptr) const {
4752 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
4753 StartToken, StartTokenByteOffset);
4754 }
4755
4756 SourceLocation getLocStart() const LLVM_READONLY {
4757 return FExpr->getLocStart().getLocWithOffset(Offset);
4758 }
4759 SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); }
4760};
4761} // end anonymous namespace
4762
4763static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004764 const Expr *OrigFormatExpr,
4765 ArrayRef<const Expr *> Args,
4766 bool HasVAListArg, unsigned format_idx,
4767 unsigned firstDataArg,
4768 Sema::FormatStringType Type,
4769 bool inFunctionCall,
4770 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004771 llvm::SmallBitVector &CheckedVarArgs,
4772 UncoveredArgHandler &UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004773
Richard Smith55ce3522012-06-25 20:30:08 +00004774// Determine if an expression is a string literal or constant string.
4775// If this function returns false on the arguments to a function expecting a
4776// format string, we will usually need to emit a warning.
4777// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00004778static StringLiteralCheckType
4779checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
4780 bool HasVAListArg, unsigned format_idx,
4781 unsigned firstDataArg, Sema::FormatStringType Type,
4782 Sema::VariadicCallType CallType, bool InFunctionCall,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004783 llvm::SmallBitVector &CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00004784 UncoveredArgHandler &UncoveredArg,
4785 llvm::APSInt Offset) {
Ted Kremenek808829352010-09-09 03:51:39 +00004786 tryAgain:
Stephen Hines648c3692016-09-16 01:07:04 +00004787 assert(Offset.isSigned() && "invalid offset");
4788
Douglas Gregorc25f7662009-05-19 22:10:17 +00004789 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00004790 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004791
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004792 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00004793
Richard Smithd7293d72013-08-05 18:49:43 +00004794 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00004795 // Technically -Wformat-nonliteral does not warn about this case.
4796 // The behavior of printf and friends in this case is implementation
4797 // dependent. Ideally if the format string cannot be null then
4798 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00004799 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00004800
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004801 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00004802 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004803 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00004804 // The expression is a literal if both sub-expressions were, and it was
4805 // completely checked only if both sub-expressions were checked.
4806 const AbstractConditionalOperator *C =
4807 cast<AbstractConditionalOperator>(E);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004808
4809 // Determine whether it is necessary to check both sub-expressions, for
4810 // example, because the condition expression is a constant that can be
4811 // evaluated at compile time.
4812 bool CheckLeft = true, CheckRight = true;
4813
4814 bool Cond;
4815 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
4816 if (Cond)
4817 CheckRight = false;
4818 else
4819 CheckLeft = false;
4820 }
4821
Stephen Hines648c3692016-09-16 01:07:04 +00004822 // We need to maintain the offsets for the right and the left hand side
4823 // separately to check if every possible indexed expression is a valid
4824 // string literal. They might have different offsets for different string
4825 // literals in the end.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004826 StringLiteralCheckType Left;
4827 if (!CheckLeft)
4828 Left = SLCT_UncheckedLiteral;
4829 else {
4830 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
4831 HasVAListArg, format_idx, firstDataArg,
4832 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00004833 CheckedVarArgs, UncoveredArg, Offset);
4834 if (Left == SLCT_NotALiteral || !CheckRight) {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004835 return Left;
Stephen Hines648c3692016-09-16 01:07:04 +00004836 }
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004837 }
4838
Richard Smith55ce3522012-06-25 20:30:08 +00004839 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00004840 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004841 HasVAListArg, format_idx, firstDataArg,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004842 Type, CallType, InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00004843 UncoveredArg, Offset);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004844
4845 return (CheckLeft && Left < Right) ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004846 }
4847
4848 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00004849 E = cast<ImplicitCastExpr>(E)->getSubExpr();
4850 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004851 }
4852
John McCallc07a0c72011-02-17 10:25:35 +00004853 case Stmt::OpaqueValueExprClass:
4854 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
4855 E = src;
4856 goto tryAgain;
4857 }
Richard Smith55ce3522012-06-25 20:30:08 +00004858 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00004859
Ted Kremeneka8890832011-02-24 23:03:04 +00004860 case Stmt::PredefinedExprClass:
4861 // While __func__, etc., are technically not string literals, they
4862 // cannot contain format specifiers and thus are not a security
4863 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00004864 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00004865
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004866 case Stmt::DeclRefExprClass: {
4867 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004868
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004869 // As an exception, do not flag errors for variables binding to
4870 // const string literals.
4871 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
4872 bool isConstant = false;
4873 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004874
Richard Smithd7293d72013-08-05 18:49:43 +00004875 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
4876 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00004877 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00004878 isConstant = T.isConstant(S.Context) &&
4879 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00004880 } else if (T->isObjCObjectPointerType()) {
4881 // In ObjC, there is usually no "const ObjectPointer" type,
4882 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00004883 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004884 }
Mike Stump11289f42009-09-09 15:08:12 +00004885
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004886 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00004887 if (const Expr *Init = VD->getAnyInitializer()) {
4888 // Look through initializers like const char c[] = { "foo" }
4889 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4890 if (InitList->isStringLiteralInit())
4891 Init = InitList->getInit(0)->IgnoreParenImpCasts();
4892 }
Richard Smithd7293d72013-08-05 18:49:43 +00004893 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004894 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004895 firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00004896 /*InFunctionCall*/ false, CheckedVarArgs,
4897 UncoveredArg, Offset);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00004898 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004899 }
Mike Stump11289f42009-09-09 15:08:12 +00004900
Anders Carlssonb012ca92009-06-28 19:55:58 +00004901 // For vprintf* functions (i.e., HasVAListArg==true), we add a
4902 // special check to see if the format string is a function parameter
4903 // of the function calling the printf function. If the function
4904 // has an attribute indicating it is a printf-like function, then we
4905 // should suppress warnings concerning non-literals being used in a call
4906 // to a vprintf function. For example:
4907 //
4908 // void
4909 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
4910 // va_list ap;
4911 // va_start(ap, fmt);
4912 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
4913 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00004914 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004915 if (HasVAListArg) {
4916 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
4917 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
4918 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00004919 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004920 // adjust for implicit parameter
4921 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4922 if (MD->isInstance())
4923 ++PVIndex;
4924 // We also check if the formats are compatible.
4925 // We can't pass a 'scanf' string to a 'printf' function.
4926 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00004927 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00004928 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004929 }
4930 }
4931 }
4932 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004933 }
Mike Stump11289f42009-09-09 15:08:12 +00004934
Richard Smith55ce3522012-06-25 20:30:08 +00004935 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004936 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004937
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00004938 case Stmt::CallExprClass:
4939 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00004940 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00004941 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
4942 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
4943 unsigned ArgIndex = FA->getFormatIdx();
4944 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4945 if (MD->isInstance())
4946 --ArgIndex;
4947 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00004948
Richard Smithd7293d72013-08-05 18:49:43 +00004949 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004950 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00004951 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00004952 CheckedVarArgs, UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004953 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4954 unsigned BuiltinID = FD->getBuiltinID();
4955 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
4956 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
4957 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00004958 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004959 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004960 firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004961 InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00004962 UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004963 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00004964 }
4965 }
Mike Stump11289f42009-09-09 15:08:12 +00004966
Richard Smith55ce3522012-06-25 20:30:08 +00004967 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00004968 }
Alex Lorenzd9007142016-10-24 09:42:34 +00004969 case Stmt::ObjCMessageExprClass: {
4970 const auto *ME = cast<ObjCMessageExpr>(E);
4971 if (const auto *ND = ME->getMethodDecl()) {
4972 if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
4973 unsigned ArgIndex = FA->getFormatIdx();
4974 const Expr *Arg = ME->getArg(ArgIndex - 1);
4975 return checkFormatStringExpr(
4976 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
4977 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
4978 }
4979 }
4980
4981 return SLCT_NotALiteral;
4982 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004983 case Stmt::ObjCStringLiteralClass:
4984 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00004985 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004986
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004987 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004988 StrE = ObjCFExpr->getString();
4989 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004990 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004991
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004992 if (StrE) {
Stephen Hines648c3692016-09-16 01:07:04 +00004993 if (Offset.isNegative() || Offset > StrE->getLength()) {
4994 // TODO: It would be better to have an explicit warning for out of
4995 // bounds literals.
4996 return SLCT_NotALiteral;
4997 }
4998 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
4999 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005000 firstDataArg, Type, InFunctionCall, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005001 CheckedVarArgs, UncoveredArg);
Richard Smith55ce3522012-06-25 20:30:08 +00005002 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005003 }
Mike Stump11289f42009-09-09 15:08:12 +00005004
Richard Smith55ce3522012-06-25 20:30:08 +00005005 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005006 }
Stephen Hines648c3692016-09-16 01:07:04 +00005007 case Stmt::BinaryOperatorClass: {
5008 llvm::APSInt LResult;
5009 llvm::APSInt RResult;
5010
5011 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
5012
5013 // A string literal + an int offset is still a string literal.
5014 if (BinOp->isAdditiveOp()) {
5015 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
5016 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
5017
5018 if (LIsInt != RIsInt) {
5019 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
5020
5021 if (LIsInt) {
5022 if (BinOpKind == BO_Add) {
5023 sumOffsets(Offset, LResult, BinOpKind, RIsInt);
5024 E = BinOp->getRHS();
5025 goto tryAgain;
5026 }
5027 } else {
5028 sumOffsets(Offset, RResult, BinOpKind, RIsInt);
5029 E = BinOp->getLHS();
5030 goto tryAgain;
5031 }
5032 }
Stephen Hines648c3692016-09-16 01:07:04 +00005033 }
George Burgess IVd273aab2016-09-22 00:00:26 +00005034
5035 return SLCT_NotALiteral;
Stephen Hines648c3692016-09-16 01:07:04 +00005036 }
5037 case Stmt::UnaryOperatorClass: {
5038 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
5039 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
5040 if (UnaOp->getOpcode() == clang::UO_AddrOf && ASE) {
5041 llvm::APSInt IndexResult;
5042 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
5043 sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true);
5044 E = ASE->getBase();
5045 goto tryAgain;
5046 }
5047 }
5048
5049 return SLCT_NotALiteral;
5050 }
Mike Stump11289f42009-09-09 15:08:12 +00005051
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005052 default:
Richard Smith55ce3522012-06-25 20:30:08 +00005053 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005054 }
5055}
5056
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005057Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00005058 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Mehdi Amini06d367c2016-10-24 20:39:34 +00005059 .Case("scanf", FST_Scanf)
5060 .Cases("printf", "printf0", FST_Printf)
5061 .Cases("NSString", "CFString", FST_NSString)
5062 .Case("strftime", FST_Strftime)
5063 .Case("strfmon", FST_Strfmon)
5064 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
5065 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
5066 .Case("os_trace", FST_OSLog)
5067 .Case("os_log", FST_OSLog)
5068 .Default(FST_Unknown);
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005069}
5070
Jordan Rose3e0ec582012-07-19 18:10:23 +00005071/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00005072/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00005073/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005074bool Sema::CheckFormatArguments(const FormatAttr *Format,
5075 ArrayRef<const Expr *> Args,
5076 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005077 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00005078 SourceLocation Loc, SourceRange Range,
5079 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00005080 FormatStringInfo FSI;
5081 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005082 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00005083 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00005084 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00005085 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005086}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00005087
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005088bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005089 bool HasVAListArg, unsigned format_idx,
5090 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005091 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00005092 SourceLocation Loc, SourceRange Range,
5093 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00005094 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005095 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005096 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00005097 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00005098 }
Mike Stump11289f42009-09-09 15:08:12 +00005099
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005100 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00005101
Chris Lattnerb87b1b32007-08-10 20:18:51 +00005102 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00005103 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00005104 // Dynamically generated format strings are difficult to
5105 // automatically vet at compile time. Requiring that format strings
5106 // are string literals: (1) permits the checking of format strings by
5107 // the compiler and thereby (2) can practically remove the source of
5108 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00005109
Mike Stump11289f42009-09-09 15:08:12 +00005110 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00005111 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00005112 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00005113 // the same format string checking logic for both ObjC and C strings.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005114 UncoveredArgHandler UncoveredArg;
Richard Smith55ce3522012-06-25 20:30:08 +00005115 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00005116 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
5117 format_idx, firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00005118 /*IsFunctionCall*/ true, CheckedVarArgs,
5119 UncoveredArg,
5120 /*no string offset*/ llvm::APSInt(64, false) = 0);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005121
5122 // Generate a diagnostic where an uncovered argument is detected.
5123 if (UncoveredArg.hasUncoveredArg()) {
5124 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
5125 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
5126 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
5127 }
5128
Richard Smith55ce3522012-06-25 20:30:08 +00005129 if (CT != SLCT_NotALiteral)
5130 // Literal format string found, check done!
5131 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00005132
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00005133 // Strftime is particular as it always uses a single 'time' argument,
5134 // so it is safe to pass a non-literal string.
5135 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00005136 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00005137
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00005138 // Do not emit diag when the string param is a macro expansion and the
5139 // format is either NSString or CFString. This is a hack to prevent
5140 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
5141 // which are usually used in place of NS and CF string literals.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005142 SourceLocation FormatLoc = Args[format_idx]->getLocStart();
5143 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
Richard Smith55ce3522012-06-25 20:30:08 +00005144 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00005145
Chris Lattnercc5d1c22009-04-29 04:59:47 +00005146 // If there are no arguments specified, warn with -Wformat-security, otherwise
5147 // warn only with -Wformat-nonliteral.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005148 if (Args.size() == firstDataArg) {
Bob Wilson57819fc2016-03-15 20:56:38 +00005149 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
5150 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005151 switch (Type) {
5152 default:
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005153 break;
5154 case FST_Kprintf:
5155 case FST_FreeBSDKPrintf:
5156 case FST_Printf:
Bob Wilson57819fc2016-03-15 20:56:38 +00005157 Diag(FormatLoc, diag::note_format_security_fixit)
5158 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005159 break;
5160 case FST_NSString:
Bob Wilson57819fc2016-03-15 20:56:38 +00005161 Diag(FormatLoc, diag::note_format_security_fixit)
5162 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005163 break;
5164 }
5165 } else {
5166 Diag(FormatLoc, diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00005167 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005168 }
Richard Smith55ce3522012-06-25 20:30:08 +00005169 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005170}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00005171
Ted Kremenekab278de2010-01-28 23:39:18 +00005172namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00005173class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
5174protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00005175 Sema &S;
Stephen Hines648c3692016-09-16 01:07:04 +00005176 const FormatStringLiteral *FExpr;
Ted Kremenekab278de2010-01-28 23:39:18 +00005177 const Expr *OrigFormatExpr;
Mehdi Amini06d367c2016-10-24 20:39:34 +00005178 const Sema::FormatStringType FSType;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00005179 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00005180 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00005181 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00005182 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005183 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00005184 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00005185 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00005186 bool usesPositionalArgs;
5187 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00005188 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00005189 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00005190 llvm::SmallBitVector &CheckedVarArgs;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005191 UncoveredArgHandler &UncoveredArg;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005192
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005193public:
Stephen Hines648c3692016-09-16 01:07:04 +00005194 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00005195 const Expr *origFormatExpr,
5196 const Sema::FormatStringType type, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005197 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Mehdi Amini06d367c2016-10-24 20:39:34 +00005198 ArrayRef<const Expr *> Args, unsigned formatIdx,
5199 bool inFunctionCall, Sema::VariadicCallType callType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005200 llvm::SmallBitVector &CheckedVarArgs,
5201 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00005202 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
5203 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
5204 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
5205 usesPositionalArgs(false), atFirstArg(true),
5206 inFunctionCall(inFunctionCall), CallType(callType),
5207 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
Richard Smithd7293d72013-08-05 18:49:43 +00005208 CoveredArgs.resize(numDataArgs);
5209 CoveredArgs.reset();
5210 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005211
Ted Kremenek019d2242010-01-29 01:50:07 +00005212 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005213
Ted Kremenek02087932010-07-16 02:11:22 +00005214 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005215 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005216
Jordan Rose92303592012-09-08 04:00:03 +00005217 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005218 const analyze_format_string::FormatSpecifier &FS,
5219 const analyze_format_string::ConversionSpecifier &CS,
5220 const char *startSpecifier, unsigned specifierLen,
5221 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00005222
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005223 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005224 const analyze_format_string::FormatSpecifier &FS,
5225 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005226
5227 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005228 const analyze_format_string::ConversionSpecifier &CS,
5229 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005230
Craig Toppere14c0f82014-03-12 04:55:44 +00005231 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00005232
Craig Toppere14c0f82014-03-12 04:55:44 +00005233 void HandleInvalidPosition(const char *startSpecifier,
5234 unsigned specifierLen,
5235 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00005236
Craig Toppere14c0f82014-03-12 04:55:44 +00005237 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00005238
Craig Toppere14c0f82014-03-12 04:55:44 +00005239 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005240
Richard Trieu03cf7b72011-10-28 00:41:25 +00005241 template <typename Range>
Benjamin Kramer7320b992016-06-15 14:20:56 +00005242 static void
5243 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
5244 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
5245 bool IsStringLocation, Range StringRange,
5246 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005247
Ted Kremenek02087932010-07-16 02:11:22 +00005248protected:
Ted Kremenekce815422010-07-19 21:25:57 +00005249 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
5250 const char *startSpec,
5251 unsigned specifierLen,
5252 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005253
5254 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
5255 const char *startSpec,
5256 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00005257
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005258 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00005259 CharSourceRange getSpecifierRange(const char *startSpecifier,
5260 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00005261 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005262
Ted Kremenek5739de72010-01-29 01:06:55 +00005263 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005264
5265 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
5266 const analyze_format_string::ConversionSpecifier &CS,
5267 const char *startSpecifier, unsigned specifierLen,
5268 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005269
5270 template <typename Range>
5271 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5272 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00005273 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00005274};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005275} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00005276
Ted Kremenek02087932010-07-16 02:11:22 +00005277SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00005278 return OrigFormatExpr->getSourceRange();
5279}
5280
Ted Kremenek02087932010-07-16 02:11:22 +00005281CharSourceRange CheckFormatHandler::
5282getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00005283 SourceLocation Start = getLocationOfByte(startSpecifier);
5284 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
5285
5286 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00005287 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00005288
5289 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005290}
5291
Ted Kremenek02087932010-07-16 02:11:22 +00005292SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Stephen Hines648c3692016-09-16 01:07:04 +00005293 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
5294 S.getLangOpts(), S.Context.getTargetInfo());
Ted Kremenekab278de2010-01-28 23:39:18 +00005295}
5296
Ted Kremenek02087932010-07-16 02:11:22 +00005297void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
5298 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00005299 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
5300 getLocationOfByte(startSpecifier),
5301 /*IsStringLocation*/true,
5302 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00005303}
5304
Jordan Rose92303592012-09-08 04:00:03 +00005305void CheckFormatHandler::HandleInvalidLengthModifier(
5306 const analyze_format_string::FormatSpecifier &FS,
5307 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00005308 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00005309 using namespace analyze_format_string;
5310
5311 const LengthModifier &LM = FS.getLengthModifier();
5312 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5313
5314 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00005315 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00005316 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005317 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00005318 getLocationOfByte(LM.getStart()),
5319 /*IsStringLocation*/true,
5320 getSpecifierRange(startSpecifier, specifierLen));
5321
5322 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5323 << FixedLM->toString()
5324 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5325
5326 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005327 FixItHint Hint;
5328 if (DiagID == diag::warn_format_nonsensical_length)
5329 Hint = FixItHint::CreateRemoval(LMRange);
5330
5331 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00005332 getLocationOfByte(LM.getStart()),
5333 /*IsStringLocation*/true,
5334 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00005335 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00005336 }
5337}
5338
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005339void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00005340 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005341 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005342 using namespace analyze_format_string;
5343
5344 const LengthModifier &LM = FS.getLengthModifier();
5345 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5346
5347 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00005348 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00005349 if (FixedLM) {
5350 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5351 << LM.toString() << 0,
5352 getLocationOfByte(LM.getStart()),
5353 /*IsStringLocation*/true,
5354 getSpecifierRange(startSpecifier, specifierLen));
5355
5356 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5357 << FixedLM->toString()
5358 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5359
5360 } else {
5361 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5362 << LM.toString() << 0,
5363 getLocationOfByte(LM.getStart()),
5364 /*IsStringLocation*/true,
5365 getSpecifierRange(startSpecifier, specifierLen));
5366 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005367}
5368
5369void CheckFormatHandler::HandleNonStandardConversionSpecifier(
5370 const analyze_format_string::ConversionSpecifier &CS,
5371 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00005372 using namespace analyze_format_string;
5373
5374 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00005375 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00005376 if (FixedCS) {
5377 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5378 << CS.toString() << /*conversion specifier*/1,
5379 getLocationOfByte(CS.getStart()),
5380 /*IsStringLocation*/true,
5381 getSpecifierRange(startSpecifier, specifierLen));
5382
5383 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
5384 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
5385 << FixedCS->toString()
5386 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
5387 } else {
5388 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5389 << CS.toString() << /*conversion specifier*/1,
5390 getLocationOfByte(CS.getStart()),
5391 /*IsStringLocation*/true,
5392 getSpecifierRange(startSpecifier, specifierLen));
5393 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005394}
5395
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00005396void CheckFormatHandler::HandlePosition(const char *startPos,
5397 unsigned posLen) {
5398 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
5399 getLocationOfByte(startPos),
5400 /*IsStringLocation*/true,
5401 getSpecifierRange(startPos, posLen));
5402}
5403
Ted Kremenekd1668192010-02-27 01:41:03 +00005404void
Ted Kremenek02087932010-07-16 02:11:22 +00005405CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
5406 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005407 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
5408 << (unsigned) p,
5409 getLocationOfByte(startPos), /*IsStringLocation*/true,
5410 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00005411}
5412
Ted Kremenek02087932010-07-16 02:11:22 +00005413void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00005414 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005415 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
5416 getLocationOfByte(startPos),
5417 /*IsStringLocation*/true,
5418 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00005419}
5420
Ted Kremenek02087932010-07-16 02:11:22 +00005421void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005422 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00005423 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00005424 EmitFormatDiagnostic(
5425 S.PDiag(diag::warn_printf_format_string_contains_null_char),
5426 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
5427 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00005428 }
Ted Kremenek02087932010-07-16 02:11:22 +00005429}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005430
Jordan Rose58bbe422012-07-19 18:10:08 +00005431// Note that this may return NULL if there was an error parsing or building
5432// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00005433const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005434 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00005435}
5436
5437void CheckFormatHandler::DoneProcessing() {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005438 // Does the number of data arguments exceed the number of
5439 // format conversions in the format string?
Ted Kremenek02087932010-07-16 02:11:22 +00005440 if (!HasVAListArg) {
5441 // Find any arguments that weren't covered.
5442 CoveredArgs.flip();
5443 signed notCoveredArg = CoveredArgs.find_first();
5444 if (notCoveredArg >= 0) {
5445 assert((unsigned)notCoveredArg < NumDataArgs);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005446 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
5447 } else {
5448 UncoveredArg.setAllCovered();
Ted Kremenek02087932010-07-16 02:11:22 +00005449 }
5450 }
5451}
5452
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005453void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
5454 const Expr *ArgExpr) {
5455 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
5456 "Invalid state");
5457
5458 if (!ArgExpr)
5459 return;
5460
5461 SourceLocation Loc = ArgExpr->getLocStart();
5462
5463 if (S.getSourceManager().isInSystemMacro(Loc))
5464 return;
5465
5466 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
5467 for (auto E : DiagnosticExprs)
5468 PDiag << E->getSourceRange();
5469
5470 CheckFormatHandler::EmitFormatDiagnostic(
5471 S, IsFunctionCall, DiagnosticExprs[0],
5472 PDiag, Loc, /*IsStringLocation*/false,
5473 DiagnosticExprs[0]->getSourceRange());
5474}
5475
Ted Kremenekce815422010-07-19 21:25:57 +00005476bool
5477CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
5478 SourceLocation Loc,
5479 const char *startSpec,
5480 unsigned specifierLen,
5481 const char *csStart,
5482 unsigned csLen) {
Ted Kremenekce815422010-07-19 21:25:57 +00005483 bool keepGoing = true;
5484 if (argIndex < NumDataArgs) {
5485 // Consider the argument coverered, even though the specifier doesn't
5486 // make sense.
5487 CoveredArgs.set(argIndex);
5488 }
5489 else {
5490 // If argIndex exceeds the number of data arguments we
5491 // don't issue a warning because that is just a cascade of warnings (and
5492 // they may have intended '%%' anyway). We don't want to continue processing
5493 // the format string after this point, however, as we will like just get
5494 // gibberish when trying to match arguments.
5495 keepGoing = false;
5496 }
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005497
5498 StringRef Specifier(csStart, csLen);
5499
5500 // If the specifier in non-printable, it could be the first byte of a UTF-8
5501 // sequence. In that case, print the UTF-8 code point. If not, print the byte
5502 // hex value.
5503 std::string CodePointStr;
5504 if (!llvm::sys::locale::isPrint(*csStart)) {
Justin Lebar90910552016-09-30 00:38:45 +00005505 llvm::UTF32 CodePoint;
5506 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
5507 const llvm::UTF8 *E =
5508 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
5509 llvm::ConversionResult Result =
5510 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005511
Justin Lebar90910552016-09-30 00:38:45 +00005512 if (Result != llvm::conversionOK) {
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005513 unsigned char FirstChar = *csStart;
Justin Lebar90910552016-09-30 00:38:45 +00005514 CodePoint = (llvm::UTF32)FirstChar;
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005515 }
5516
5517 llvm::raw_string_ostream OS(CodePointStr);
5518 if (CodePoint < 256)
5519 OS << "\\x" << llvm::format("%02x", CodePoint);
5520 else if (CodePoint <= 0xFFFF)
5521 OS << "\\u" << llvm::format("%04x", CodePoint);
5522 else
5523 OS << "\\U" << llvm::format("%08x", CodePoint);
5524 OS.flush();
5525 Specifier = CodePointStr;
5526 }
5527
5528 EmitFormatDiagnostic(
5529 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
5530 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
5531
Ted Kremenekce815422010-07-19 21:25:57 +00005532 return keepGoing;
5533}
5534
Richard Trieu03cf7b72011-10-28 00:41:25 +00005535void
5536CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
5537 const char *startSpec,
5538 unsigned specifierLen) {
5539 EmitFormatDiagnostic(
5540 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
5541 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
5542}
5543
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005544bool
5545CheckFormatHandler::CheckNumArgs(
5546 const analyze_format_string::FormatSpecifier &FS,
5547 const analyze_format_string::ConversionSpecifier &CS,
5548 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
5549
5550 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005551 PartialDiagnostic PDiag = FS.usesPositionalArg()
5552 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
5553 << (argIndex+1) << NumDataArgs)
5554 : S.PDiag(diag::warn_printf_insufficient_data_args);
5555 EmitFormatDiagnostic(
5556 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
5557 getSpecifierRange(startSpecifier, specifierLen));
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005558
5559 // Since more arguments than conversion tokens are given, by extension
5560 // all arguments are covered, so mark this as so.
5561 UncoveredArg.setAllCovered();
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005562 return false;
5563 }
5564 return true;
5565}
5566
Richard Trieu03cf7b72011-10-28 00:41:25 +00005567template<typename Range>
5568void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
5569 SourceLocation Loc,
5570 bool IsStringLocation,
5571 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00005572 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005573 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00005574 Loc, IsStringLocation, StringRange, FixIt);
5575}
5576
5577/// \brief If the format string is not within the funcion call, emit a note
5578/// so that the function call and string are in diagnostic messages.
5579///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00005580/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00005581/// call and only one diagnostic message will be produced. Otherwise, an
5582/// extra note will be emitted pointing to location of the format string.
5583///
5584/// \param ArgumentExpr the expression that is passed as the format string
5585/// argument in the function call. Used for getting locations when two
5586/// diagnostics are emitted.
5587///
5588/// \param PDiag the callee should already have provided any strings for the
5589/// diagnostic message. This function only adds locations and fixits
5590/// to diagnostics.
5591///
5592/// \param Loc primary location for diagnostic. If two diagnostics are
5593/// required, one will be at Loc and a new SourceLocation will be created for
5594/// the other one.
5595///
5596/// \param IsStringLocation if true, Loc points to the format string should be
5597/// used for the note. Otherwise, Loc points to the argument list and will
5598/// be used with PDiag.
5599///
5600/// \param StringRange some or all of the string to highlight. This is
5601/// templated so it can accept either a CharSourceRange or a SourceRange.
5602///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00005603/// \param FixIt optional fix it hint for the format string.
Benjamin Kramer7320b992016-06-15 14:20:56 +00005604template <typename Range>
5605void CheckFormatHandler::EmitFormatDiagnostic(
5606 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
5607 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
5608 Range StringRange, ArrayRef<FixItHint> FixIt) {
Jordan Roseaee34382012-09-05 22:56:26 +00005609 if (InFunctionCall) {
5610 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
5611 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00005612 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00005613 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005614 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
5615 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00005616
5617 const Sema::SemaDiagnosticBuilder &Note =
5618 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
5619 diag::note_format_string_defined);
5620
5621 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00005622 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00005623 }
5624}
5625
Ted Kremenek02087932010-07-16 02:11:22 +00005626//===--- CHECK: Printf format string checking ------------------------------===//
5627
5628namespace {
5629class CheckPrintfHandler : public CheckFormatHandler {
5630public:
Stephen Hines648c3692016-09-16 01:07:04 +00005631 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00005632 const Expr *origFormatExpr,
5633 const Sema::FormatStringType type, unsigned firstDataArg,
5634 unsigned numDataArgs, bool isObjC, const char *beg,
5635 bool hasVAListArg, ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005636 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00005637 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005638 llvm::SmallBitVector &CheckedVarArgs,
5639 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00005640 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
5641 numDataArgs, beg, hasVAListArg, Args, formatIdx,
5642 inFunctionCall, CallType, CheckedVarArgs,
5643 UncoveredArg) {}
5644
5645 bool isObjCContext() const { return FSType == Sema::FST_NSString; }
5646
5647 /// Returns true if '%@' specifiers are allowed in the format string.
5648 bool allowsObjCArg() const {
5649 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
5650 FSType == Sema::FST_OSTrace;
5651 }
Jordan Rose3e0ec582012-07-19 18:10:23 +00005652
Ted Kremenek02087932010-07-16 02:11:22 +00005653 bool HandleInvalidPrintfConversionSpecifier(
5654 const analyze_printf::PrintfSpecifier &FS,
5655 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005656 unsigned specifierLen) override;
5657
Ted Kremenek02087932010-07-16 02:11:22 +00005658 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
5659 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005660 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00005661 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5662 const char *StartSpecifier,
5663 unsigned SpecifierLen,
5664 const Expr *E);
5665
Ted Kremenek02087932010-07-16 02:11:22 +00005666 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
5667 const char *startSpecifier, unsigned specifierLen);
5668 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
5669 const analyze_printf::OptionalAmount &Amt,
5670 unsigned type,
5671 const char *startSpecifier, unsigned specifierLen);
5672 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
5673 const analyze_printf::OptionalFlag &flag,
5674 const char *startSpecifier, unsigned specifierLen);
5675 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
5676 const analyze_printf::OptionalFlag &ignoredFlag,
5677 const analyze_printf::OptionalFlag &flag,
5678 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005679 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00005680 const Expr *E);
Ted Kremenek2b417712015-07-02 05:39:16 +00005681
5682 void HandleEmptyObjCModifierFlag(const char *startFlag,
5683 unsigned flagLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00005684
Ted Kremenek2b417712015-07-02 05:39:16 +00005685 void HandleInvalidObjCModifierFlag(const char *startFlag,
5686 unsigned flagLen) override;
5687
5688 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
5689 const char *flagsEnd,
5690 const char *conversionPosition)
5691 override;
5692};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005693} // end anonymous namespace
Ted Kremenek02087932010-07-16 02:11:22 +00005694
5695bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
5696 const analyze_printf::PrintfSpecifier &FS,
5697 const char *startSpecifier,
5698 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005699 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00005700 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00005701
Ted Kremenekce815422010-07-19 21:25:57 +00005702 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
5703 getLocationOfByte(CS.getStart()),
5704 startSpecifier, specifierLen,
5705 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00005706}
5707
Ted Kremenek02087932010-07-16 02:11:22 +00005708bool CheckPrintfHandler::HandleAmount(
5709 const analyze_format_string::OptionalAmount &Amt,
5710 unsigned k, const char *startSpecifier,
5711 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00005712 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00005713 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00005714 unsigned argIndex = Amt.getArgIndex();
5715 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005716 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
5717 << k,
5718 getLocationOfByte(Amt.getStart()),
5719 /*IsStringLocation*/true,
5720 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00005721 // Don't do any more checking. We will just emit
5722 // spurious errors.
5723 return false;
5724 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005725
Ted Kremenek5739de72010-01-29 01:06:55 +00005726 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00005727 // Although not in conformance with C99, we also allow the argument to be
5728 // an 'unsigned int' as that is a reasonably safe case. GCC also
5729 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00005730 CoveredArgs.set(argIndex);
5731 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00005732 if (!Arg)
5733 return false;
5734
Ted Kremenek5739de72010-01-29 01:06:55 +00005735 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005736
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005737 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
5738 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005739
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005740 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005741 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005742 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00005743 << T << Arg->getSourceRange(),
5744 getLocationOfByte(Amt.getStart()),
5745 /*IsStringLocation*/true,
5746 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00005747 // Don't do any more checking. We will just emit
5748 // spurious errors.
5749 return false;
5750 }
5751 }
5752 }
5753 return true;
5754}
Ted Kremenek5739de72010-01-29 01:06:55 +00005755
Tom Careb49ec692010-06-17 19:00:27 +00005756void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00005757 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005758 const analyze_printf::OptionalAmount &Amt,
5759 unsigned type,
5760 const char *startSpecifier,
5761 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005762 const analyze_printf::PrintfConversionSpecifier &CS =
5763 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00005764
Richard Trieu03cf7b72011-10-28 00:41:25 +00005765 FixItHint fixit =
5766 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
5767 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
5768 Amt.getConstantLength()))
5769 : FixItHint();
5770
5771 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
5772 << type << CS.toString(),
5773 getLocationOfByte(Amt.getStart()),
5774 /*IsStringLocation*/true,
5775 getSpecifierRange(startSpecifier, specifierLen),
5776 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00005777}
5778
Ted Kremenek02087932010-07-16 02:11:22 +00005779void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005780 const analyze_printf::OptionalFlag &flag,
5781 const char *startSpecifier,
5782 unsigned specifierLen) {
5783 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005784 const analyze_printf::PrintfConversionSpecifier &CS =
5785 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00005786 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
5787 << flag.toString() << CS.toString(),
5788 getLocationOfByte(flag.getPosition()),
5789 /*IsStringLocation*/true,
5790 getSpecifierRange(startSpecifier, specifierLen),
5791 FixItHint::CreateRemoval(
5792 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00005793}
5794
5795void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00005796 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005797 const analyze_printf::OptionalFlag &ignoredFlag,
5798 const analyze_printf::OptionalFlag &flag,
5799 const char *startSpecifier,
5800 unsigned specifierLen) {
5801 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00005802 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
5803 << ignoredFlag.toString() << flag.toString(),
5804 getLocationOfByte(ignoredFlag.getPosition()),
5805 /*IsStringLocation*/true,
5806 getSpecifierRange(startSpecifier, specifierLen),
5807 FixItHint::CreateRemoval(
5808 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00005809}
5810
Ted Kremenek2b417712015-07-02 05:39:16 +00005811// void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5812// bool IsStringLocation, Range StringRange,
5813// ArrayRef<FixItHint> Fixit = None);
5814
5815void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
5816 unsigned flagLen) {
5817 // Warn about an empty flag.
5818 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
5819 getLocationOfByte(startFlag),
5820 /*IsStringLocation*/true,
5821 getSpecifierRange(startFlag, flagLen));
5822}
5823
5824void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
5825 unsigned flagLen) {
5826 // Warn about an invalid flag.
5827 auto Range = getSpecifierRange(startFlag, flagLen);
5828 StringRef flag(startFlag, flagLen);
5829 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
5830 getLocationOfByte(startFlag),
5831 /*IsStringLocation*/true,
5832 Range, FixItHint::CreateRemoval(Range));
5833}
5834
5835void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
5836 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
5837 // Warn about using '[...]' without a '@' conversion.
5838 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
5839 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
5840 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
5841 getLocationOfByte(conversionPosition),
5842 /*IsStringLocation*/true,
5843 Range, FixItHint::CreateRemoval(Range));
5844}
5845
Richard Smith55ce3522012-06-25 20:30:08 +00005846// Determines if the specified is a C++ class or struct containing
5847// a member with the specified name and kind (e.g. a CXXMethodDecl named
5848// "c_str()").
5849template<typename MemberKind>
5850static llvm::SmallPtrSet<MemberKind*, 1>
5851CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
5852 const RecordType *RT = Ty->getAs<RecordType>();
5853 llvm::SmallPtrSet<MemberKind*, 1> Results;
5854
5855 if (!RT)
5856 return Results;
5857 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00005858 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00005859 return Results;
5860
Alp Tokerb6cc5922014-05-03 03:45:55 +00005861 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00005862 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00005863 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00005864
5865 // We just need to include all members of the right kind turned up by the
5866 // filter, at this point.
5867 if (S.LookupQualifiedName(R, RT->getDecl()))
5868 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
5869 NamedDecl *decl = (*I)->getUnderlyingDecl();
5870 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
5871 Results.insert(FK);
5872 }
5873 return Results;
5874}
5875
Richard Smith2868a732014-02-28 01:36:39 +00005876/// Check if we could call '.c_str()' on an object.
5877///
5878/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
5879/// allow the call, or if it would be ambiguous).
5880bool Sema::hasCStrMethod(const Expr *E) {
5881 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5882 MethodSet Results =
5883 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
5884 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5885 MI != ME; ++MI)
5886 if ((*MI)->getMinRequiredArguments() == 0)
5887 return true;
5888 return false;
5889}
5890
Richard Smith55ce3522012-06-25 20:30:08 +00005891// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005892// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00005893// Returns true when a c_str() conversion method is found.
5894bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00005895 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00005896 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5897
5898 MethodSet Results =
5899 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
5900
5901 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5902 MI != ME; ++MI) {
5903 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00005904 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00005905 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00005906 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00005907 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00005908 S.Diag(E->getLocStart(), diag::note_printf_c_str)
5909 << "c_str()"
5910 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
5911 return true;
5912 }
5913 }
5914
5915 return false;
5916}
5917
Ted Kremenekab278de2010-01-28 23:39:18 +00005918bool
Ted Kremenek02087932010-07-16 02:11:22 +00005919CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00005920 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00005921 const char *startSpecifier,
5922 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005923 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00005924 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005925 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00005926
Ted Kremenek6cd69422010-07-19 22:01:06 +00005927 if (FS.consumesDataArgument()) {
5928 if (atFirstArg) {
5929 atFirstArg = false;
5930 usesPositionalArgs = FS.usesPositionalArg();
5931 }
5932 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005933 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
5934 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00005935 return false;
5936 }
Ted Kremenek5739de72010-01-29 01:06:55 +00005937 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005938
Ted Kremenekd1668192010-02-27 01:41:03 +00005939 // First check if the field width, precision, and conversion specifier
5940 // have matching data arguments.
5941 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
5942 startSpecifier, specifierLen)) {
5943 return false;
5944 }
5945
5946 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
5947 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00005948 return false;
5949 }
5950
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005951 if (!CS.consumesDataArgument()) {
5952 // FIXME: Technically specifying a precision or field width here
5953 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00005954 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005955 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005956
Ted Kremenek4a49d982010-02-26 19:18:41 +00005957 // Consume the argument.
5958 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00005959 if (argIndex < NumDataArgs) {
5960 // The check to see if the argIndex is valid will come later.
5961 // We set the bit here because we may exit early from this
5962 // function if we encounter some other error.
5963 CoveredArgs.set(argIndex);
5964 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00005965
Dimitry Andric6b5ed342015-02-19 22:32:33 +00005966 // FreeBSD kernel extensions.
5967 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
5968 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
5969 // We need at least two arguments.
5970 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
5971 return false;
5972
5973 // Claim the second argument.
5974 CoveredArgs.set(argIndex + 1);
5975
5976 // Type check the first argument (int for %b, pointer for %D)
5977 const Expr *Ex = getDataArg(argIndex);
5978 const analyze_printf::ArgType &AT =
5979 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
5980 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
5981 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
5982 EmitFormatDiagnostic(
5983 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5984 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
5985 << false << Ex->getSourceRange(),
5986 Ex->getLocStart(), /*IsStringLocation*/false,
5987 getSpecifierRange(startSpecifier, specifierLen));
5988
5989 // Type check the second argument (char * for both %b and %D)
5990 Ex = getDataArg(argIndex + 1);
5991 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
5992 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
5993 EmitFormatDiagnostic(
5994 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5995 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
5996 << false << Ex->getSourceRange(),
5997 Ex->getLocStart(), /*IsStringLocation*/false,
5998 getSpecifierRange(startSpecifier, specifierLen));
5999
6000 return true;
6001 }
6002
Ted Kremenek4a49d982010-02-26 19:18:41 +00006003 // Check for using an Objective-C specific conversion specifier
6004 // in a non-ObjC literal.
Mehdi Amini06d367c2016-10-24 20:39:34 +00006005 if (!allowsObjCArg() && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00006006 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6007 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00006008 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006009
Mehdi Amini06d367c2016-10-24 20:39:34 +00006010 // %P can only be used with os_log.
6011 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
6012 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6013 specifierLen);
6014 }
6015
6016 // %n is not allowed with os_log.
6017 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
6018 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
6019 getLocationOfByte(CS.getStart()),
6020 /*IsStringLocation*/ false,
6021 getSpecifierRange(startSpecifier, specifierLen));
6022
6023 return true;
6024 }
6025
6026 // Only scalars are allowed for os_trace.
6027 if (FSType == Sema::FST_OSTrace &&
6028 (CS.getKind() == ConversionSpecifier::PArg ||
6029 CS.getKind() == ConversionSpecifier::sArg ||
6030 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
6031 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6032 specifierLen);
6033 }
6034
6035 // Check for use of public/private annotation outside of os_log().
6036 if (FSType != Sema::FST_OSLog) {
6037 if (FS.isPublic().isSet()) {
6038 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
6039 << "public",
6040 getLocationOfByte(FS.isPublic().getPosition()),
6041 /*IsStringLocation*/ false,
6042 getSpecifierRange(startSpecifier, specifierLen));
6043 }
6044 if (FS.isPrivate().isSet()) {
6045 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
6046 << "private",
6047 getLocationOfByte(FS.isPrivate().getPosition()),
6048 /*IsStringLocation*/ false,
6049 getSpecifierRange(startSpecifier, specifierLen));
6050 }
6051 }
6052
Tom Careb49ec692010-06-17 19:00:27 +00006053 // Check for invalid use of field width
6054 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00006055 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00006056 startSpecifier, specifierLen);
6057 }
6058
6059 // Check for invalid use of precision
6060 if (!FS.hasValidPrecision()) {
6061 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
6062 startSpecifier, specifierLen);
6063 }
6064
Mehdi Amini06d367c2016-10-24 20:39:34 +00006065 // Precision is mandatory for %P specifier.
6066 if (CS.getKind() == ConversionSpecifier::PArg &&
6067 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
6068 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
6069 getLocationOfByte(startSpecifier),
6070 /*IsStringLocation*/ false,
6071 getSpecifierRange(startSpecifier, specifierLen));
6072 }
6073
Tom Careb49ec692010-06-17 19:00:27 +00006074 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00006075 if (!FS.hasValidThousandsGroupingPrefix())
6076 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00006077 if (!FS.hasValidLeadingZeros())
6078 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
6079 if (!FS.hasValidPlusPrefix())
6080 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00006081 if (!FS.hasValidSpacePrefix())
6082 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00006083 if (!FS.hasValidAlternativeForm())
6084 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
6085 if (!FS.hasValidLeftJustified())
6086 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
6087
6088 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00006089 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
6090 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
6091 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00006092 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
6093 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
6094 startSpecifier, specifierLen);
6095
6096 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00006097 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00006098 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6099 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00006100 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006101 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00006102 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006103 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6104 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00006105
Jordan Rose92303592012-09-08 04:00:03 +00006106 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6107 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6108
Ted Kremenek9fcd8302010-01-29 01:43:31 +00006109 // The remaining checks depend on the data arguments.
6110 if (HasVAListArg)
6111 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006112
Ted Kremenek6adb7e32010-07-26 19:45:42 +00006113 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00006114 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006115
Jordan Rose58bbe422012-07-19 18:10:08 +00006116 const Expr *Arg = getDataArg(argIndex);
6117 if (!Arg)
6118 return true;
6119
6120 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00006121}
6122
Jordan Roseaee34382012-09-05 22:56:26 +00006123static bool requiresParensToAddCast(const Expr *E) {
6124 // FIXME: We should have a general way to reason about operator
6125 // precedence and whether parens are actually needed here.
6126 // Take care of a few common cases where they aren't.
6127 const Expr *Inside = E->IgnoreImpCasts();
6128 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
6129 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
6130
6131 switch (Inside->getStmtClass()) {
6132 case Stmt::ArraySubscriptExprClass:
6133 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006134 case Stmt::CharacterLiteralClass:
6135 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006136 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006137 case Stmt::FloatingLiteralClass:
6138 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006139 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006140 case Stmt::ObjCArrayLiteralClass:
6141 case Stmt::ObjCBoolLiteralExprClass:
6142 case Stmt::ObjCBoxedExprClass:
6143 case Stmt::ObjCDictionaryLiteralClass:
6144 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006145 case Stmt::ObjCIvarRefExprClass:
6146 case Stmt::ObjCMessageExprClass:
6147 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006148 case Stmt::ObjCStringLiteralClass:
6149 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006150 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006151 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006152 case Stmt::UnaryOperatorClass:
6153 return false;
6154 default:
6155 return true;
6156 }
6157}
6158
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006159static std::pair<QualType, StringRef>
6160shouldNotPrintDirectly(const ASTContext &Context,
6161 QualType IntendedTy,
6162 const Expr *E) {
6163 // Use a 'while' to peel off layers of typedefs.
6164 QualType TyTy = IntendedTy;
6165 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
6166 StringRef Name = UserTy->getDecl()->getName();
6167 QualType CastTy = llvm::StringSwitch<QualType>(Name)
Alexander Shaposhnikov62351372017-06-26 23:02:27 +00006168 .Case("CFIndex", Context.LongTy)
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006169 .Case("NSInteger", Context.LongTy)
6170 .Case("NSUInteger", Context.UnsignedLongTy)
6171 .Case("SInt32", Context.IntTy)
6172 .Case("UInt32", Context.UnsignedIntTy)
6173 .Default(QualType());
6174
6175 if (!CastTy.isNull())
6176 return std::make_pair(CastTy, Name);
6177
6178 TyTy = UserTy->desugar();
6179 }
6180
6181 // Strip parens if necessary.
6182 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
6183 return shouldNotPrintDirectly(Context,
6184 PE->getSubExpr()->getType(),
6185 PE->getSubExpr());
6186
6187 // If this is a conditional expression, then its result type is constructed
6188 // via usual arithmetic conversions and thus there might be no necessary
6189 // typedef sugar there. Recurse to operands to check for NSInteger &
6190 // Co. usage condition.
6191 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
6192 QualType TrueTy, FalseTy;
6193 StringRef TrueName, FalseName;
6194
6195 std::tie(TrueTy, TrueName) =
6196 shouldNotPrintDirectly(Context,
6197 CO->getTrueExpr()->getType(),
6198 CO->getTrueExpr());
6199 std::tie(FalseTy, FalseName) =
6200 shouldNotPrintDirectly(Context,
6201 CO->getFalseExpr()->getType(),
6202 CO->getFalseExpr());
6203
6204 if (TrueTy == FalseTy)
6205 return std::make_pair(TrueTy, TrueName);
6206 else if (TrueTy.isNull())
6207 return std::make_pair(FalseTy, FalseName);
6208 else if (FalseTy.isNull())
6209 return std::make_pair(TrueTy, TrueName);
6210 }
6211
6212 return std::make_pair(QualType(), StringRef());
6213}
6214
Richard Smith55ce3522012-06-25 20:30:08 +00006215bool
6216CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
6217 const char *StartSpecifier,
6218 unsigned SpecifierLen,
6219 const Expr *E) {
6220 using namespace analyze_format_string;
6221 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006222 // Now type check the data expression that matches the
6223 // format specifier.
Mehdi Amini06d367c2016-10-24 20:39:34 +00006224 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
Jordan Rose22b74712012-09-05 22:56:19 +00006225 if (!AT.isValid())
6226 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00006227
Jordan Rose598ec092012-12-05 18:44:40 +00006228 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00006229 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
6230 ExprTy = TET->getUnderlyingExpr()->getType();
6231 }
6232
Seth Cantrellb4802962015-03-04 03:12:10 +00006233 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
6234
6235 if (match == analyze_printf::ArgType::Match) {
Jordan Rose22b74712012-09-05 22:56:19 +00006236 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00006237 }
Jordan Rose98709982012-06-04 22:48:57 +00006238
Jordan Rose22b74712012-09-05 22:56:19 +00006239 // Look through argument promotions for our error message's reported type.
6240 // This includes the integral and floating promotions, but excludes array
6241 // and function pointer decay; seeing that an argument intended to be a
6242 // string has type 'char [6]' is probably more confusing than 'char *'.
6243 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6244 if (ICE->getCastKind() == CK_IntegralCast ||
6245 ICE->getCastKind() == CK_FloatingCast) {
6246 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00006247 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00006248
6249 // Check if we didn't match because of an implicit cast from a 'char'
6250 // or 'short' to an 'int'. This is done because printf is a varargs
6251 // function.
6252 if (ICE->getType() == S.Context.IntTy ||
6253 ICE->getType() == S.Context.UnsignedIntTy) {
6254 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00006255 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00006256 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00006257 }
Jordan Rose98709982012-06-04 22:48:57 +00006258 }
Jordan Rose598ec092012-12-05 18:44:40 +00006259 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
6260 // Special case for 'a', which has type 'int' in C.
6261 // Note, however, that we do /not/ want to treat multibyte constants like
6262 // 'MooV' as characters! This form is deprecated but still exists.
6263 if (ExprTy == S.Context.IntTy)
6264 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
6265 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00006266 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006267
Jordan Rosebc53ed12014-05-31 04:12:14 +00006268 // Look through enums to their underlying type.
6269 bool IsEnum = false;
6270 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
6271 ExprTy = EnumTy->getDecl()->getIntegerType();
6272 IsEnum = true;
6273 }
6274
Jordan Rose0e5badd2012-12-05 18:44:49 +00006275 // %C in an Objective-C context prints a unichar, not a wchar_t.
6276 // If the argument is an integer of some kind, believe the %C and suggest
6277 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00006278 QualType IntendedTy = ExprTy;
Mehdi Amini06d367c2016-10-24 20:39:34 +00006279 if (isObjCContext() &&
Jordan Rose0e5badd2012-12-05 18:44:49 +00006280 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
6281 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
6282 !ExprTy->isCharType()) {
6283 // 'unichar' is defined as a typedef of unsigned short, but we should
6284 // prefer using the typedef if it is visible.
6285 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00006286
6287 // While we are here, check if the value is an IntegerLiteral that happens
6288 // to be within the valid range.
6289 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
6290 const llvm::APInt &V = IL->getValue();
6291 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
6292 return true;
6293 }
6294
Jordan Rose0e5badd2012-12-05 18:44:49 +00006295 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
6296 Sema::LookupOrdinaryName);
6297 if (S.LookupName(Result, S.getCurScope())) {
6298 NamedDecl *ND = Result.getFoundDecl();
6299 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
6300 if (TD->getUnderlyingType() == IntendedTy)
6301 IntendedTy = S.Context.getTypedefType(TD);
6302 }
6303 }
6304 }
6305
6306 // Special-case some of Darwin's platform-independence types by suggesting
6307 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006308 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00006309 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006310 QualType CastTy;
6311 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
6312 if (!CastTy.isNull()) {
6313 IntendedTy = CastTy;
6314 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00006315 }
6316 }
6317
Jordan Rose22b74712012-09-05 22:56:19 +00006318 // We may be able to offer a FixItHint if it is a supported type.
6319 PrintfSpecifier fixedFS = FS;
Mehdi Amini06d367c2016-10-24 20:39:34 +00006320 bool success =
6321 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006322
Jordan Rose22b74712012-09-05 22:56:19 +00006323 if (success) {
6324 // Get the fix string from the fixed format specifier
6325 SmallString<16> buf;
6326 llvm::raw_svector_ostream os(buf);
6327 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006328
Jordan Roseaee34382012-09-05 22:56:26 +00006329 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
6330
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006331 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Daniel Jasperad8d8492015-03-04 14:18:20 +00006332 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6333 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6334 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6335 }
Jordan Rose0e5badd2012-12-05 18:44:49 +00006336 // In this case, the specifier is wrong and should be changed to match
6337 // the argument.
Daniel Jasperad8d8492015-03-04 14:18:20 +00006338 EmitFormatDiagnostic(S.PDiag(diag)
6339 << AT.getRepresentativeTypeName(S.Context)
6340 << IntendedTy << IsEnum << E->getSourceRange(),
6341 E->getLocStart(),
6342 /*IsStringLocation*/ false, SpecRange,
6343 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00006344 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00006345 // The canonical type for formatting this value is different from the
6346 // actual type of the expression. (This occurs, for example, with Darwin's
6347 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
6348 // should be printed as 'long' for 64-bit compatibility.)
6349 // Rather than emitting a normal format/argument mismatch, we want to
6350 // add a cast to the recommended type (and correct the format string
6351 // if necessary).
6352 SmallString<16> CastBuf;
6353 llvm::raw_svector_ostream CastFix(CastBuf);
6354 CastFix << "(";
6355 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
6356 CastFix << ")";
6357
6358 SmallVector<FixItHint,4> Hints;
Alexander Shaposhnikov1788a9b2017-09-22 18:36:06 +00006359 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
Jordan Roseaee34382012-09-05 22:56:26 +00006360 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
6361
6362 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
6363 // If there's already a cast present, just replace it.
6364 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
6365 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
6366
6367 } else if (!requiresParensToAddCast(E)) {
6368 // If the expression has high enough precedence,
6369 // just write the C-style cast.
6370 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6371 CastFix.str()));
6372 } else {
6373 // Otherwise, add parens around the expression as well as the cast.
6374 CastFix << "(";
6375 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6376 CastFix.str()));
6377
Alp Tokerb6cc5922014-05-03 03:45:55 +00006378 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00006379 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
6380 }
6381
Jordan Rose0e5badd2012-12-05 18:44:49 +00006382 if (ShouldNotPrintDirectly) {
6383 // The expression has a type that should not be printed directly.
6384 // We extract the name from the typedef because we don't want to show
6385 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006386 StringRef Name;
6387 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
6388 Name = TypedefTy->getDecl()->getName();
6389 else
6390 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00006391 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00006392 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00006393 << E->getSourceRange(),
6394 E->getLocStart(), /*IsStringLocation=*/false,
6395 SpecRange, Hints);
6396 } else {
6397 // In this case, the expression could be printed using a different
6398 // specifier, but we've decided that the specifier is probably correct
6399 // and we should cast instead. Just use the normal warning message.
6400 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00006401 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6402 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00006403 << E->getSourceRange(),
6404 E->getLocStart(), /*IsStringLocation*/false,
6405 SpecRange, Hints);
6406 }
Jordan Roseaee34382012-09-05 22:56:26 +00006407 }
Jordan Rose22b74712012-09-05 22:56:19 +00006408 } else {
6409 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
6410 SpecifierLen);
6411 // Since the warning for passing non-POD types to variadic functions
6412 // was deferred until now, we emit a warning for non-POD
6413 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00006414 switch (S.isValidVarArgType(ExprTy)) {
6415 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00006416 case Sema::VAK_ValidInCXX11: {
6417 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6418 if (match == analyze_printf::ArgType::NoMatchPedantic) {
6419 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6420 }
Richard Smithd7293d72013-08-05 18:49:43 +00006421
Seth Cantrellb4802962015-03-04 03:12:10 +00006422 EmitFormatDiagnostic(
6423 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
6424 << IsEnum << CSR << E->getSourceRange(),
6425 E->getLocStart(), /*IsStringLocation*/ false, CSR);
6426 break;
6427 }
Richard Smithd7293d72013-08-05 18:49:43 +00006428 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00006429 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00006430 EmitFormatDiagnostic(
6431 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006432 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00006433 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00006434 << CallType
6435 << AT.getRepresentativeTypeName(S.Context)
6436 << CSR
6437 << E->getSourceRange(),
6438 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00006439 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00006440 break;
6441
6442 case Sema::VAK_Invalid:
6443 if (ExprTy->isObjCObjectType())
6444 EmitFormatDiagnostic(
6445 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
6446 << S.getLangOpts().CPlusPlus11
6447 << ExprTy
6448 << CallType
6449 << AT.getRepresentativeTypeName(S.Context)
6450 << CSR
6451 << E->getSourceRange(),
6452 E->getLocStart(), /*IsStringLocation*/false, CSR);
6453 else
6454 // FIXME: If this is an initializer list, suggest removing the braces
6455 // or inserting a cast to the target type.
6456 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
6457 << isa<InitListExpr>(E) << ExprTy << CallType
6458 << AT.getRepresentativeTypeName(S.Context)
6459 << E->getSourceRange();
6460 break;
6461 }
6462
6463 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
6464 "format string specifier index out of range");
6465 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006466 }
6467
Ted Kremenekab278de2010-01-28 23:39:18 +00006468 return true;
6469}
6470
Ted Kremenek02087932010-07-16 02:11:22 +00006471//===--- CHECK: Scanf format string checking ------------------------------===//
6472
6473namespace {
6474class CheckScanfHandler : public CheckFormatHandler {
6475public:
Stephen Hines648c3692016-09-16 01:07:04 +00006476 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00006477 const Expr *origFormatExpr, Sema::FormatStringType type,
6478 unsigned firstDataArg, unsigned numDataArgs,
6479 const char *beg, bool hasVAListArg,
6480 ArrayRef<const Expr *> Args, unsigned formatIdx,
6481 bool inFunctionCall, Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006482 llvm::SmallBitVector &CheckedVarArgs,
6483 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00006484 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
6485 numDataArgs, beg, hasVAListArg, Args, formatIdx,
6486 inFunctionCall, CallType, CheckedVarArgs,
6487 UncoveredArg) {}
6488
Ted Kremenek02087932010-07-16 02:11:22 +00006489 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
6490 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006491 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00006492
6493 bool HandleInvalidScanfConversionSpecifier(
6494 const analyze_scanf::ScanfSpecifier &FS,
6495 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006496 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006497
Craig Toppere14c0f82014-03-12 04:55:44 +00006498 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00006499};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006500} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00006501
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006502void CheckScanfHandler::HandleIncompleteScanList(const char *start,
6503 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006504 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
6505 getLocationOfByte(end), /*IsStringLocation*/true,
6506 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006507}
6508
Ted Kremenekce815422010-07-19 21:25:57 +00006509bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
6510 const analyze_scanf::ScanfSpecifier &FS,
6511 const char *startSpecifier,
6512 unsigned specifierLen) {
6513
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006514 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00006515 FS.getConversionSpecifier();
6516
6517 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
6518 getLocationOfByte(CS.getStart()),
6519 startSpecifier, specifierLen,
6520 CS.getStart(), CS.getLength());
6521}
6522
Ted Kremenek02087932010-07-16 02:11:22 +00006523bool CheckScanfHandler::HandleScanfSpecifier(
6524 const analyze_scanf::ScanfSpecifier &FS,
6525 const char *startSpecifier,
6526 unsigned specifierLen) {
Ted Kremenek02087932010-07-16 02:11:22 +00006527 using namespace analyze_scanf;
6528 using namespace analyze_format_string;
6529
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006530 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00006531
Ted Kremenek6cd69422010-07-19 22:01:06 +00006532 // Handle case where '%' and '*' don't consume an argument. These shouldn't
6533 // be used to decide if we are using positional arguments consistently.
6534 if (FS.consumesDataArgument()) {
6535 if (atFirstArg) {
6536 atFirstArg = false;
6537 usesPositionalArgs = FS.usesPositionalArg();
6538 }
6539 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006540 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
6541 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00006542 return false;
6543 }
Ted Kremenek02087932010-07-16 02:11:22 +00006544 }
6545
6546 // Check if the field with is non-zero.
6547 const OptionalAmount &Amt = FS.getFieldWidth();
6548 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
6549 if (Amt.getConstantAmount() == 0) {
6550 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
6551 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00006552 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
6553 getLocationOfByte(Amt.getStart()),
6554 /*IsStringLocation*/true, R,
6555 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00006556 }
6557 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006558
Ted Kremenek02087932010-07-16 02:11:22 +00006559 if (!FS.consumesDataArgument()) {
6560 // FIXME: Technically specifying a precision or field width here
6561 // makes no sense. Worth issuing a warning at some point.
6562 return true;
6563 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006564
Ted Kremenek02087932010-07-16 02:11:22 +00006565 // Consume the argument.
6566 unsigned argIndex = FS.getArgIndex();
6567 if (argIndex < NumDataArgs) {
6568 // The check to see if the argIndex is valid will come later.
6569 // We set the bit here because we may exit early from this
6570 // function if we encounter some other error.
6571 CoveredArgs.set(argIndex);
6572 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006573
Ted Kremenek4407ea42010-07-20 20:04:47 +00006574 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00006575 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00006576 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6577 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00006578 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006579 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00006580 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006581 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6582 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00006583
Jordan Rose92303592012-09-08 04:00:03 +00006584 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6585 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6586
Ted Kremenek02087932010-07-16 02:11:22 +00006587 // The remaining checks depend on the data arguments.
6588 if (HasVAListArg)
6589 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00006590
Ted Kremenek6adb7e32010-07-26 19:45:42 +00006591 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00006592 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00006593
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006594 // Check that the argument type matches the format specifier.
6595 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00006596 if (!Ex)
6597 return true;
6598
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00006599 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00006600
6601 if (!AT.isValid()) {
6602 return true;
6603 }
6604
Seth Cantrellb4802962015-03-04 03:12:10 +00006605 analyze_format_string::ArgType::MatchKind match =
6606 AT.matchesType(S.Context, Ex->getType());
Seth Cantrell79340072015-03-04 05:58:08 +00006607 if (match == analyze_format_string::ArgType::Match) {
6608 return true;
6609 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006610
Seth Cantrell79340072015-03-04 05:58:08 +00006611 ScanfSpecifier fixedFS = FS;
6612 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
6613 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006614
Seth Cantrell79340072015-03-04 05:58:08 +00006615 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6616 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6617 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6618 }
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006619
Seth Cantrell79340072015-03-04 05:58:08 +00006620 if (success) {
6621 // Get the fix string from the fixed format specifier.
6622 SmallString<128> buf;
6623 llvm::raw_svector_ostream os(buf);
6624 fixedFS.toString(os);
6625
6626 EmitFormatDiagnostic(
6627 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
6628 << Ex->getType() << false << Ex->getSourceRange(),
6629 Ex->getLocStart(),
6630 /*IsStringLocation*/ false,
6631 getSpecifierRange(startSpecifier, specifierLen),
6632 FixItHint::CreateReplacement(
6633 getSpecifierRange(startSpecifier, specifierLen), os.str()));
6634 } else {
6635 EmitFormatDiagnostic(S.PDiag(diag)
6636 << AT.getRepresentativeTypeName(S.Context)
6637 << Ex->getType() << false << Ex->getSourceRange(),
6638 Ex->getLocStart(),
6639 /*IsStringLocation*/ false,
6640 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006641 }
6642
Ted Kremenek02087932010-07-16 02:11:22 +00006643 return true;
6644}
6645
Stephen Hines648c3692016-09-16 01:07:04 +00006646static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006647 const Expr *OrigFormatExpr,
6648 ArrayRef<const Expr *> Args,
6649 bool HasVAListArg, unsigned format_idx,
6650 unsigned firstDataArg,
6651 Sema::FormatStringType Type,
6652 bool inFunctionCall,
6653 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006654 llvm::SmallBitVector &CheckedVarArgs,
6655 UncoveredArgHandler &UncoveredArg) {
Ted Kremenekab278de2010-01-28 23:39:18 +00006656 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00006657 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006658 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006659 S, inFunctionCall, Args[format_idx],
6660 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00006661 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00006662 return;
6663 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006664
Ted Kremenekab278de2010-01-28 23:39:18 +00006665 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006666 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00006667 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006668 // Account for cases where the string literal is truncated in a declaration.
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006669 const ConstantArrayType *T =
6670 S.Context.getAsConstantArrayType(FExpr->getType());
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006671 assert(T && "String literal not of constant array type!");
6672 size_t TypeSize = T->getSize().getZExtValue();
6673 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00006674 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006675
6676 // Emit a warning if the string literal is truncated and does not contain an
6677 // embedded null character.
6678 if (TypeSize <= StrRef.size() &&
6679 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
6680 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006681 S, inFunctionCall, Args[format_idx],
6682 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006683 FExpr->getLocStart(),
6684 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
6685 return;
6686 }
6687
Ted Kremenekab278de2010-01-28 23:39:18 +00006688 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00006689 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006690 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006691 S, inFunctionCall, Args[format_idx],
6692 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00006693 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00006694 return;
6695 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006696
6697 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
Mehdi Amini06d367c2016-10-24 20:39:34 +00006698 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
6699 Type == Sema::FST_OSTrace) {
6700 CheckPrintfHandler H(
6701 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
6702 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
6703 HasVAListArg, Args, format_idx, inFunctionCall, CallType,
6704 CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006705
Hans Wennborg23926bd2011-12-15 10:25:47 +00006706 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006707 S.getLangOpts(),
6708 S.Context.getTargetInfo(),
6709 Type == Sema::FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00006710 H.DoneProcessing();
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006711 } else if (Type == Sema::FST_Scanf) {
Mehdi Amini06d367c2016-10-24 20:39:34 +00006712 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
6713 numDataArgs, Str, HasVAListArg, Args, format_idx,
6714 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006715
Hans Wennborg23926bd2011-12-15 10:25:47 +00006716 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006717 S.getLangOpts(),
6718 S.Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00006719 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00006720 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00006721}
6722
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00006723bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
6724 // Str - The format string. NOTE: this is NOT null-terminated!
6725 StringRef StrRef = FExpr->getString();
6726 const char *Str = StrRef.data();
6727 // Account for cases where the string literal is truncated in a declaration.
6728 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
6729 assert(T && "String literal not of constant array type!");
6730 size_t TypeSize = T->getSize().getZExtValue();
6731 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
6732 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
6733 getLangOpts(),
6734 Context.getTargetInfo());
6735}
6736
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006737//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
6738
6739// Returns the related absolute value function that is larger, of 0 if one
6740// does not exist.
6741static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
6742 switch (AbsFunction) {
6743 default:
6744 return 0;
6745
6746 case Builtin::BI__builtin_abs:
6747 return Builtin::BI__builtin_labs;
6748 case Builtin::BI__builtin_labs:
6749 return Builtin::BI__builtin_llabs;
6750 case Builtin::BI__builtin_llabs:
6751 return 0;
6752
6753 case Builtin::BI__builtin_fabsf:
6754 return Builtin::BI__builtin_fabs;
6755 case Builtin::BI__builtin_fabs:
6756 return Builtin::BI__builtin_fabsl;
6757 case Builtin::BI__builtin_fabsl:
6758 return 0;
6759
6760 case Builtin::BI__builtin_cabsf:
6761 return Builtin::BI__builtin_cabs;
6762 case Builtin::BI__builtin_cabs:
6763 return Builtin::BI__builtin_cabsl;
6764 case Builtin::BI__builtin_cabsl:
6765 return 0;
6766
6767 case Builtin::BIabs:
6768 return Builtin::BIlabs;
6769 case Builtin::BIlabs:
6770 return Builtin::BIllabs;
6771 case Builtin::BIllabs:
6772 return 0;
6773
6774 case Builtin::BIfabsf:
6775 return Builtin::BIfabs;
6776 case Builtin::BIfabs:
6777 return Builtin::BIfabsl;
6778 case Builtin::BIfabsl:
6779 return 0;
6780
6781 case Builtin::BIcabsf:
6782 return Builtin::BIcabs;
6783 case Builtin::BIcabs:
6784 return Builtin::BIcabsl;
6785 case Builtin::BIcabsl:
6786 return 0;
6787 }
6788}
6789
6790// Returns the argument type of the absolute value function.
6791static QualType getAbsoluteValueArgumentType(ASTContext &Context,
6792 unsigned AbsType) {
6793 if (AbsType == 0)
6794 return QualType();
6795
6796 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
6797 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
6798 if (Error != ASTContext::GE_None)
6799 return QualType();
6800
6801 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
6802 if (!FT)
6803 return QualType();
6804
6805 if (FT->getNumParams() != 1)
6806 return QualType();
6807
6808 return FT->getParamType(0);
6809}
6810
6811// Returns the best absolute value function, or zero, based on type and
6812// current absolute value function.
6813static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
6814 unsigned AbsFunctionKind) {
6815 unsigned BestKind = 0;
6816 uint64_t ArgSize = Context.getTypeSize(ArgType);
6817 for (unsigned Kind = AbsFunctionKind; Kind != 0;
6818 Kind = getLargerAbsoluteValueFunction(Kind)) {
6819 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
6820 if (Context.getTypeSize(ParamType) >= ArgSize) {
6821 if (BestKind == 0)
6822 BestKind = Kind;
6823 else if (Context.hasSameType(ParamType, ArgType)) {
6824 BestKind = Kind;
6825 break;
6826 }
6827 }
6828 }
6829 return BestKind;
6830}
6831
6832enum AbsoluteValueKind {
6833 AVK_Integer,
6834 AVK_Floating,
6835 AVK_Complex
6836};
6837
6838static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
6839 if (T->isIntegralOrEnumerationType())
6840 return AVK_Integer;
6841 if (T->isRealFloatingType())
6842 return AVK_Floating;
6843 if (T->isAnyComplexType())
6844 return AVK_Complex;
6845
6846 llvm_unreachable("Type not integer, floating, or complex");
6847}
6848
6849// Changes the absolute value function to a different type. Preserves whether
6850// the function is a builtin.
6851static unsigned changeAbsFunction(unsigned AbsKind,
6852 AbsoluteValueKind ValueKind) {
6853 switch (ValueKind) {
6854 case AVK_Integer:
6855 switch (AbsKind) {
6856 default:
6857 return 0;
6858 case Builtin::BI__builtin_fabsf:
6859 case Builtin::BI__builtin_fabs:
6860 case Builtin::BI__builtin_fabsl:
6861 case Builtin::BI__builtin_cabsf:
6862 case Builtin::BI__builtin_cabs:
6863 case Builtin::BI__builtin_cabsl:
6864 return Builtin::BI__builtin_abs;
6865 case Builtin::BIfabsf:
6866 case Builtin::BIfabs:
6867 case Builtin::BIfabsl:
6868 case Builtin::BIcabsf:
6869 case Builtin::BIcabs:
6870 case Builtin::BIcabsl:
6871 return Builtin::BIabs;
6872 }
6873 case AVK_Floating:
6874 switch (AbsKind) {
6875 default:
6876 return 0;
6877 case Builtin::BI__builtin_abs:
6878 case Builtin::BI__builtin_labs:
6879 case Builtin::BI__builtin_llabs:
6880 case Builtin::BI__builtin_cabsf:
6881 case Builtin::BI__builtin_cabs:
6882 case Builtin::BI__builtin_cabsl:
6883 return Builtin::BI__builtin_fabsf;
6884 case Builtin::BIabs:
6885 case Builtin::BIlabs:
6886 case Builtin::BIllabs:
6887 case Builtin::BIcabsf:
6888 case Builtin::BIcabs:
6889 case Builtin::BIcabsl:
6890 return Builtin::BIfabsf;
6891 }
6892 case AVK_Complex:
6893 switch (AbsKind) {
6894 default:
6895 return 0;
6896 case Builtin::BI__builtin_abs:
6897 case Builtin::BI__builtin_labs:
6898 case Builtin::BI__builtin_llabs:
6899 case Builtin::BI__builtin_fabsf:
6900 case Builtin::BI__builtin_fabs:
6901 case Builtin::BI__builtin_fabsl:
6902 return Builtin::BI__builtin_cabsf;
6903 case Builtin::BIabs:
6904 case Builtin::BIlabs:
6905 case Builtin::BIllabs:
6906 case Builtin::BIfabsf:
6907 case Builtin::BIfabs:
6908 case Builtin::BIfabsl:
6909 return Builtin::BIcabsf;
6910 }
6911 }
6912 llvm_unreachable("Unable to convert function");
6913}
6914
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00006915static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006916 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
6917 if (!FnInfo)
6918 return 0;
6919
6920 switch (FDecl->getBuiltinID()) {
6921 default:
6922 return 0;
6923 case Builtin::BI__builtin_abs:
6924 case Builtin::BI__builtin_fabs:
6925 case Builtin::BI__builtin_fabsf:
6926 case Builtin::BI__builtin_fabsl:
6927 case Builtin::BI__builtin_labs:
6928 case Builtin::BI__builtin_llabs:
6929 case Builtin::BI__builtin_cabs:
6930 case Builtin::BI__builtin_cabsf:
6931 case Builtin::BI__builtin_cabsl:
6932 case Builtin::BIabs:
6933 case Builtin::BIlabs:
6934 case Builtin::BIllabs:
6935 case Builtin::BIfabs:
6936 case Builtin::BIfabsf:
6937 case Builtin::BIfabsl:
6938 case Builtin::BIcabs:
6939 case Builtin::BIcabsf:
6940 case Builtin::BIcabsl:
6941 return FDecl->getBuiltinID();
6942 }
6943 llvm_unreachable("Unknown Builtin type");
6944}
6945
6946// If the replacement is valid, emit a note with replacement function.
6947// Additionally, suggest including the proper header if not already included.
6948static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00006949 unsigned AbsKind, QualType ArgType) {
6950 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00006951 const char *HeaderName = nullptr;
Mehdi Amini7186a432016-10-11 19:04:24 +00006952 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00006953 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
6954 FunctionName = "std::abs";
6955 if (ArgType->isIntegralOrEnumerationType()) {
6956 HeaderName = "cstdlib";
6957 } else if (ArgType->isRealFloatingType()) {
6958 HeaderName = "cmath";
6959 } else {
6960 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006961 }
Richard Trieubeffb832014-04-15 23:47:53 +00006962
6963 // Lookup all std::abs
6964 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00006965 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00006966 R.suppressDiagnostics();
6967 S.LookupQualifiedName(R, Std);
6968
6969 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006970 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00006971 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
6972 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
6973 } else {
6974 FDecl = dyn_cast<FunctionDecl>(I);
6975 }
6976 if (!FDecl)
6977 continue;
6978
6979 // Found std::abs(), check that they are the right ones.
6980 if (FDecl->getNumParams() != 1)
6981 continue;
6982
6983 // Check that the parameter type can handle the argument.
6984 QualType ParamType = FDecl->getParamDecl(0)->getType();
6985 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
6986 S.Context.getTypeSize(ArgType) <=
6987 S.Context.getTypeSize(ParamType)) {
6988 // Found a function, don't need the header hint.
6989 EmitHeaderHint = false;
6990 break;
6991 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006992 }
Richard Trieubeffb832014-04-15 23:47:53 +00006993 }
6994 } else {
Eric Christopher02d5d862015-08-06 01:01:12 +00006995 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
Richard Trieubeffb832014-04-15 23:47:53 +00006996 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
6997
6998 if (HeaderName) {
6999 DeclarationName DN(&S.Context.Idents.get(FunctionName));
7000 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
7001 R.suppressDiagnostics();
7002 S.LookupName(R, S.getCurScope());
7003
7004 if (R.isSingleResult()) {
7005 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
7006 if (FD && FD->getBuiltinID() == AbsKind) {
7007 EmitHeaderHint = false;
7008 } else {
7009 return;
7010 }
7011 } else if (!R.empty()) {
7012 return;
7013 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007014 }
7015 }
7016
7017 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00007018 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007019
Richard Trieubeffb832014-04-15 23:47:53 +00007020 if (!HeaderName)
7021 return;
7022
7023 if (!EmitHeaderHint)
7024 return;
7025
Alp Toker5d96e0a2014-07-11 20:53:51 +00007026 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
7027 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00007028}
7029
Richard Trieua7f30b12016-12-06 01:42:28 +00007030template <std::size_t StrLen>
7031static bool IsStdFunction(const FunctionDecl *FDecl,
7032 const char (&Str)[StrLen]) {
Richard Trieubeffb832014-04-15 23:47:53 +00007033 if (!FDecl)
7034 return false;
Richard Trieua7f30b12016-12-06 01:42:28 +00007035 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
Richard Trieubeffb832014-04-15 23:47:53 +00007036 return false;
Richard Trieua7f30b12016-12-06 01:42:28 +00007037 if (!FDecl->isInStdNamespace())
Richard Trieubeffb832014-04-15 23:47:53 +00007038 return false;
7039
7040 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007041}
7042
7043// Warn when using the wrong abs() function.
7044void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
Richard Trieua7f30b12016-12-06 01:42:28 +00007045 const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007046 if (Call->getNumArgs() != 1)
7047 return;
7048
7049 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieua7f30b12016-12-06 01:42:28 +00007050 bool IsStdAbs = IsStdFunction(FDecl, "abs");
Richard Trieubeffb832014-04-15 23:47:53 +00007051 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007052 return;
7053
7054 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7055 QualType ParamType = Call->getArg(0)->getType();
7056
Alp Toker5d96e0a2014-07-11 20:53:51 +00007057 // Unsigned types cannot be negative. Suggest removing the absolute value
7058 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007059 if (ArgType->isUnsignedIntegerType()) {
Mehdi Amini7186a432016-10-11 19:04:24 +00007060 const char *FunctionName =
Eric Christopher02d5d862015-08-06 01:01:12 +00007061 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007062 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
7063 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00007064 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007065 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
7066 return;
7067 }
7068
David Majnemer7f77eb92015-11-15 03:04:34 +00007069 // Taking the absolute value of a pointer is very suspicious, they probably
7070 // wanted to index into an array, dereference a pointer, call a function, etc.
7071 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
7072 unsigned DiagType = 0;
7073 if (ArgType->isFunctionType())
7074 DiagType = 1;
7075 else if (ArgType->isArrayType())
7076 DiagType = 2;
7077
7078 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
7079 return;
7080 }
7081
Richard Trieubeffb832014-04-15 23:47:53 +00007082 // std::abs has overloads which prevent most of the absolute value problems
7083 // from occurring.
7084 if (IsStdAbs)
7085 return;
7086
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007087 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
7088 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
7089
7090 // The argument and parameter are the same kind. Check if they are the right
7091 // size.
7092 if (ArgValueKind == ParamValueKind) {
7093 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
7094 return;
7095
7096 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
7097 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
7098 << FDecl << ArgType << ParamType;
7099
7100 if (NewAbsKind == 0)
7101 return;
7102
7103 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00007104 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007105 return;
7106 }
7107
7108 // ArgValueKind != ParamValueKind
7109 // The wrong type of absolute value function was used. Attempt to find the
7110 // proper one.
7111 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
7112 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
7113 if (NewAbsKind == 0)
7114 return;
7115
7116 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
7117 << FDecl << ParamValueKind << ArgValueKind;
7118
7119 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00007120 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007121}
7122
Richard Trieu67c00712016-12-05 23:41:46 +00007123//===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
Richard Trieua7f30b12016-12-06 01:42:28 +00007124void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
7125 const FunctionDecl *FDecl) {
Richard Trieu67c00712016-12-05 23:41:46 +00007126 if (!Call || !FDecl) return;
7127
7128 // Ignore template specializations and macros.
Richard Smith51ec0cf2017-02-21 01:17:38 +00007129 if (inTemplateInstantiation()) return;
Richard Trieu67c00712016-12-05 23:41:46 +00007130 if (Call->getExprLoc().isMacroID()) return;
7131
7132 // Only care about the one template argument, two function parameter std::max
7133 if (Call->getNumArgs() != 2) return;
Richard Trieua7f30b12016-12-06 01:42:28 +00007134 if (!IsStdFunction(FDecl, "max")) return;
Richard Trieu67c00712016-12-05 23:41:46 +00007135 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
7136 if (!ArgList) return;
7137 if (ArgList->size() != 1) return;
7138
7139 // Check that template type argument is unsigned integer.
7140 const auto& TA = ArgList->get(0);
7141 if (TA.getKind() != TemplateArgument::Type) return;
7142 QualType ArgType = TA.getAsType();
7143 if (!ArgType->isUnsignedIntegerType()) return;
7144
7145 // See if either argument is a literal zero.
7146 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
7147 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
7148 if (!MTE) return false;
7149 const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
7150 if (!Num) return false;
7151 if (Num->getValue() != 0) return false;
7152 return true;
7153 };
7154
7155 const Expr *FirstArg = Call->getArg(0);
7156 const Expr *SecondArg = Call->getArg(1);
7157 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
7158 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
7159
7160 // Only warn when exactly one argument is zero.
7161 if (IsFirstArgZero == IsSecondArgZero) return;
7162
7163 SourceRange FirstRange = FirstArg->getSourceRange();
7164 SourceRange SecondRange = SecondArg->getSourceRange();
7165
7166 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
7167
7168 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
7169 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
7170
7171 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
7172 SourceRange RemovalRange;
7173 if (IsFirstArgZero) {
7174 RemovalRange = SourceRange(FirstRange.getBegin(),
7175 SecondRange.getBegin().getLocWithOffset(-1));
7176 } else {
7177 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
7178 SecondRange.getEnd());
7179 }
7180
7181 Diag(Call->getExprLoc(), diag::note_remove_max_call)
7182 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
7183 << FixItHint::CreateRemoval(RemovalRange);
7184}
7185
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007186//===--- CHECK: Standard memory functions ---------------------------------===//
7187
Nico Weber0e6daef2013-12-26 23:38:39 +00007188/// \brief Takes the expression passed to the size_t parameter of functions
7189/// such as memcmp, strncat, etc and warns if it's a comparison.
7190///
7191/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
7192static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
7193 IdentifierInfo *FnName,
7194 SourceLocation FnLoc,
7195 SourceLocation RParenLoc) {
7196 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
7197 if (!Size)
7198 return false;
7199
7200 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
7201 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
7202 return false;
7203
Nico Weber0e6daef2013-12-26 23:38:39 +00007204 SourceRange SizeRange = Size->getSourceRange();
7205 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
7206 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00007207 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00007208 << FnName << FixItHint::CreateInsertion(
7209 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00007210 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00007211 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00007212 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00007213 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
7214 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00007215
7216 return true;
7217}
7218
Reid Kleckner5fb5b122014-06-27 23:58:21 +00007219/// \brief Determine whether the given type is or contains a dynamic class type
7220/// (e.g., whether it has a vtable).
7221static const CXXRecordDecl *getContainedDynamicClass(QualType T,
7222 bool &IsContained) {
7223 // Look through array types while ignoring qualifiers.
7224 const Type *Ty = T->getBaseElementTypeUnsafe();
7225 IsContained = false;
7226
7227 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
7228 RD = RD ? RD->getDefinition() : nullptr;
Richard Trieu1c7237a2016-03-31 04:18:07 +00007229 if (!RD || RD->isInvalidDecl())
Reid Kleckner5fb5b122014-06-27 23:58:21 +00007230 return nullptr;
7231
7232 if (RD->isDynamicClass())
7233 return RD;
7234
7235 // Check all the fields. If any bases were dynamic, the class is dynamic.
7236 // It's impossible for a class to transitively contain itself by value, so
7237 // infinite recursion is impossible.
7238 for (auto *FD : RD->fields()) {
7239 bool SubContained;
7240 if (const CXXRecordDecl *ContainedRD =
7241 getContainedDynamicClass(FD->getType(), SubContained)) {
7242 IsContained = true;
7243 return ContainedRD;
7244 }
7245 }
7246
7247 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00007248}
7249
Chandler Carruth889ed862011-06-21 23:04:20 +00007250/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007251/// otherwise returns NULL.
Nico Weberc44b35e2015-03-21 17:37:46 +00007252static const Expr *getSizeOfExprArg(const Expr *E) {
Nico Weberc5e73862011-06-14 16:14:58 +00007253 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007254 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
7255 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
7256 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00007257
Craig Topperc3ec1492014-05-26 06:22:03 +00007258 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007259}
7260
Chandler Carruth889ed862011-06-21 23:04:20 +00007261/// \brief If E is a sizeof expression, returns its argument type.
Nico Weberc44b35e2015-03-21 17:37:46 +00007262static QualType getSizeOfArgType(const Expr *E) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007263 if (const UnaryExprOrTypeTraitExpr *SizeOf =
7264 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
7265 if (SizeOf->getKind() == clang::UETT_SizeOf)
7266 return SizeOf->getTypeOfArgument();
7267
7268 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00007269}
7270
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007271/// \brief Check for dangerous or invalid arguments to memset().
7272///
Chandler Carruthac687262011-06-03 06:23:57 +00007273/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007274/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
7275/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007276///
7277/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007278void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00007279 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007280 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00007281 assert(BId != 0);
7282
Ted Kremenekb5fabb22011-04-28 01:38:02 +00007283 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00007284 // we have enough arguments, and if not, abort further checking.
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007285 unsigned ExpectedNumArgs =
7286 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00007287 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00007288 return;
7289
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007290 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
Anna Zaks22122702012-01-17 00:37:07 +00007291 BId == Builtin::BIstrndup ? 1 : 2);
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007292 unsigned LenArg =
7293 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00007294 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007295
Nico Weber0e6daef2013-12-26 23:38:39 +00007296 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
7297 Call->getLocStart(), Call->getRParenLoc()))
7298 return;
7299
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007300 // We have special checking when the length is a sizeof expression.
7301 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
7302 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
7303 llvm::FoldingSetNodeID SizeOfArgID;
7304
Bruno Cardoso Lopesc73e4c32016-08-11 18:33:15 +00007305 // Although widely used, 'bzero' is not a standard function. Be more strict
7306 // with the argument types before allowing diagnostics and only allow the
7307 // form bzero(ptr, sizeof(...)).
7308 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7309 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
7310 return;
7311
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007312 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
7313 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00007314 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007315
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007316 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00007317 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007318 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00007319 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00007320
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007321 // Never warn about void type pointers. This can be used to suppress
7322 // false positives.
7323 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007324 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007325
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007326 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
7327 // actually comparing the expressions for equality. Because computing the
7328 // expression IDs can be expensive, we only do this if the diagnostic is
7329 // enabled.
7330 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007331 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
7332 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007333 // We only compute IDs for expressions if the warning is enabled, and
7334 // cache the sizeof arg's ID.
7335 if (SizeOfArgID == llvm::FoldingSetNodeID())
7336 SizeOfArg->Profile(SizeOfArgID, Context, true);
7337 llvm::FoldingSetNodeID DestID;
7338 Dest->Profile(DestID, Context, true);
7339 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00007340 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
7341 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007342 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00007343 StringRef ReadableName = FnName->getName();
7344
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007345 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00007346 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007347 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00007348 if (!PointeeTy->isIncompleteType() &&
7349 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007350 ActionIdx = 2; // If the pointee's size is sizeof(char),
7351 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00007352
7353 // If the function is defined as a builtin macro, do not show macro
7354 // expansion.
7355 SourceLocation SL = SizeOfArg->getExprLoc();
7356 SourceRange DSR = Dest->getSourceRange();
7357 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00007358 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00007359
7360 if (SM.isMacroArgExpansion(SL)) {
7361 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
7362 SL = SM.getSpellingLoc(SL);
7363 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
7364 SM.getSpellingLoc(DSR.getEnd()));
7365 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
7366 SM.getSpellingLoc(SSR.getEnd()));
7367 }
7368
Anna Zaksd08d9152012-05-30 23:14:52 +00007369 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007370 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00007371 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00007372 << PointeeTy
7373 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00007374 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00007375 << SSR);
7376 DiagRuntimeBehavior(SL, SizeOfArg,
7377 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
7378 << ActionIdx
7379 << SSR);
7380
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007381 break;
7382 }
7383 }
7384
7385 // Also check for cases where the sizeof argument is the exact same
7386 // type as the memory argument, and where it points to a user-defined
7387 // record type.
7388 if (SizeOfArgTy != QualType()) {
7389 if (PointeeTy->isRecordType() &&
7390 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
7391 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
7392 PDiag(diag::warn_sizeof_pointer_type_memaccess)
7393 << FnName << SizeOfArgTy << ArgIdx
7394 << PointeeTy << Dest->getSourceRange()
7395 << LenExpr->getSourceRange());
7396 break;
7397 }
Nico Weberc5e73862011-06-14 16:14:58 +00007398 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00007399 } else if (DestTy->isArrayType()) {
7400 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00007401 }
Nico Weberc5e73862011-06-14 16:14:58 +00007402
Nico Weberc44b35e2015-03-21 17:37:46 +00007403 if (PointeeTy == QualType())
7404 continue;
Anna Zaks22122702012-01-17 00:37:07 +00007405
Nico Weberc44b35e2015-03-21 17:37:46 +00007406 // Always complain about dynamic classes.
7407 bool IsContained;
7408 if (const CXXRecordDecl *ContainedRD =
7409 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00007410
Nico Weberc44b35e2015-03-21 17:37:46 +00007411 unsigned OperationType = 0;
7412 // "overwritten" if we're warning about the destination for any call
7413 // but memcmp; otherwise a verb appropriate to the call.
7414 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
7415 if (BId == Builtin::BImemcpy)
7416 OperationType = 1;
7417 else if(BId == Builtin::BImemmove)
7418 OperationType = 2;
7419 else if (BId == Builtin::BImemcmp)
7420 OperationType = 3;
7421 }
7422
John McCall31168b02011-06-15 23:02:42 +00007423 DiagRuntimeBehavior(
7424 Dest->getExprLoc(), Dest,
Nico Weberc44b35e2015-03-21 17:37:46 +00007425 PDiag(diag::warn_dyn_class_memaccess)
7426 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
7427 << FnName << IsContained << ContainedRD << OperationType
7428 << Call->getCallee()->getSourceRange());
7429 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
7430 BId != Builtin::BImemset)
7431 DiagRuntimeBehavior(
7432 Dest->getExprLoc(), Dest,
7433 PDiag(diag::warn_arc_object_memaccess)
7434 << ArgIdx << FnName << PointeeTy
7435 << Call->getCallee()->getSourceRange());
7436 else
7437 continue;
7438
7439 DiagRuntimeBehavior(
7440 Dest->getExprLoc(), Dest,
7441 PDiag(diag::note_bad_memaccess_silence)
7442 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
7443 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007444 }
7445}
7446
Ted Kremenek6865f772011-08-18 20:55:45 +00007447// A little helper routine: ignore addition and subtraction of integer literals.
7448// This intentionally does not ignore all integer constant expressions because
7449// we don't want to remove sizeof().
7450static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
7451 Ex = Ex->IgnoreParenCasts();
7452
7453 for (;;) {
7454 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
7455 if (!BO || !BO->isAdditiveOp())
7456 break;
7457
7458 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
7459 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
7460
7461 if (isa<IntegerLiteral>(RHS))
7462 Ex = LHS;
7463 else if (isa<IntegerLiteral>(LHS))
7464 Ex = RHS;
7465 else
7466 break;
7467 }
7468
7469 return Ex;
7470}
7471
Anna Zaks13b08572012-08-08 21:42:23 +00007472static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
7473 ASTContext &Context) {
7474 // Only handle constant-sized or VLAs, but not flexible members.
7475 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
7476 // Only issue the FIXIT for arrays of size > 1.
7477 if (CAT->getSize().getSExtValue() <= 1)
7478 return false;
7479 } else if (!Ty->isVariableArrayType()) {
7480 return false;
7481 }
7482 return true;
7483}
7484
Ted Kremenek6865f772011-08-18 20:55:45 +00007485// Warn if the user has made the 'size' argument to strlcpy or strlcat
7486// be the size of the source, instead of the destination.
7487void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
7488 IdentifierInfo *FnName) {
7489
7490 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00007491 unsigned NumArgs = Call->getNumArgs();
7492 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00007493 return;
7494
7495 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
7496 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00007497 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00007498
7499 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
7500 Call->getLocStart(), Call->getRParenLoc()))
7501 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00007502
7503 // Look for 'strlcpy(dst, x, sizeof(x))'
7504 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
7505 CompareWithSrc = Ex;
7506 else {
7507 // Look for 'strlcpy(dst, x, strlen(x))'
7508 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00007509 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
7510 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00007511 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
7512 }
7513 }
7514
7515 if (!CompareWithSrc)
7516 return;
7517
7518 // Determine if the argument to sizeof/strlen is equal to the source
7519 // argument. In principle there's all kinds of things you could do
7520 // here, for instance creating an == expression and evaluating it with
7521 // EvaluateAsBooleanCondition, but this uses a more direct technique:
7522 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
7523 if (!SrcArgDRE)
7524 return;
7525
7526 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
7527 if (!CompareWithSrcDRE ||
7528 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
7529 return;
7530
7531 const Expr *OriginalSizeArg = Call->getArg(2);
7532 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
7533 << OriginalSizeArg->getSourceRange() << FnName;
7534
7535 // Output a FIXIT hint if the destination is an array (rather than a
7536 // pointer to an array). This could be enhanced to handle some
7537 // pointers if we know the actual size, like if DstArg is 'array+2'
7538 // we could say 'sizeof(array)-2'.
7539 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00007540 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00007541 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00007542
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00007543 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00007544 llvm::raw_svector_ostream OS(sizeString);
7545 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007546 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00007547 OS << ")";
7548
7549 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
7550 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
7551 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00007552}
7553
Anna Zaks314cd092012-02-01 19:08:57 +00007554/// Check if two expressions refer to the same declaration.
7555static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
7556 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
7557 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
7558 return D1->getDecl() == D2->getDecl();
7559 return false;
7560}
7561
7562static const Expr *getStrlenExprArg(const Expr *E) {
7563 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
7564 const FunctionDecl *FD = CE->getDirectCallee();
7565 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00007566 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00007567 return CE->getArg(0)->IgnoreParenCasts();
7568 }
Craig Topperc3ec1492014-05-26 06:22:03 +00007569 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00007570}
7571
7572// Warn on anti-patterns as the 'size' argument to strncat.
7573// The correct size argument should look like following:
7574// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
7575void Sema::CheckStrncatArguments(const CallExpr *CE,
7576 IdentifierInfo *FnName) {
7577 // Don't crash if the user has the wrong number of arguments.
7578 if (CE->getNumArgs() < 3)
7579 return;
7580 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
7581 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
7582 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
7583
Nico Weber0e6daef2013-12-26 23:38:39 +00007584 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
7585 CE->getRParenLoc()))
7586 return;
7587
Anna Zaks314cd092012-02-01 19:08:57 +00007588 // Identify common expressions, which are wrongly used as the size argument
7589 // to strncat and may lead to buffer overflows.
7590 unsigned PatternType = 0;
7591 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
7592 // - sizeof(dst)
7593 if (referToTheSameDecl(SizeOfArg, DstArg))
7594 PatternType = 1;
7595 // - sizeof(src)
7596 else if (referToTheSameDecl(SizeOfArg, SrcArg))
7597 PatternType = 2;
7598 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
7599 if (BE->getOpcode() == BO_Sub) {
7600 const Expr *L = BE->getLHS()->IgnoreParenCasts();
7601 const Expr *R = BE->getRHS()->IgnoreParenCasts();
7602 // - sizeof(dst) - strlen(dst)
7603 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
7604 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
7605 PatternType = 1;
7606 // - sizeof(src) - (anything)
7607 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
7608 PatternType = 2;
7609 }
7610 }
7611
7612 if (PatternType == 0)
7613 return;
7614
Anna Zaks5069aa32012-02-03 01:27:37 +00007615 // Generate the diagnostic.
7616 SourceLocation SL = LenArg->getLocStart();
7617 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00007618 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00007619
7620 // If the function is defined as a builtin macro, do not show macro expansion.
7621 if (SM.isMacroArgExpansion(SL)) {
7622 SL = SM.getSpellingLoc(SL);
7623 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
7624 SM.getSpellingLoc(SR.getEnd()));
7625 }
7626
Anna Zaks13b08572012-08-08 21:42:23 +00007627 // Check if the destination is an array (rather than a pointer to an array).
7628 QualType DstTy = DstArg->getType();
7629 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
7630 Context);
7631 if (!isKnownSizeArray) {
7632 if (PatternType == 1)
7633 Diag(SL, diag::warn_strncat_wrong_size) << SR;
7634 else
7635 Diag(SL, diag::warn_strncat_src_size) << SR;
7636 return;
7637 }
7638
Anna Zaks314cd092012-02-01 19:08:57 +00007639 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00007640 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00007641 else
Anna Zaks5069aa32012-02-03 01:27:37 +00007642 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00007643
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00007644 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00007645 llvm::raw_svector_ostream OS(sizeString);
7646 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007647 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00007648 OS << ") - ";
7649 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007650 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00007651 OS << ") - 1";
7652
Anna Zaks5069aa32012-02-03 01:27:37 +00007653 Diag(SL, diag::note_strncat_wrong_size)
7654 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00007655}
7656
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007657//===--- CHECK: Return Address of Stack Variable --------------------------===//
7658
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007659static const Expr *EvalVal(const Expr *E,
7660 SmallVectorImpl<const DeclRefExpr *> &refVars,
7661 const Decl *ParentDecl);
7662static const Expr *EvalAddr(const Expr *E,
7663 SmallVectorImpl<const DeclRefExpr *> &refVars,
7664 const Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007665
7666/// CheckReturnStackAddr - Check if a return statement returns the address
7667/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007668static void
7669CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
7670 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00007671
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007672 const Expr *stackE = nullptr;
7673 SmallVector<const DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007674
7675 // Perform checking for returned stack addresses, local blocks,
7676 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00007677 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007678 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007679 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00007680 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007681 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007682 }
7683
Craig Topperc3ec1492014-05-26 06:22:03 +00007684 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007685 return; // Nothing suspicious was found.
7686
Simon Pilgrim750bde62017-03-31 11:00:53 +00007687 // Parameters are initialized in the calling scope, so taking the address
Richard Trieu81b6c562016-08-05 23:24:47 +00007688 // of a parameter reference doesn't need a warning.
7689 for (auto *DRE : refVars)
7690 if (isa<ParmVarDecl>(DRE->getDecl()))
7691 return;
7692
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007693 SourceLocation diagLoc;
7694 SourceRange diagRange;
7695 if (refVars.empty()) {
7696 diagLoc = stackE->getLocStart();
7697 diagRange = stackE->getSourceRange();
7698 } else {
7699 // We followed through a reference variable. 'stackE' contains the
7700 // problematic expression but we will warn at the return statement pointing
7701 // at the reference variable. We will later display the "trail" of
7702 // reference variables using notes.
7703 diagLoc = refVars[0]->getLocStart();
7704 diagRange = refVars[0]->getSourceRange();
7705 }
7706
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007707 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
7708 // address of local var
Craig Topperda7b27f2015-11-17 05:40:09 +00007709 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007710 << DR->getDecl()->getDeclName() << diagRange;
7711 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007712 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007713 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007714 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007715 } else { // local temporary.
Richard Trieu81b6c562016-08-05 23:24:47 +00007716 // If there is an LValue->RValue conversion, then the value of the
7717 // reference type is used, not the reference.
7718 if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
7719 if (ICE->getCastKind() == CK_LValueToRValue) {
7720 return;
7721 }
7722 }
Craig Topperda7b27f2015-11-17 05:40:09 +00007723 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
7724 << lhsType->isReferenceType() << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007725 }
7726
7727 // Display the "trail" of reference variables that we followed until we
7728 // found the problematic expression using notes.
7729 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007730 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007731 // If this var binds to another reference var, show the range of the next
7732 // var, otherwise the var binds to the problematic expression, in which case
7733 // show the range of the expression.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007734 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
7735 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007736 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
7737 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007738 }
7739}
7740
7741/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
7742/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007743/// to a location on the stack, a local block, an address of a label, or a
7744/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007745/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007746/// encounter a subexpression that (1) clearly does not lead to one of the
7747/// above problematic expressions (2) is something we cannot determine leads to
7748/// a problematic expression based on such local checking.
7749///
7750/// Both EvalAddr and EvalVal follow through reference variables to evaluate
7751/// the expression that they point to. Such variables are added to the
7752/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007753///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00007754/// EvalAddr processes expressions that are pointers that are used as
7755/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007756/// At the base case of the recursion is a check for the above problematic
7757/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007758///
7759/// This implementation handles:
7760///
7761/// * pointer-to-pointer casts
7762/// * implicit conversions from array references to pointers
7763/// * taking the address of fields
7764/// * arbitrary interplay between "&" and "*" operators
7765/// * pointer arithmetic from an address of a stack variable
7766/// * taking the address of an array element where the array is on the stack
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007767static const Expr *EvalAddr(const Expr *E,
7768 SmallVectorImpl<const DeclRefExpr *> &refVars,
7769 const Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007770 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00007771 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007772
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007773 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00007774 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00007775 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00007776 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00007777 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00007778
Peter Collingbourne91147592011-04-15 00:35:48 +00007779 E = E->IgnoreParens();
7780
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007781 // Our "symbolic interpreter" is just a dispatch off the currently
7782 // viewed AST node. We then recursively traverse the AST by calling
7783 // EvalAddr and EvalVal appropriately.
7784 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007785 case Stmt::DeclRefExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007786 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007787
Richard Smith40f08eb2014-01-30 22:05:38 +00007788 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00007789 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00007790 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00007791
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007792 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007793 // If this is a reference variable, follow through to the expression that
7794 // it points to.
7795 if (V->hasLocalStorage() &&
7796 V->getType()->isReferenceType() && V->hasInit()) {
7797 // Add the reference variable to the "trail".
7798 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007799 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007800 }
7801
Craig Topperc3ec1492014-05-26 06:22:03 +00007802 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007803 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007804
Chris Lattner934edb22007-12-28 05:31:15 +00007805 case Stmt::UnaryOperatorClass: {
7806 // The only unary operator that make sense to handle here
7807 // is AddrOf. All others don't make sense as pointers.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007808 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007809
John McCalle3027922010-08-25 11:45:40 +00007810 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007811 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007812 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007813 }
Mike Stump11289f42009-09-09 15:08:12 +00007814
Chris Lattner934edb22007-12-28 05:31:15 +00007815 case Stmt::BinaryOperatorClass: {
7816 // Handle pointer arithmetic. All other binary operators are not valid
7817 // in this context.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007818 const BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00007819 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00007820
John McCalle3027922010-08-25 11:45:40 +00007821 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00007822 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00007823
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007824 const Expr *Base = B->getLHS();
Chris Lattner934edb22007-12-28 05:31:15 +00007825
7826 // Determine which argument is the real pointer base. It could be
7827 // the RHS argument instead of the LHS.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007828 if (!Base->getType()->isPointerType())
7829 Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00007830
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007831 assert(Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007832 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00007833 }
Steve Naroff2752a172008-09-10 19:17:48 +00007834
Chris Lattner934edb22007-12-28 05:31:15 +00007835 // For conditional operators we need to see if either the LHS or RHS are
7836 // valid DeclRefExpr*s. If one of them is valid, we return it.
7837 case Stmt::ConditionalOperatorClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007838 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007839
Chris Lattner934edb22007-12-28 05:31:15 +00007840 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007841 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007842 if (const Expr *LHSExpr = C->getLHS()) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007843 // In C++, we can have a throw-expression, which has 'void' type.
7844 if (!LHSExpr->getType()->isVoidType())
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007845 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007846 return LHS;
7847 }
Chris Lattner934edb22007-12-28 05:31:15 +00007848
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007849 // In C++, we can have a throw-expression, which has 'void' type.
7850 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00007851 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007852
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007853 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00007854 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007855
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007856 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00007857 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007858 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00007859 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007860
7861 case Stmt::AddrLabelExprClass:
7862 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00007863
John McCall28fc7092011-11-10 05:35:25 +00007864 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007865 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7866 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00007867
Ted Kremenekc3b4c522008-08-07 00:49:01 +00007868 // For casts, we need to handle conversions from arrays to
7869 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00007870 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00007871 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00007872 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00007873 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00007874 case Stmt::CXXStaticCastExprClass:
7875 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00007876 case Stmt::CXXConstCastExprClass:
7877 case Stmt::CXXReinterpretCastExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007878 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Eli Friedman8195ad72012-02-23 23:04:32 +00007879 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00007880 case CK_LValueToRValue:
7881 case CK_NoOp:
7882 case CK_BaseToDerived:
7883 case CK_DerivedToBase:
7884 case CK_UncheckedDerivedToBase:
7885 case CK_Dynamic:
7886 case CK_CPointerToObjCPointerCast:
7887 case CK_BlockPointerToObjCPointerCast:
7888 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007889 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00007890
7891 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007892 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00007893
Richard Trieudadefde2014-07-02 04:39:38 +00007894 case CK_BitCast:
7895 if (SubExpr->getType()->isAnyPointerType() ||
7896 SubExpr->getType()->isBlockPointerType() ||
7897 SubExpr->getType()->isObjCQualifiedIdType())
7898 return EvalAddr(SubExpr, refVars, ParentDecl);
7899 else
7900 return nullptr;
7901
Eli Friedman8195ad72012-02-23 23:04:32 +00007902 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00007903 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00007904 }
Chris Lattner934edb22007-12-28 05:31:15 +00007905 }
Mike Stump11289f42009-09-09 15:08:12 +00007906
Douglas Gregorfe314812011-06-21 17:03:29 +00007907 case Stmt::MaterializeTemporaryExprClass:
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007908 if (const Expr *Result =
7909 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7910 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00007911 return Result;
Douglas Gregorfe314812011-06-21 17:03:29 +00007912 return E;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007913
Chris Lattner934edb22007-12-28 05:31:15 +00007914 // Everything else: we simply don't reason about them.
7915 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00007916 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00007917 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007918}
Mike Stump11289f42009-09-09 15:08:12 +00007919
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007920/// EvalVal - This function is complements EvalAddr in the mutual recursion.
7921/// See the comments for EvalAddr for more details.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007922static const Expr *EvalVal(const Expr *E,
7923 SmallVectorImpl<const DeclRefExpr *> &refVars,
7924 const Decl *ParentDecl) {
7925 do {
7926 // We should only be called for evaluating non-pointer expressions, or
7927 // expressions with a pointer type that are not used as references but
7928 // instead
7929 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00007930
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007931 // Our "symbolic interpreter" is just a dispatch off the currently
7932 // viewed AST node. We then recursively traverse the AST by calling
7933 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00007934
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007935 E = E->IgnoreParens();
7936 switch (E->getStmtClass()) {
7937 case Stmt::ImplicitCastExprClass: {
7938 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
7939 if (IE->getValueKind() == VK_LValue) {
7940 E = IE->getSubExpr();
7941 continue;
7942 }
Craig Topperc3ec1492014-05-26 06:22:03 +00007943 return nullptr;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007944 }
Richard Smith40f08eb2014-01-30 22:05:38 +00007945
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007946 case Stmt::ExprWithCleanupsClass:
7947 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7948 ParentDecl);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007949
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007950 case Stmt::DeclRefExprClass: {
7951 // When we hit a DeclRefExpr we are looking at code that refers to a
7952 // variable's name. If it's not a reference variable we check if it has
7953 // local storage within the function, and if so, return the expression.
7954 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7955
7956 // If we leave the immediate function, the lifetime isn't about to end.
7957 if (DR->refersToEnclosingVariableOrCapture())
7958 return nullptr;
7959
7960 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
7961 // Check if it refers to itself, e.g. "int& i = i;".
7962 if (V == ParentDecl)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007963 return DR;
7964
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007965 if (V->hasLocalStorage()) {
7966 if (!V->getType()->isReferenceType())
7967 return DR;
7968
7969 // Reference variable, follow through to the expression that
7970 // it points to.
7971 if (V->hasInit()) {
7972 // Add the reference variable to the "trail".
7973 refVars.push_back(DR);
7974 return EvalVal(V->getInit(), refVars, V);
7975 }
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007976 }
7977 }
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007978
7979 return nullptr;
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007980 }
Mike Stump11289f42009-09-09 15:08:12 +00007981
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007982 case Stmt::UnaryOperatorClass: {
7983 // The only unary operator that make sense to handle here
7984 // is Deref. All others don't resolve to a "name." This includes
7985 // handling all sorts of rvalues passed to a unary operator.
7986 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007987
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007988 if (U->getOpcode() == UO_Deref)
7989 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Mike Stump11289f42009-09-09 15:08:12 +00007990
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007991 return nullptr;
7992 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007993
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007994 case Stmt::ArraySubscriptExprClass: {
7995 // Array subscripts are potential references to data on the stack. We
7996 // retrieve the DeclRefExpr* for the array variable if it indeed
7997 // has local storage.
Saleem Abdulrasoolcfd45532016-02-15 01:51:24 +00007998 const auto *ASE = cast<ArraySubscriptExpr>(E);
7999 if (ASE->isTypeDependent())
8000 return nullptr;
8001 return EvalAddr(ASE->getBase(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008002 }
Mike Stump11289f42009-09-09 15:08:12 +00008003
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008004 case Stmt::OMPArraySectionExprClass: {
8005 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
8006 ParentDecl);
8007 }
Mike Stump11289f42009-09-09 15:08:12 +00008008
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008009 case Stmt::ConditionalOperatorClass: {
8010 // For conditional operators we need to see if either the LHS or RHS are
8011 // non-NULL Expr's. If one is non-NULL, we return it.
8012 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Alexey Bataev1a3320e2015-08-25 14:24:04 +00008013
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008014 // Handle the GNU extension for missing LHS.
8015 if (const Expr *LHSExpr = C->getLHS()) {
8016 // In C++, we can have a throw-expression, which has 'void' type.
8017 if (!LHSExpr->getType()->isVoidType())
8018 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
8019 return LHS;
8020 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008021
Richard Smith6a6a4bb2014-01-27 04:19:56 +00008022 // In C++, we can have a throw-expression, which has 'void' type.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008023 if (C->getRHS()->getType()->isVoidType())
8024 return nullptr;
8025
8026 return EvalVal(C->getRHS(), refVars, ParentDecl);
Richard Smith6a6a4bb2014-01-27 04:19:56 +00008027 }
8028
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008029 // Accesses to members are potential references to data on the stack.
8030 case Stmt::MemberExprClass: {
8031 const MemberExpr *M = cast<MemberExpr>(E);
Anders Carlsson801c5c72007-11-30 19:04:31 +00008032
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008033 // Check for indirect access. We only want direct field accesses.
8034 if (M->isArrow())
8035 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00008036
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008037 // Check whether the member type is itself a reference, in which case
8038 // we're not going to refer to the member, but to what the member refers
8039 // to.
8040 if (M->getMemberDecl()->getType()->isReferenceType())
8041 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00008042
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008043 return EvalVal(M->getBase(), refVars, ParentDecl);
8044 }
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00008045
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008046 case Stmt::MaterializeTemporaryExprClass:
8047 if (const Expr *Result =
8048 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
8049 refVars, ParentDecl))
8050 return Result;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008051 return E;
8052
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008053 default:
8054 // Check that we don't return or take the address of a reference to a
8055 // temporary. This is only useful in C++.
8056 if (!E->isTypeDependent() && E->isRValue())
8057 return E;
8058
8059 // Everything else: we simply don't reason about them.
8060 return nullptr;
8061 }
8062 } while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008063}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008064
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008065void
8066Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
8067 SourceLocation ReturnLoc,
8068 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00008069 const AttrVec *Attrs,
8070 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008071 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
8072
8073 // Check if the return value is null but should not be.
Douglas Gregorb4866e82015-06-19 18:13:19 +00008074 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
8075 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
Benjamin Kramerae852a62014-02-23 14:34:50 +00008076 CheckNonNullExpr(*this, RetValExp))
8077 Diag(ReturnLoc, diag::warn_null_ret)
8078 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00008079
8080 // C++11 [basic.stc.dynamic.allocation]p4:
8081 // If an allocation function declared with a non-throwing
8082 // exception-specification fails to allocate storage, it shall return
8083 // a null pointer. Any other allocation function that fails to allocate
8084 // storage shall indicate failure only by throwing an exception [...]
8085 if (FD) {
8086 OverloadedOperatorKind Op = FD->getOverloadedOperator();
8087 if (Op == OO_New || Op == OO_Array_New) {
8088 const FunctionProtoType *Proto
8089 = FD->getType()->castAs<FunctionProtoType>();
8090 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
8091 CheckNonNullExpr(*this, RetValExp))
8092 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
8093 << FD << getLangOpts().CPlusPlus11;
8094 }
8095 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008096}
8097
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008098//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
8099
8100/// Check for comparisons of floating point operands using != and ==.
8101/// Issue a warning if these are no self-comparisons, as they are not likely
8102/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00008103void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00008104 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
8105 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008106
8107 // Special case: check for x == x (which is OK).
8108 // Do not emit warnings for such cases.
8109 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
8110 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
8111 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00008112 return;
Mike Stump11289f42009-09-09 15:08:12 +00008113
Ted Kremenekeda40e22007-11-29 00:59:04 +00008114 // Special case: check for comparisons against literals that can be exactly
8115 // represented by APFloat. In such cases, do not emit a warning. This
8116 // is a heuristic: often comparison against such literals are used to
8117 // detect if a value in a variable has not changed. This clearly can
8118 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00008119 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
8120 if (FLL->isExact())
8121 return;
8122 } else
8123 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
8124 if (FLR->isExact())
8125 return;
Mike Stump11289f42009-09-09 15:08:12 +00008126
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008127 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00008128 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00008129 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00008130 return;
Mike Stump11289f42009-09-09 15:08:12 +00008131
David Blaikie1f4ff152012-07-16 20:47:22 +00008132 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00008133 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00008134 return;
Mike Stump11289f42009-09-09 15:08:12 +00008135
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008136 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00008137 Diag(Loc, diag::warn_floatingpoint_eq)
8138 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008139}
John McCallca01b222010-01-04 23:21:16 +00008140
John McCall70aa5392010-01-06 05:24:50 +00008141//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
8142//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00008143
John McCall70aa5392010-01-06 05:24:50 +00008144namespace {
John McCallca01b222010-01-04 23:21:16 +00008145
John McCall70aa5392010-01-06 05:24:50 +00008146/// Structure recording the 'active' range of an integer-valued
8147/// expression.
8148struct IntRange {
8149 /// The number of bits active in the int.
8150 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00008151
John McCall70aa5392010-01-06 05:24:50 +00008152 /// True if the int is known not to have negative values.
8153 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00008154
John McCall70aa5392010-01-06 05:24:50 +00008155 IntRange(unsigned Width, bool NonNegative)
8156 : Width(Width), NonNegative(NonNegative)
8157 {}
John McCallca01b222010-01-04 23:21:16 +00008158
John McCall817d4af2010-11-10 23:38:19 +00008159 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00008160 static IntRange forBoolType() {
8161 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00008162 }
8163
John McCall817d4af2010-11-10 23:38:19 +00008164 /// Returns the range of an opaque value of the given integral type.
8165 static IntRange forValueOfType(ASTContext &C, QualType T) {
8166 return forValueOfCanonicalType(C,
8167 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00008168 }
8169
John McCall817d4af2010-11-10 23:38:19 +00008170 /// Returns the range of an opaque value of a canonical integral type.
8171 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00008172 assert(T->isCanonicalUnqualified());
8173
8174 if (const VectorType *VT = dyn_cast<VectorType>(T))
8175 T = VT->getElementType().getTypePtr();
8176 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8177 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00008178 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8179 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00008180
David Majnemer6a426652013-06-07 22:07:20 +00008181 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00008182 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00008183 EnumDecl *Enum = ET->getDecl();
Erich Keane69dbbb02017-09-21 19:58:55 +00008184 // In C++11, enums without definitions can have an explicitly specified
8185 // underlying type. Use this type to compute the range.
David Majnemer6a426652013-06-07 22:07:20 +00008186 if (!Enum->isCompleteDefinition())
Erich Keane69dbbb02017-09-21 19:58:55 +00008187 return IntRange(C.getIntWidth(QualType(T, 0)),
8188 !ET->isSignedIntegerOrEnumerationType());
John McCall18a2c2c2010-11-09 22:22:12 +00008189
David Majnemer6a426652013-06-07 22:07:20 +00008190 unsigned NumPositive = Enum->getNumPositiveBits();
8191 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00008192
David Majnemer6a426652013-06-07 22:07:20 +00008193 if (NumNegative == 0)
8194 return IntRange(NumPositive, true/*NonNegative*/);
8195 else
8196 return IntRange(std::max(NumPositive + 1, NumNegative),
8197 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00008198 }
John McCall70aa5392010-01-06 05:24:50 +00008199
8200 const BuiltinType *BT = cast<BuiltinType>(T);
8201 assert(BT->isInteger());
8202
8203 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8204 }
8205
John McCall817d4af2010-11-10 23:38:19 +00008206 /// Returns the "target" range of a canonical integral type, i.e.
8207 /// the range of values expressible in the type.
8208 ///
8209 /// This matches forValueOfCanonicalType except that enums have the
8210 /// full range of their type, not the range of their enumerators.
8211 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
8212 assert(T->isCanonicalUnqualified());
8213
8214 if (const VectorType *VT = dyn_cast<VectorType>(T))
8215 T = VT->getElementType().getTypePtr();
8216 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8217 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00008218 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8219 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00008220 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00008221 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00008222
8223 const BuiltinType *BT = cast<BuiltinType>(T);
8224 assert(BT->isInteger());
8225
8226 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8227 }
8228
8229 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00008230 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00008231 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00008232 L.NonNegative && R.NonNegative);
8233 }
8234
John McCall817d4af2010-11-10 23:38:19 +00008235 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00008236 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00008237 return IntRange(std::min(L.Width, R.Width),
8238 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00008239 }
8240};
8241
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008242IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008243 if (value.isSigned() && value.isNegative())
8244 return IntRange(value.getMinSignedBits(), false);
8245
8246 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00008247 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00008248
8249 // isNonNegative() just checks the sign bit without considering
8250 // signedness.
8251 return IntRange(value.getActiveBits(), true);
8252}
8253
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008254IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
8255 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008256 if (result.isInt())
8257 return GetValueRange(C, result.getInt(), MaxWidth);
8258
8259 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00008260 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
8261 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
8262 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
8263 R = IntRange::join(R, El);
8264 }
John McCall70aa5392010-01-06 05:24:50 +00008265 return R;
8266 }
8267
8268 if (result.isComplexInt()) {
8269 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
8270 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
8271 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00008272 }
8273
8274 // This can happen with lossless casts to intptr_t of "based" lvalues.
8275 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00008276 // FIXME: The only reason we need to pass the type in here is to get
8277 // the sign right on this one case. It would be nice if APValue
8278 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008279 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00008280 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00008281}
John McCall70aa5392010-01-06 05:24:50 +00008282
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008283QualType GetExprType(const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008284 QualType Ty = E->getType();
8285 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
8286 Ty = AtomicRHS->getValueType();
8287 return Ty;
8288}
8289
John McCall70aa5392010-01-06 05:24:50 +00008290/// Pseudo-evaluate the given integer expression, estimating the
8291/// range of values it might take.
8292///
8293/// \param MaxWidth - the width to which the value will be truncated
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008294IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008295 E = E->IgnoreParens();
8296
8297 // Try a full evaluation first.
8298 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00008299 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00008300 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00008301
8302 // I think we only want to look through implicit casts here; if the
8303 // user has an explicit widening cast, we should treat the value as
8304 // being of the new, wider type.
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008305 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00008306 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00008307 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
8308
Eli Friedmane6d33952013-07-08 20:20:06 +00008309 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00008310
George Burgess IVdf1ed002016-01-13 01:52:39 +00008311 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
8312 CE->getCastKind() == CK_BooleanToSignedIntegral;
John McCall2ce81ad2010-01-06 22:07:33 +00008313
John McCall70aa5392010-01-06 05:24:50 +00008314 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00008315 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00008316 return OutputTypeRange;
8317
8318 IntRange SubRange
8319 = GetExprRange(C, CE->getSubExpr(),
8320 std::min(MaxWidth, OutputTypeRange.Width));
8321
8322 // Bail out if the subexpr's range is as wide as the cast type.
8323 if (SubRange.Width >= OutputTypeRange.Width)
8324 return OutputTypeRange;
8325
8326 // Otherwise, we take the smaller width, and we're non-negative if
8327 // either the output type or the subexpr is.
8328 return IntRange(SubRange.Width,
8329 SubRange.NonNegative || OutputTypeRange.NonNegative);
8330 }
8331
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008332 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008333 // If we can fold the condition, just take that operand.
8334 bool CondResult;
8335 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
8336 return GetExprRange(C, CondResult ? CO->getTrueExpr()
8337 : CO->getFalseExpr(),
8338 MaxWidth);
8339
8340 // Otherwise, conservatively merge.
8341 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
8342 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
8343 return IntRange::join(L, R);
8344 }
8345
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008346 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008347 switch (BO->getOpcode()) {
8348
8349 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00008350 case BO_LAnd:
8351 case BO_LOr:
8352 case BO_LT:
8353 case BO_GT:
8354 case BO_LE:
8355 case BO_GE:
8356 case BO_EQ:
8357 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00008358 return IntRange::forBoolType();
8359
John McCallc3688382011-07-13 06:35:24 +00008360 // The type of the assignments is the type of the LHS, so the RHS
8361 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00008362 case BO_MulAssign:
8363 case BO_DivAssign:
8364 case BO_RemAssign:
8365 case BO_AddAssign:
8366 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00008367 case BO_XorAssign:
8368 case BO_OrAssign:
8369 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00008370 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00008371
John McCallc3688382011-07-13 06:35:24 +00008372 // Simple assignments just pass through the RHS, which will have
8373 // been coerced to the LHS type.
8374 case BO_Assign:
8375 // TODO: bitfields?
8376 return GetExprRange(C, BO->getRHS(), MaxWidth);
8377
John McCall70aa5392010-01-06 05:24:50 +00008378 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00008379 case BO_PtrMemD:
8380 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00008381 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008382
John McCall2ce81ad2010-01-06 22:07:33 +00008383 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00008384 case BO_And:
8385 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00008386 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
8387 GetExprRange(C, BO->getRHS(), MaxWidth));
8388
John McCall70aa5392010-01-06 05:24:50 +00008389 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00008390 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00008391 // ...except that we want to treat '1 << (blah)' as logically
8392 // positive. It's an important idiom.
8393 if (IntegerLiteral *I
8394 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
8395 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008396 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00008397 return IntRange(R.Width, /*NonNegative*/ true);
8398 }
8399 }
8400 // fallthrough
8401
John McCalle3027922010-08-25 11:45:40 +00008402 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00008403 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008404
John McCall2ce81ad2010-01-06 22:07:33 +00008405 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00008406 case BO_Shr:
8407 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00008408 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8409
8410 // If the shift amount is a positive constant, drop the width by
8411 // that much.
8412 llvm::APSInt shift;
8413 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
8414 shift.isNonNegative()) {
8415 unsigned zext = shift.getZExtValue();
8416 if (zext >= L.Width)
8417 L.Width = (L.NonNegative ? 0 : 1);
8418 else
8419 L.Width -= zext;
8420 }
8421
8422 return L;
8423 }
8424
8425 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00008426 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00008427 return GetExprRange(C, BO->getRHS(), MaxWidth);
8428
John McCall2ce81ad2010-01-06 22:07:33 +00008429 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00008430 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00008431 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00008432 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008433 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00008434
John McCall51431812011-07-14 22:39:48 +00008435 // The width of a division result is mostly determined by the size
8436 // of the LHS.
8437 case BO_Div: {
8438 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00008439 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008440 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8441
8442 // If the divisor is constant, use that.
8443 llvm::APSInt divisor;
8444 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
8445 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
8446 if (log2 >= L.Width)
8447 L.Width = (L.NonNegative ? 0 : 1);
8448 else
8449 L.Width = std::min(L.Width - log2, MaxWidth);
8450 return L;
8451 }
8452
8453 // Otherwise, just use the LHS's width.
8454 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8455 return IntRange(L.Width, L.NonNegative && R.NonNegative);
8456 }
8457
8458 // The result of a remainder can't be larger than the result of
8459 // either side.
8460 case BO_Rem: {
8461 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00008462 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008463 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8464 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8465
8466 IntRange meet = IntRange::meet(L, R);
8467 meet.Width = std::min(meet.Width, MaxWidth);
8468 return meet;
8469 }
8470
8471 // The default behavior is okay for these.
8472 case BO_Mul:
8473 case BO_Add:
8474 case BO_Xor:
8475 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00008476 break;
8477 }
8478
John McCall51431812011-07-14 22:39:48 +00008479 // The default case is to treat the operation as if it were closed
8480 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00008481 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8482 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
8483 return IntRange::join(L, R);
8484 }
8485
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008486 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008487 switch (UO->getOpcode()) {
8488 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00008489 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00008490 return IntRange::forBoolType();
8491
8492 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00008493 case UO_Deref:
8494 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00008495 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008496
8497 default:
8498 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
8499 }
8500 }
8501
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008502 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
Ted Kremeneka553fbf2013-10-14 18:55:27 +00008503 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
8504
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008505 if (const auto *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00008506 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00008507 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00008508
Eli Friedmane6d33952013-07-08 20:20:06 +00008509 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008510}
John McCall263a48b2010-01-04 23:31:57 +00008511
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008512IntRange GetExprRange(ASTContext &C, const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008513 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00008514}
8515
John McCall263a48b2010-01-04 23:31:57 +00008516/// Checks whether the given value, which currently has the given
8517/// source semantics, has the same value when coerced through the
8518/// target semantics.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008519bool IsSameFloatAfterCast(const llvm::APFloat &value,
8520 const llvm::fltSemantics &Src,
8521 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00008522 llvm::APFloat truncated = value;
8523
8524 bool ignored;
8525 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
8526 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
8527
8528 return truncated.bitwiseIsEqual(value);
8529}
8530
8531/// Checks whether the given value, which currently has the given
8532/// source semantics, has the same value when coerced through the
8533/// target semantics.
8534///
8535/// The value might be a vector of floats (or a complex number).
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008536bool IsSameFloatAfterCast(const APValue &value,
8537 const llvm::fltSemantics &Src,
8538 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00008539 if (value.isFloat())
8540 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
8541
8542 if (value.isVector()) {
8543 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
8544 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
8545 return false;
8546 return true;
8547 }
8548
8549 assert(value.isComplexFloat());
8550 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
8551 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
8552}
8553
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008554void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008555
Roman Lebedevbd1fc222017-10-12 20:16:51 +00008556bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
Ted Kremenek6274be42010-09-23 21:43:44 +00008557 // Suppress cases where we are comparing against an enum constant.
8558 if (const DeclRefExpr *DR =
8559 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
8560 if (isa<EnumConstantDecl>(DR->getDecl()))
Roman Lebedevbd1fc222017-10-12 20:16:51 +00008561 return true;
Ted Kremenek6274be42010-09-23 21:43:44 +00008562
8563 // Suppress cases where the '0' value is expanded from a macro.
8564 if (E->getLocStart().isMacroID())
Roman Lebedevbd1fc222017-10-12 20:16:51 +00008565 return true;
Ted Kremenek6274be42010-09-23 21:43:44 +00008566
Roman Lebedevbd1fc222017-10-12 20:16:51 +00008567 return false;
8568}
8569
8570bool isNonBooleanIntegerValue(Expr *E) {
8571 return !E->isKnownToHaveBooleanValue() && E->getType()->isIntegerType();
8572}
8573
8574bool isNonBooleanUnsignedValue(Expr *E) {
8575 // We are checking that the expression is not known to have boolean value,
8576 // is an integer type; and is either unsigned after implicit casts,
8577 // or was unsigned before implicit casts.
8578 return isNonBooleanIntegerValue(E) &&
8579 (!E->getType()->isSignedIntegerType() ||
8580 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
8581}
8582
8583enum class LimitType {
8584 Max, // e.g. 32767 for short
8585 Min // e.g. -32768 for short
8586};
8587
8588/// Checks whether Expr 'Constant' may be the
8589/// std::numeric_limits<>::max() or std::numeric_limits<>::min()
8590/// of the Expr 'Other'. If true, then returns the limit type (min or max).
8591/// The Value is the evaluation of Constant
8592llvm::Optional<LimitType> IsTypeLimit(Sema &S, Expr *Constant, Expr *Other,
8593 const llvm::APSInt &Value) {
8594 if (IsEnumConstOrFromMacro(S, Constant))
8595 return llvm::Optional<LimitType>();
8596
8597 if (isNonBooleanUnsignedValue(Other) && Value == 0)
8598 return LimitType::Min;
8599
8600 // TODO: Investigate using GetExprRange() to get tighter bounds
8601 // on the bit ranges.
8602 QualType OtherT = Other->IgnoreParenImpCasts()->getType();
8603 if (const auto *AT = OtherT->getAs<AtomicType>())
8604 OtherT = AT->getValueType();
8605
8606 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
8607
8608 if (llvm::APSInt::isSameValue(
8609 llvm::APSInt::getMaxValue(OtherRange.Width,
8610 OtherT->isUnsignedIntegerType()),
8611 Value))
8612 return LimitType::Max;
8613
8614 if (llvm::APSInt::isSameValue(
8615 llvm::APSInt::getMinValue(OtherRange.Width,
8616 OtherT->isUnsignedIntegerType()),
8617 Value))
8618 return LimitType::Min;
8619
8620 return llvm::Optional<LimitType>();
John McCallcc7e5bf2010-05-06 08:58:33 +00008621}
8622
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008623bool HasEnumType(Expr *E) {
John McCall2551c1b2010-10-06 00:25:24 +00008624 // Strip off implicit integral promotions.
8625 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00008626 if (ICE->getCastKind() != CK_IntegralCast &&
8627 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00008628 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00008629 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00008630 }
8631
8632 return E->getType()->isEnumeralType();
8633}
8634
Roman Lebedevbd1fc222017-10-12 20:16:51 +00008635bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, Expr *Constant,
8636 Expr *Other, const llvm::APSInt &Value,
8637 bool RhsConstant) {
8638 // Disable warning in template instantiations
8639 // and only analyze <, >, <= and >= operations.
8640 if (S.inTemplateInstantiation() || !E->isRelationalOp())
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00008641 return false;
8642
Roman Lebedevb0f0a1e2017-09-20 09:54:47 +00008643 BinaryOperatorKind Op = E->getOpcode();
Roman Lebedevbd1fc222017-10-12 20:16:51 +00008644
8645 QualType OType = Other->IgnoreParenImpCasts()->getType();
8646
8647 llvm::Optional<LimitType> ValueType; // Which limit (min/max) is the constant?
8648
8649 if (!(isNonBooleanIntegerValue(Other) &&
8650 (ValueType = IsTypeLimit(S, Constant, Other, Value))))
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00008651 return false;
Douglas Gregorb14dbd72010-12-21 07:22:56 +00008652
Roman Lebedevbd1fc222017-10-12 20:16:51 +00008653 bool ConstIsLowerBound = (Op == BO_LT || Op == BO_LE) ^ RhsConstant;
8654 bool ResultWhenConstEqualsOther = (Op == BO_LE || Op == BO_GE);
8655 bool ResultWhenConstNeOther = ConstIsLowerBound ^ ValueType == LimitType::Max;
8656 if (ResultWhenConstEqualsOther != ResultWhenConstNeOther)
8657 return false; // The comparison is not tautological.
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00008658
Roman Lebedevbd1fc222017-10-12 20:16:51 +00008659 const bool Result = ResultWhenConstEqualsOther;
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00008660
Roman Lebedevbd1fc222017-10-12 20:16:51 +00008661 unsigned Diag = (isNonBooleanUnsignedValue(Other) && Value == 0)
8662 ? (HasEnumType(Other)
8663 ? diag::warn_unsigned_enum_always_true_comparison
8664 : diag::warn_unsigned_always_true_comparison)
8665 : diag::warn_tautological_constant_compare;
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00008666
Roman Lebedevbd1fc222017-10-12 20:16:51 +00008667 // Should be enough for uint128 (39 decimal digits)
8668 SmallString<64> PrettySourceValue;
8669 llvm::raw_svector_ostream OS(PrettySourceValue);
8670 OS << Value;
8671
8672 S.Diag(E->getOperatorLoc(), Diag)
8673 << RhsConstant << OType << E->getOpcodeStr() << OS.str() << Result
8674 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
8675
8676 return true;
John McCallcc7e5bf2010-05-06 08:58:33 +00008677}
8678
Roman Lebedevbd1fc222017-10-12 20:16:51 +00008679bool DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E, Expr *Constant,
Benjamin Kramer7320b992016-06-15 14:20:56 +00008680 Expr *Other, const llvm::APSInt &Value,
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008681 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00008682 // Disable warning in template instantiations.
Richard Smith51ec0cf2017-02-21 01:17:38 +00008683 if (S.inTemplateInstantiation())
Roman Lebedevbd1fc222017-10-12 20:16:51 +00008684 return false;
8685
8686 Constant = Constant->IgnoreParenImpCasts();
8687 Other = Other->IgnoreParenImpCasts();
Richard Trieudd51d742013-11-01 21:19:43 +00008688
Richard Trieu0f097742014-04-04 04:13:47 +00008689 // TODO: Investigate using GetExprRange() to get tighter bounds
8690 // on the bit ranges.
8691 QualType OtherT = Other->getType();
David Majnemer7800f1f2015-05-23 01:32:17 +00008692 if (const auto *AT = OtherT->getAs<AtomicType>())
Justin Bogner4f42fc42014-07-21 18:01:53 +00008693 OtherT = AT->getValueType();
Richard Trieu0f097742014-04-04 04:13:47 +00008694 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
8695 unsigned OtherWidth = OtherRange.Width;
8696
8697 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
8698
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008699 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00008700 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00008701
Richard Trieu0f097742014-04-04 04:13:47 +00008702 // Used for diagnostic printout.
8703 enum {
8704 LiteralConstant = 0,
8705 CXXBoolLiteralTrue,
8706 CXXBoolLiteralFalse
8707 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00008708
Richard Trieu0f097742014-04-04 04:13:47 +00008709 if (!OtherIsBooleanType) {
8710 QualType ConstantT = Constant->getType();
8711 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00008712
Richard Trieu0f097742014-04-04 04:13:47 +00008713 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
Roman Lebedevbd1fc222017-10-12 20:16:51 +00008714 return false;
Richard Trieu0f097742014-04-04 04:13:47 +00008715 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
8716 "comparison with non-integer type");
8717
8718 bool ConstantSigned = ConstantT->isSignedIntegerType();
8719 bool CommonSigned = CommonT->isSignedIntegerType();
8720
8721 bool EqualityOnly = false;
8722
8723 if (CommonSigned) {
8724 // The common type is signed, therefore no signed to unsigned conversion.
8725 if (!OtherRange.NonNegative) {
8726 // Check that the constant is representable in type OtherT.
8727 if (ConstantSigned) {
8728 if (OtherWidth >= Value.getMinSignedBits())
Roman Lebedevbd1fc222017-10-12 20:16:51 +00008729 return false;
Richard Trieu0f097742014-04-04 04:13:47 +00008730 } else { // !ConstantSigned
8731 if (OtherWidth >= Value.getActiveBits() + 1)
Roman Lebedevbd1fc222017-10-12 20:16:51 +00008732 return false;
Richard Trieu0f097742014-04-04 04:13:47 +00008733 }
8734 } else { // !OtherSigned
8735 // Check that the constant is representable in type OtherT.
8736 // Negative values are out of range.
8737 if (ConstantSigned) {
8738 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
Roman Lebedevbd1fc222017-10-12 20:16:51 +00008739 return false;
Richard Trieu0f097742014-04-04 04:13:47 +00008740 } else { // !ConstantSigned
8741 if (OtherWidth >= Value.getActiveBits())
Roman Lebedevbd1fc222017-10-12 20:16:51 +00008742 return false;
Richard Trieu0f097742014-04-04 04:13:47 +00008743 }
Richard Trieu560910c2012-11-14 22:50:24 +00008744 }
Richard Trieu0f097742014-04-04 04:13:47 +00008745 } else { // !CommonSigned
8746 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00008747 if (OtherWidth >= Value.getActiveBits())
Roman Lebedevbd1fc222017-10-12 20:16:51 +00008748 return false;
Craig Toppercf360162014-06-18 05:13:11 +00008749 } else { // OtherSigned
8750 assert(!ConstantSigned &&
8751 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00008752 // Check to see if the constant is representable in OtherT.
8753 if (OtherWidth > Value.getActiveBits())
Roman Lebedevbd1fc222017-10-12 20:16:51 +00008754 return false;
Richard Trieu0f097742014-04-04 04:13:47 +00008755 // Check to see if the constant is equivalent to a negative value
8756 // cast to CommonT.
8757 if (S.Context.getIntWidth(ConstantT) ==
8758 S.Context.getIntWidth(CommonT) &&
8759 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
Roman Lebedevbd1fc222017-10-12 20:16:51 +00008760 return false;
Richard Trieu0f097742014-04-04 04:13:47 +00008761 // The constant value rests between values that OtherT can represent
8762 // after conversion. Relational comparison still works, but equality
8763 // comparisons will be tautological.
8764 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00008765 }
8766 }
Richard Trieu0f097742014-04-04 04:13:47 +00008767
8768 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
8769
8770 if (op == BO_EQ || op == BO_NE) {
8771 IsTrue = op == BO_NE;
8772 } else if (EqualityOnly) {
Roman Lebedevbd1fc222017-10-12 20:16:51 +00008773 return false;
Richard Trieu0f097742014-04-04 04:13:47 +00008774 } else if (RhsConstant) {
8775 if (op == BO_GT || op == BO_GE)
8776 IsTrue = !PositiveConstant;
8777 else // op == BO_LT || op == BO_LE
8778 IsTrue = PositiveConstant;
8779 } else {
8780 if (op == BO_LT || op == BO_LE)
8781 IsTrue = !PositiveConstant;
8782 else // op == BO_GT || op == BO_GE
8783 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00008784 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00008785 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00008786 // Other isKnownToHaveBooleanValue
8787 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
8788 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
8789 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
8790
8791 static const struct LinkedConditions {
8792 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
8793 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
8794 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
8795 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
8796 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
8797 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
8798
8799 } TruthTable = {
8800 // Constant on LHS. | Constant on RHS. |
8801 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
8802 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
8803 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
8804 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
8805 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
8806 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
8807 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
8808 };
8809
8810 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
8811
8812 enum ConstantValue ConstVal = Zero;
8813 if (Value.isUnsigned() || Value.isNonNegative()) {
8814 if (Value == 0) {
8815 LiteralOrBoolConstant =
8816 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
8817 ConstVal = Zero;
8818 } else if (Value == 1) {
8819 LiteralOrBoolConstant =
8820 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
8821 ConstVal = One;
8822 } else {
8823 LiteralOrBoolConstant = LiteralConstant;
8824 ConstVal = GT_One;
8825 }
8826 } else {
8827 ConstVal = LT_Zero;
8828 }
8829
8830 CompareBoolWithConstantResult CmpRes;
8831
8832 switch (op) {
8833 case BO_LT:
8834 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
8835 break;
8836 case BO_GT:
8837 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
8838 break;
8839 case BO_LE:
8840 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
8841 break;
8842 case BO_GE:
8843 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
8844 break;
8845 case BO_EQ:
8846 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
8847 break;
8848 case BO_NE:
8849 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
8850 break;
8851 default:
8852 CmpRes = Unkwn;
8853 break;
8854 }
8855
8856 if (CmpRes == AFals) {
8857 IsTrue = false;
8858 } else if (CmpRes == ATrue) {
8859 IsTrue = true;
8860 } else {
Roman Lebedevbd1fc222017-10-12 20:16:51 +00008861 return false;
Richard Trieu0f097742014-04-04 04:13:47 +00008862 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008863 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008864
8865 // If this is a comparison to an enum constant, include that
8866 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00008867 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008868 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
8869 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
8870
8871 SmallString<64> PrettySourceValue;
8872 llvm::raw_svector_ostream OS(PrettySourceValue);
8873 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00008874 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008875 else
8876 OS << Value;
8877
Richard Trieu0f097742014-04-04 04:13:47 +00008878 S.DiagRuntimeBehavior(
8879 E->getOperatorLoc(), E,
8880 S.PDiag(diag::warn_out_of_range_compare)
8881 << OS.str() << LiteralOrBoolConstant
8882 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
8883 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Roman Lebedevbd1fc222017-10-12 20:16:51 +00008884
8885 return true;
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008886}
8887
John McCallcc7e5bf2010-05-06 08:58:33 +00008888/// Analyze the operands of the given comparison. Implements the
8889/// fallback case from AnalyzeComparison.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008890void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00008891 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8892 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00008893}
John McCall263a48b2010-01-04 23:31:57 +00008894
John McCallca01b222010-01-04 23:21:16 +00008895/// \brief Implements -Wsign-compare.
8896///
Richard Trieu82402a02011-09-15 21:56:47 +00008897/// \param E the binary operator to check for warnings
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008898void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008899 // The type the comparison is being performed in.
8900 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00008901
8902 // Only analyze comparison operators where both sides have been converted to
8903 // the same type.
8904 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
8905 return AnalyzeImpConvsInComparison(S, E);
8906
8907 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00008908 if (E->isValueDependent())
8909 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00008910
Roman Lebedevbd1fc222017-10-12 20:16:51 +00008911 Expr *LHS = E->getLHS();
8912 Expr *RHS = E->getRHS();
8913
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008914 if (T->isIntegralType(S.Context)) {
8915 llvm::APSInt RHSValue;
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008916 llvm::APSInt LHSValue;
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00008917
Roman Lebedevbd1fc222017-10-12 20:16:51 +00008918 bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
8919 bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00008920
Roman Lebedevbd1fc222017-10-12 20:16:51 +00008921 // We don't care about expressions whose result is a constant.
8922 if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
8923 return AnalyzeImpConvsInComparison(S, E);
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00008924
Roman Lebedevbd1fc222017-10-12 20:16:51 +00008925 // We only care about expressions where just one side is literal
8926 if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
8927 // Is the constant on the RHS or LHS?
8928 const bool RhsConstant = IsRHSIntegralLiteral;
8929 Expr *Const = RhsConstant ? RHS : LHS;
8930 Expr *Other = RhsConstant ? LHS : RHS;
8931 const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
8932
8933 // Check whether an integer constant comparison results in a value
8934 // of 'true' or 'false'.
8935
8936 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
8937 return AnalyzeImpConvsInComparison(S, E);
8938
8939 if (DiagnoseOutOfRangeComparison(S, E, Const, Other, Value, RhsConstant))
8940 return AnalyzeImpConvsInComparison(S, E);
8941 }
8942 }
8943
8944 if (!T->hasUnsignedIntegerRepresentation()) {
8945 // We don't do anything special if this isn't an unsigned integral
8946 // comparison: we're only interested in integral comparisons, and
8947 // signed comparisons only happen in cases we don't care to warn about.
John McCallcc7e5bf2010-05-06 08:58:33 +00008948 return AnalyzeImpConvsInComparison(S, E);
Roman Lebedevbd1fc222017-10-12 20:16:51 +00008949 }
8950
8951 LHS = LHS->IgnoreParenImpCasts();
8952 RHS = RHS->IgnoreParenImpCasts();
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00008953
John McCallcc7e5bf2010-05-06 08:58:33 +00008954 // Check to see if one of the (unmodified) operands is of different
8955 // signedness.
8956 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00008957 if (LHS->getType()->hasSignedIntegerRepresentation()) {
8958 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00008959 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00008960 signedOperand = LHS;
8961 unsignedOperand = RHS;
8962 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
8963 signedOperand = RHS;
8964 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00008965 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00008966 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00008967 }
8968
John McCallcc7e5bf2010-05-06 08:58:33 +00008969 // Otherwise, calculate the effective range of the signed operand.
8970 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00008971
John McCallcc7e5bf2010-05-06 08:58:33 +00008972 // Go ahead and analyze implicit conversions in the operands. Note
8973 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00008974 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
8975 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00008976
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00008977 // If the signed range is non-negative, -Wsign-compare won't fire.
John McCallcc7e5bf2010-05-06 08:58:33 +00008978 if (signedRange.NonNegative)
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00008979 return;
John McCallca01b222010-01-04 23:21:16 +00008980
8981 // For (in)equality comparisons, if the unsigned operand is a
8982 // constant which cannot collide with a overflowed signed operand,
8983 // then reinterpreting the signed operand as unsigned will not
8984 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00008985 if (E->isEqualityOp()) {
8986 unsigned comparisonWidth = S.Context.getIntWidth(T);
8987 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00008988
John McCallcc7e5bf2010-05-06 08:58:33 +00008989 // We should never be unable to prove that the unsigned operand is
8990 // non-negative.
8991 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
8992
8993 if (unsignedRange.Width < comparisonWidth)
8994 return;
8995 }
8996
Douglas Gregorbfb4a212012-05-01 01:53:49 +00008997 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
8998 S.PDiag(diag::warn_mixed_sign_comparison)
8999 << LHS->getType() << RHS->getType()
9000 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00009001}
9002
John McCall1f425642010-11-11 03:21:53 +00009003/// Analyzes an attempt to assign the given value to a bitfield.
9004///
9005/// Returns true if there was something fishy about the attempt.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009006bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
9007 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00009008 assert(Bitfield->isBitField());
9009 if (Bitfield->isInvalidDecl())
9010 return false;
9011
John McCalldeebbcf2010-11-11 05:33:51 +00009012 // White-list bool bitfields.
Reid Klecknerad425622016-11-16 23:40:00 +00009013 QualType BitfieldType = Bitfield->getType();
9014 if (BitfieldType->isBooleanType())
9015 return false;
9016
9017 if (BitfieldType->isEnumeralType()) {
9018 EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
9019 // If the underlying enum type was not explicitly specified as an unsigned
9020 // type and the enum contain only positive values, MSVC++ will cause an
9021 // inconsistency by storing this as a signed type.
9022 if (S.getLangOpts().CPlusPlus11 &&
9023 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
9024 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
9025 BitfieldEnumDecl->getNumNegativeBits() == 0) {
9026 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
9027 << BitfieldEnumDecl->getNameAsString();
9028 }
9029 }
9030
John McCalldeebbcf2010-11-11 05:33:51 +00009031 if (Bitfield->getType()->isBooleanType())
9032 return false;
9033
Douglas Gregor789adec2011-02-04 13:09:01 +00009034 // Ignore value- or type-dependent expressions.
9035 if (Bitfield->getBitWidth()->isValueDependent() ||
9036 Bitfield->getBitWidth()->isTypeDependent() ||
9037 Init->isValueDependent() ||
9038 Init->isTypeDependent())
9039 return false;
9040
John McCall1f425642010-11-11 03:21:53 +00009041 Expr *OriginalInit = Init->IgnoreParenImpCasts();
Reid Kleckner329f24d2017-03-14 18:01:02 +00009042 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00009043
Richard Smith5fab0c92011-12-28 19:48:30 +00009044 llvm::APSInt Value;
Reid Kleckner329f24d2017-03-14 18:01:02 +00009045 if (!OriginalInit->EvaluateAsInt(Value, S.Context,
9046 Expr::SE_AllowSideEffects)) {
9047 // The RHS is not constant. If the RHS has an enum type, make sure the
9048 // bitfield is wide enough to hold all the values of the enum without
9049 // truncation.
9050 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
9051 EnumDecl *ED = EnumTy->getDecl();
9052 bool SignedBitfield = BitfieldType->isSignedIntegerType();
9053
9054 // Enum types are implicitly signed on Windows, so check if there are any
9055 // negative enumerators to see if the enum was intended to be signed or
9056 // not.
9057 bool SignedEnum = ED->getNumNegativeBits() > 0;
9058
9059 // Check for surprising sign changes when assigning enum values to a
9060 // bitfield of different signedness. If the bitfield is signed and we
9061 // have exactly the right number of bits to store this unsigned enum,
9062 // suggest changing the enum to an unsigned type. This typically happens
9063 // on Windows where unfixed enums always use an underlying type of 'int'.
9064 unsigned DiagID = 0;
9065 if (SignedEnum && !SignedBitfield) {
9066 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
9067 } else if (SignedBitfield && !SignedEnum &&
9068 ED->getNumPositiveBits() == FieldWidth) {
9069 DiagID = diag::warn_signed_bitfield_enum_conversion;
9070 }
9071
9072 if (DiagID) {
9073 S.Diag(InitLoc, DiagID) << Bitfield << ED;
9074 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
9075 SourceRange TypeRange =
9076 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
9077 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
9078 << SignedEnum << TypeRange;
9079 }
9080
9081 // Compute the required bitwidth. If the enum has negative values, we need
9082 // one more bit than the normal number of positive bits to represent the
9083 // sign bit.
9084 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
9085 ED->getNumNegativeBits())
9086 : ED->getNumPositiveBits();
9087
9088 // Check the bitwidth.
9089 if (BitsNeeded > FieldWidth) {
9090 Expr *WidthExpr = Bitfield->getBitWidth();
9091 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
9092 << Bitfield << ED;
9093 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
9094 << BitsNeeded << ED << WidthExpr->getSourceRange();
9095 }
9096 }
9097
John McCall1f425642010-11-11 03:21:53 +00009098 return false;
Reid Kleckner329f24d2017-03-14 18:01:02 +00009099 }
John McCall1f425642010-11-11 03:21:53 +00009100
John McCall1f425642010-11-11 03:21:53 +00009101 unsigned OriginalWidth = Value.getBitWidth();
John McCall1f425642010-11-11 03:21:53 +00009102
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +00009103 if (!Value.isSigned() || Value.isNegative())
Richard Trieu7561ed02016-08-05 02:39:30 +00009104 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +00009105 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
9106 OriginalWidth = Value.getMinSignedBits();
Richard Trieu7561ed02016-08-05 02:39:30 +00009107
John McCall1f425642010-11-11 03:21:53 +00009108 if (OriginalWidth <= FieldWidth)
9109 return false;
9110
Eli Friedmanc267a322012-01-26 23:11:39 +00009111 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00009112 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Reid Klecknerad425622016-11-16 23:40:00 +00009113 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00009114
Eli Friedmanc267a322012-01-26 23:11:39 +00009115 // Check whether the stored value is equal to the original value.
9116 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00009117 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00009118 return false;
9119
Eli Friedmanc267a322012-01-26 23:11:39 +00009120 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00009121 // therefore don't strictly fit into a signed bitfield of width 1.
9122 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00009123 return false;
9124
John McCall1f425642010-11-11 03:21:53 +00009125 std::string PrettyValue = Value.toString(10);
9126 std::string PrettyTrunc = TruncatedValue.toString(10);
9127
9128 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
9129 << PrettyValue << PrettyTrunc << OriginalInit->getType()
9130 << Init->getSourceRange();
9131
9132 return true;
9133}
9134
John McCalld2a53122010-11-09 23:24:47 +00009135/// Analyze the given simple or compound assignment for warning-worthy
9136/// operations.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009137void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00009138 // Just recurse on the LHS.
9139 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
9140
9141 // We want to recurse on the RHS as normal unless we're assigning to
9142 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00009143 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009144 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00009145 E->getOperatorLoc())) {
9146 // Recurse, ignoring any implicit conversions on the RHS.
9147 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
9148 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00009149 }
9150 }
9151
9152 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
9153}
9154
John McCall263a48b2010-01-04 23:31:57 +00009155/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009156void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
9157 SourceLocation CContext, unsigned diag,
9158 bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00009159 if (pruneControlFlow) {
9160 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9161 S.PDiag(diag)
9162 << SourceType << T << E->getSourceRange()
9163 << SourceRange(CContext));
9164 return;
9165 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00009166 S.Diag(E->getExprLoc(), diag)
9167 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
9168}
9169
Chandler Carruth7f3654f2011-04-05 06:47:57 +00009170/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009171void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
9172 unsigned diag, bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00009173 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00009174}
9175
Richard Trieube234c32016-04-21 21:04:55 +00009176
9177/// Diagnose an implicit cast from a floating point value to an integer value.
9178void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
9179
9180 SourceLocation CContext) {
9181 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
Richard Smith51ec0cf2017-02-21 01:17:38 +00009182 const bool PruneWarnings = S.inTemplateInstantiation();
Richard Trieube234c32016-04-21 21:04:55 +00009183
9184 Expr *InnerE = E->IgnoreParenImpCasts();
9185 // We also want to warn on, e.g., "int i = -1.234"
9186 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
9187 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
9188 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
9189
9190 const bool IsLiteral =
9191 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
9192
9193 llvm::APFloat Value(0.0);
9194 bool IsConstant =
9195 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
9196 if (!IsConstant) {
Richard Trieu891f0f12016-04-22 22:14:32 +00009197 return DiagnoseImpCast(S, E, T, CContext,
9198 diag::warn_impcast_float_integer, PruneWarnings);
Richard Trieube234c32016-04-21 21:04:55 +00009199 }
9200
Chandler Carruth016ef402011-04-10 08:36:24 +00009201 bool isExact = false;
Richard Trieube234c32016-04-21 21:04:55 +00009202
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00009203 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
9204 T->hasUnsignedIntegerRepresentation());
Richard Trieube234c32016-04-21 21:04:55 +00009205 if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero,
9206 &isExact) == llvm::APFloat::opOK &&
Richard Trieu891f0f12016-04-22 22:14:32 +00009207 isExact) {
Richard Trieube234c32016-04-21 21:04:55 +00009208 if (IsLiteral) return;
9209 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
9210 PruneWarnings);
9211 }
9212
9213 unsigned DiagID = 0;
Richard Trieu891f0f12016-04-22 22:14:32 +00009214 if (IsLiteral) {
Richard Trieube234c32016-04-21 21:04:55 +00009215 // Warn on floating point literal to integer.
9216 DiagID = diag::warn_impcast_literal_float_to_integer;
9217 } else if (IntegerValue == 0) {
9218 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
9219 return DiagnoseImpCast(S, E, T, CContext,
9220 diag::warn_impcast_float_integer, PruneWarnings);
9221 }
9222 // Warn on non-zero to zero conversion.
9223 DiagID = diag::warn_impcast_float_to_integer_zero;
9224 } else {
9225 if (IntegerValue.isUnsigned()) {
9226 if (!IntegerValue.isMaxValue()) {
9227 return DiagnoseImpCast(S, E, T, CContext,
9228 diag::warn_impcast_float_integer, PruneWarnings);
9229 }
9230 } else { // IntegerValue.isSigned()
9231 if (!IntegerValue.isMaxSignedValue() &&
9232 !IntegerValue.isMinSignedValue()) {
9233 return DiagnoseImpCast(S, E, T, CContext,
9234 diag::warn_impcast_float_integer, PruneWarnings);
9235 }
9236 }
9237 // Warn on evaluatable floating point expression to integer conversion.
9238 DiagID = diag::warn_impcast_float_to_integer;
9239 }
Chandler Carruth016ef402011-04-10 08:36:24 +00009240
Eli Friedman07185912013-08-29 23:44:43 +00009241 // FIXME: Force the precision of the source value down so we don't print
9242 // digits which are usually useless (we don't really care here if we
9243 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
9244 // would automatically print the shortest representation, but it's a bit
9245 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00009246 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00009247 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
9248 precision = (precision * 59 + 195) / 196;
9249 Value.toString(PrettySourceValue, precision);
9250
David Blaikie9b88cc02012-05-15 17:18:27 +00009251 SmallString<16> PrettyTargetValue;
Richard Trieube234c32016-04-21 21:04:55 +00009252 if (IsBool)
Aaron Ballmandbc441e2015-12-30 14:26:07 +00009253 PrettyTargetValue = Value.isZero() ? "false" : "true";
David Blaikie7555b6a2012-05-15 16:56:36 +00009254 else
David Blaikie9b88cc02012-05-15 17:18:27 +00009255 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00009256
Richard Trieube234c32016-04-21 21:04:55 +00009257 if (PruneWarnings) {
9258 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9259 S.PDiag(DiagID)
9260 << E->getType() << T.getUnqualifiedType()
9261 << PrettySourceValue << PrettyTargetValue
9262 << E->getSourceRange() << SourceRange(CContext));
9263 } else {
9264 S.Diag(E->getExprLoc(), DiagID)
9265 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
9266 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
9267 }
Chandler Carruth016ef402011-04-10 08:36:24 +00009268}
9269
John McCall18a2c2c2010-11-09 22:22:12 +00009270std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
9271 if (!Range.Width) return "0";
9272
9273 llvm::APSInt ValueInRange = Value;
9274 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00009275 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00009276 return ValueInRange.toString(10);
9277}
9278
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009279bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009280 if (!isa<ImplicitCastExpr>(Ex))
9281 return false;
9282
9283 Expr *InnerE = Ex->IgnoreParenImpCasts();
9284 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
9285 const Type *Source =
9286 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
9287 if (Target->isDependentType())
9288 return false;
9289
9290 const BuiltinType *FloatCandidateBT =
9291 dyn_cast<BuiltinType>(ToBool ? Source : Target);
9292 const Type *BoolCandidateType = ToBool ? Target : Source;
9293
9294 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
9295 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
9296}
9297
9298void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
9299 SourceLocation CC) {
9300 unsigned NumArgs = TheCall->getNumArgs();
9301 for (unsigned i = 0; i < NumArgs; ++i) {
9302 Expr *CurrA = TheCall->getArg(i);
9303 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
9304 continue;
9305
9306 bool IsSwapped = ((i > 0) &&
9307 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
9308 IsSwapped |= ((i < (NumArgs - 1)) &&
9309 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
9310 if (IsSwapped) {
9311 // Warn on this floating-point to bool conversion.
9312 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
9313 CurrA->getType(), CC,
9314 diag::warn_impcast_floating_point_to_bool);
9315 }
9316 }
9317}
9318
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009319void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) {
Richard Trieu5b993502014-10-15 03:42:06 +00009320 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
9321 E->getExprLoc()))
9322 return;
9323
Richard Trieu09d6b802016-01-08 23:35:06 +00009324 // Don't warn on functions which have return type nullptr_t.
9325 if (isa<CallExpr>(E))
9326 return;
9327
Richard Trieu5b993502014-10-15 03:42:06 +00009328 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
9329 const Expr::NullPointerConstantKind NullKind =
9330 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
9331 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
9332 return;
9333
9334 // Return if target type is a safe conversion.
9335 if (T->isAnyPointerType() || T->isBlockPointerType() ||
9336 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
9337 return;
9338
9339 SourceLocation Loc = E->getSourceRange().getBegin();
9340
Richard Trieu0a5e1662016-02-13 00:58:53 +00009341 // Venture through the macro stacks to get to the source of macro arguments.
9342 // The new location is a better location than the complete location that was
9343 // passed in.
9344 while (S.SourceMgr.isMacroArgExpansion(Loc))
9345 Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc);
9346
9347 while (S.SourceMgr.isMacroArgExpansion(CC))
9348 CC = S.SourceMgr.getImmediateMacroCallerLoc(CC);
9349
Richard Trieu5b993502014-10-15 03:42:06 +00009350 // __null is usually wrapped in a macro. Go up a macro if that is the case.
Richard Trieu0a5e1662016-02-13 00:58:53 +00009351 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
9352 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
9353 Loc, S.SourceMgr, S.getLangOpts());
9354 if (MacroName == "NULL")
9355 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
Richard Trieu5b993502014-10-15 03:42:06 +00009356 }
9357
9358 // Only warn if the null and context location are in the same macro expansion.
9359 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
9360 return;
9361
9362 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
9363 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
9364 << FixItHint::CreateReplacement(Loc,
9365 S.getFixItZeroLiteralForType(T, Loc));
9366}
9367
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009368void checkObjCArrayLiteral(Sema &S, QualType TargetType,
9369 ObjCArrayLiteral *ArrayLiteral);
9370void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
9371 ObjCDictionaryLiteral *DictionaryLiteral);
Douglas Gregor5054cb02015-07-07 03:58:22 +00009372
9373/// Check a single element within a collection literal against the
9374/// target element type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009375void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType,
9376 Expr *Element, unsigned ElementKind) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00009377 // Skip a bitcast to 'id' or qualified 'id'.
9378 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
9379 if (ICE->getCastKind() == CK_BitCast &&
9380 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
9381 Element = ICE->getSubExpr();
9382 }
9383
9384 QualType ElementType = Element->getType();
9385 ExprResult ElementResult(Element);
9386 if (ElementType->getAs<ObjCObjectPointerType>() &&
9387 S.CheckSingleAssignmentConstraints(TargetElementType,
9388 ElementResult,
9389 false, false)
9390 != Sema::Compatible) {
9391 S.Diag(Element->getLocStart(),
9392 diag::warn_objc_collection_literal_element)
9393 << ElementType << ElementKind << TargetElementType
9394 << Element->getSourceRange();
9395 }
9396
9397 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
9398 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
9399 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
9400 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
9401}
9402
9403/// Check an Objective-C array literal being converted to the given
9404/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009405void checkObjCArrayLiteral(Sema &S, QualType TargetType,
9406 ObjCArrayLiteral *ArrayLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00009407 if (!S.NSArrayDecl)
9408 return;
9409
9410 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
9411 if (!TargetObjCPtr)
9412 return;
9413
9414 if (TargetObjCPtr->isUnspecialized() ||
9415 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
9416 != S.NSArrayDecl->getCanonicalDecl())
9417 return;
9418
9419 auto TypeArgs = TargetObjCPtr->getTypeArgs();
9420 if (TypeArgs.size() != 1)
9421 return;
9422
9423 QualType TargetElementType = TypeArgs[0];
9424 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
9425 checkObjCCollectionLiteralElement(S, TargetElementType,
9426 ArrayLiteral->getElement(I),
9427 0);
9428 }
9429}
9430
9431/// Check an Objective-C dictionary literal being converted to the given
9432/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009433void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
9434 ObjCDictionaryLiteral *DictionaryLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00009435 if (!S.NSDictionaryDecl)
9436 return;
9437
9438 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
9439 if (!TargetObjCPtr)
9440 return;
9441
9442 if (TargetObjCPtr->isUnspecialized() ||
9443 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
9444 != S.NSDictionaryDecl->getCanonicalDecl())
9445 return;
9446
9447 auto TypeArgs = TargetObjCPtr->getTypeArgs();
9448 if (TypeArgs.size() != 2)
9449 return;
9450
9451 QualType TargetKeyType = TypeArgs[0];
9452 QualType TargetObjectType = TypeArgs[1];
9453 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
9454 auto Element = DictionaryLiteral->getKeyValueElement(I);
9455 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
9456 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
9457 }
9458}
9459
Richard Trieufc404c72016-02-05 23:02:38 +00009460// Helper function to filter out cases for constant width constant conversion.
9461// Don't warn on char array initialization or for non-decimal values.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009462bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
9463 SourceLocation CC) {
Richard Trieufc404c72016-02-05 23:02:38 +00009464 // If initializing from a constant, and the constant starts with '0',
9465 // then it is a binary, octal, or hexadecimal. Allow these constants
9466 // to fill all the bits, even if there is a sign change.
9467 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
9468 const char FirstLiteralCharacter =
9469 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
9470 if (FirstLiteralCharacter == '0')
9471 return false;
9472 }
9473
9474 // If the CC location points to a '{', and the type is char, then assume
9475 // assume it is an array initialization.
9476 if (CC.isValid() && T->isCharType()) {
9477 const char FirstContextCharacter =
9478 S.getSourceManager().getCharacterData(CC)[0];
9479 if (FirstContextCharacter == '{')
9480 return false;
9481 }
9482
9483 return true;
9484}
9485
John McCallcc7e5bf2010-05-06 08:58:33 +00009486void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00009487 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009488 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00009489
John McCallcc7e5bf2010-05-06 08:58:33 +00009490 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
9491 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
9492 if (Source == Target) return;
9493 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00009494
Chandler Carruthc22845a2011-07-26 05:40:03 +00009495 // If the conversion context location is invalid don't complain. We also
9496 // don't want to emit a warning if the issue occurs from the expansion of
9497 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
9498 // delay this check as long as possible. Once we detect we are in that
9499 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009500 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00009501 return;
9502
Richard Trieu021baa32011-09-23 20:10:00 +00009503 // Diagnose implicit casts to bool.
9504 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
9505 if (isa<StringLiteral>(E))
9506 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00009507 // and expressions, for instance, assert(0 && "error here"), are
9508 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00009509 return DiagnoseImpCast(S, E, T, CC,
9510 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00009511 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
9512 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
9513 // This covers the literal expressions that evaluate to Objective-C
9514 // objects.
9515 return DiagnoseImpCast(S, E, T, CC,
9516 diag::warn_impcast_objective_c_literal_to_bool);
9517 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00009518 if (Source->isPointerType() || Source->canDecayToPointerType()) {
9519 // Warn on pointer to bool conversion that is always true.
9520 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
9521 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00009522 }
Richard Trieu021baa32011-09-23 20:10:00 +00009523 }
John McCall263a48b2010-01-04 23:31:57 +00009524
Douglas Gregor5054cb02015-07-07 03:58:22 +00009525 // Check implicit casts from Objective-C collection literals to specialized
9526 // collection types, e.g., NSArray<NSString *> *.
9527 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
9528 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
9529 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
9530 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
9531
John McCall263a48b2010-01-04 23:31:57 +00009532 // Strip vector types.
9533 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009534 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009535 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009536 return;
John McCallacf0ee52010-10-08 02:01:28 +00009537 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009538 }
Chris Lattneree7286f2011-06-14 04:51:15 +00009539
9540 // If the vector cast is cast between two vectors of the same size, it is
9541 // a bitcast, not a conversion.
9542 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
9543 return;
John McCall263a48b2010-01-04 23:31:57 +00009544
9545 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
9546 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
9547 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00009548 if (auto VecTy = dyn_cast<VectorType>(Target))
9549 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00009550
9551 // Strip complex types.
9552 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009553 if (!isa<ComplexType>(Target)) {
Tim Northover02416372017-08-08 23:18:05 +00009554 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009555 return;
9556
Tim Northover02416372017-08-08 23:18:05 +00009557 return DiagnoseImpCast(S, E, T, CC,
9558 S.getLangOpts().CPlusPlus
9559 ? diag::err_impcast_complex_scalar
9560 : diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009561 }
John McCall263a48b2010-01-04 23:31:57 +00009562
9563 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
9564 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
9565 }
9566
9567 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
9568 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
9569
9570 // If the source is floating point...
9571 if (SourceBT && SourceBT->isFloatingPoint()) {
9572 // ...and the target is floating point...
9573 if (TargetBT && TargetBT->isFloatingPoint()) {
9574 // ...then warn if we're dropping FP rank.
9575
9576 // Builtin FP kinds are ordered by increasing FP rank.
9577 if (SourceBT->getKind() > TargetBT->getKind()) {
9578 // Don't warn about float constants that are precisely
9579 // representable in the target type.
9580 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00009581 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00009582 // Value might be a float, a float vector, or a float complex.
9583 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00009584 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
9585 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00009586 return;
9587 }
9588
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009589 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009590 return;
9591
John McCallacf0ee52010-10-08 02:01:28 +00009592 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
George Burgess IV148e0d32015-10-29 00:28:52 +00009593 }
9594 // ... or possibly if we're increasing rank, too
9595 else if (TargetBT->getKind() > SourceBT->getKind()) {
9596 if (S.SourceMgr.isInSystemMacro(CC))
9597 return;
9598
9599 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
John McCall263a48b2010-01-04 23:31:57 +00009600 }
9601 return;
9602 }
9603
Richard Trieube234c32016-04-21 21:04:55 +00009604 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00009605 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009606 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009607 return;
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00009608
Richard Trieube234c32016-04-21 21:04:55 +00009609 DiagnoseFloatingImpCast(S, E, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00009610 }
John McCall263a48b2010-01-04 23:31:57 +00009611
Richard Smith54894fd2015-12-30 01:06:52 +00009612 // Detect the case where a call result is converted from floating-point to
9613 // to bool, and the final argument to the call is converted from bool, to
9614 // discover this typo:
9615 //
9616 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
9617 //
9618 // FIXME: This is an incredibly special case; is there some more general
9619 // way to detect this class of misplaced-parentheses bug?
9620 if (Target->isBooleanType() && isa<CallExpr>(E)) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009621 // Check last argument of function call to see if it is an
9622 // implicit cast from a type matching the type the result
9623 // is being cast to.
9624 CallExpr *CEx = cast<CallExpr>(E);
Richard Smith54894fd2015-12-30 01:06:52 +00009625 if (unsigned NumArgs = CEx->getNumArgs()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009626 Expr *LastA = CEx->getArg(NumArgs - 1);
9627 Expr *InnerE = LastA->IgnoreParenImpCasts();
Richard Smith54894fd2015-12-30 01:06:52 +00009628 if (isa<ImplicitCastExpr>(LastA) &&
9629 InnerE->getType()->isBooleanType()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009630 // Warn on this floating-point to bool conversion
9631 DiagnoseImpCast(S, E, T, CC,
9632 diag::warn_impcast_floating_point_to_bool);
9633 }
9634 }
9635 }
John McCall263a48b2010-01-04 23:31:57 +00009636 return;
9637 }
9638
Richard Trieu5b993502014-10-15 03:42:06 +00009639 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +00009640
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +00009641 S.DiscardMisalignedMemberAddress(Target, E);
9642
David Blaikie9366d2b2012-06-19 21:19:06 +00009643 if (!Source->isIntegerType() || !Target->isIntegerType())
9644 return;
9645
David Blaikie7555b6a2012-05-15 16:56:36 +00009646 // TODO: remove this early return once the false positives for constant->bool
9647 // in templates, macros, etc, are reduced or removed.
9648 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
9649 return;
9650
John McCallcc7e5bf2010-05-06 08:58:33 +00009651 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00009652 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00009653
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009654 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00009655 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009656 // TODO: this should happen for bitfield stores, too.
9657 llvm::APSInt Value(32);
Richard Trieudcb55572016-01-29 23:51:16 +00009658 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009659 if (S.SourceMgr.isInSystemMacro(CC))
9660 return;
9661
John McCall18a2c2c2010-11-09 22:22:12 +00009662 std::string PrettySourceValue = Value.toString(10);
9663 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009664
Ted Kremenek33ba9952011-10-22 02:37:33 +00009665 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9666 S.PDiag(diag::warn_impcast_integer_precision_constant)
9667 << PrettySourceValue << PrettyTargetValue
9668 << E->getType() << T << E->getSourceRange()
9669 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00009670 return;
9671 }
9672
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009673 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
9674 if (S.SourceMgr.isInSystemMacro(CC))
9675 return;
9676
David Blaikie9455da02012-04-12 22:40:54 +00009677 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00009678 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
9679 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00009680 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00009681 }
9682
Richard Trieudcb55572016-01-29 23:51:16 +00009683 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
9684 SourceRange.NonNegative && Source->isSignedIntegerType()) {
9685 // Warn when doing a signed to signed conversion, warn if the positive
9686 // source value is exactly the width of the target type, which will
9687 // cause a negative value to be stored.
9688
9689 llvm::APSInt Value;
Richard Trieufc404c72016-02-05 23:02:38 +00009690 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
9691 !S.SourceMgr.isInSystemMacro(CC)) {
9692 if (isSameWidthConstantConversion(S, E, T, CC)) {
9693 std::string PrettySourceValue = Value.toString(10);
9694 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Richard Trieudcb55572016-01-29 23:51:16 +00009695
Richard Trieufc404c72016-02-05 23:02:38 +00009696 S.DiagRuntimeBehavior(
9697 E->getExprLoc(), E,
9698 S.PDiag(diag::warn_impcast_integer_precision_constant)
9699 << PrettySourceValue << PrettyTargetValue << E->getType() << T
9700 << E->getSourceRange() << clang::SourceRange(CC));
9701 return;
Richard Trieudcb55572016-01-29 23:51:16 +00009702 }
9703 }
Richard Trieufc404c72016-02-05 23:02:38 +00009704
Richard Trieudcb55572016-01-29 23:51:16 +00009705 // Fall through for non-constants to give a sign conversion warning.
9706 }
9707
John McCallcc7e5bf2010-05-06 08:58:33 +00009708 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
9709 (!TargetRange.NonNegative && SourceRange.NonNegative &&
9710 SourceRange.Width == TargetRange.Width)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009711 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009712 return;
9713
John McCallcc7e5bf2010-05-06 08:58:33 +00009714 unsigned DiagID = diag::warn_impcast_integer_sign;
9715
9716 // Traditionally, gcc has warned about this under -Wsign-compare.
9717 // We also want to warn about it in -Wconversion.
9718 // So if -Wconversion is off, use a completely identical diagnostic
9719 // in the sign-compare group.
9720 // The conditional-checking code will
9721 if (ICContext) {
9722 DiagID = diag::warn_impcast_integer_sign_conditional;
9723 *ICContext = true;
9724 }
9725
John McCallacf0ee52010-10-08 02:01:28 +00009726 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00009727 }
9728
Douglas Gregora78f1932011-02-22 02:45:07 +00009729 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00009730 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
9731 // type, to give us better diagnostics.
9732 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00009733 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00009734 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9735 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
9736 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
9737 SourceType = S.Context.getTypeDeclType(Enum);
9738 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
9739 }
9740 }
9741
Douglas Gregora78f1932011-02-22 02:45:07 +00009742 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
9743 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00009744 if (SourceEnum->getDecl()->hasNameForLinkage() &&
9745 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009746 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009747 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009748 return;
9749
Douglas Gregor364f7db2011-03-12 00:14:31 +00009750 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00009751 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009752 }
John McCall263a48b2010-01-04 23:31:57 +00009753}
9754
David Blaikie18e9ac72012-05-15 21:57:38 +00009755void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9756 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009757
9758void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00009759 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009760 E = E->IgnoreParenImpCasts();
9761
9762 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00009763 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009764
John McCallacf0ee52010-10-08 02:01:28 +00009765 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009766 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00009767 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00009768}
9769
David Blaikie18e9ac72012-05-15 21:57:38 +00009770void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9771 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00009772 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00009773
9774 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00009775 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
9776 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00009777
9778 // If -Wconversion would have warned about either of the candidates
9779 // for a signedness conversion to the context type...
9780 if (!Suspicious) return;
9781
9782 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009783 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00009784 return;
9785
John McCallcc7e5bf2010-05-06 08:58:33 +00009786 // ...then check whether it would have warned about either of the
9787 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00009788 if (E->getType() == T) return;
9789
9790 Suspicious = false;
9791 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
9792 E->getType(), CC, &Suspicious);
9793 if (!Suspicious)
9794 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00009795 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00009796}
9797
Richard Trieu65724892014-11-15 06:37:39 +00009798/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9799/// Input argument E is a logical expression.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009800void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
Richard Trieu65724892014-11-15 06:37:39 +00009801 if (S.getLangOpts().Bool)
9802 return;
9803 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
9804}
9805
John McCallcc7e5bf2010-05-06 08:58:33 +00009806/// AnalyzeImplicitConversions - Find and report any interesting
9807/// implicit conversions in the given expression. There are a couple
9808/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00009809void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00009810 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00009811 Expr *E = OrigE->IgnoreParenImpCasts();
9812
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00009813 if (E->isTypeDependent() || E->isValueDependent())
9814 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00009815
John McCallcc7e5bf2010-05-06 08:58:33 +00009816 // For conditional operators, we analyze the arguments as if they
9817 // were being fed directly into the output.
9818 if (isa<ConditionalOperator>(E)) {
9819 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00009820 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009821 return;
9822 }
9823
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009824 // Check implicit argument conversions for function calls.
9825 if (CallExpr *Call = dyn_cast<CallExpr>(E))
9826 CheckImplicitArgumentConversions(S, Call, CC);
9827
John McCallcc7e5bf2010-05-06 08:58:33 +00009828 // Go ahead and check any implicit conversions we might have skipped.
9829 // The non-canonical typecheck is just an optimization;
9830 // CheckImplicitConversion will filter out dead implicit conversions.
9831 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00009832 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009833
9834 // Now continue drilling into this expression.
Richard Smithd7bed4d2015-11-22 02:57:17 +00009835
9836 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
9837 // The bound subexpressions in a PseudoObjectExpr are not reachable
9838 // as transitive children.
9839 // FIXME: Use a more uniform representation for this.
9840 for (auto *SE : POE->semantics())
9841 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
9842 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00009843 }
Richard Smithd7bed4d2015-11-22 02:57:17 +00009844
John McCallcc7e5bf2010-05-06 08:58:33 +00009845 // Skip past explicit casts.
9846 if (isa<ExplicitCastExpr>(E)) {
9847 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00009848 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009849 }
9850
John McCalld2a53122010-11-09 23:24:47 +00009851 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9852 // Do a somewhat different check with comparison operators.
9853 if (BO->isComparisonOp())
9854 return AnalyzeComparison(S, BO);
9855
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009856 // And with simple assignments.
9857 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00009858 return AnalyzeAssignment(S, BO);
9859 }
John McCallcc7e5bf2010-05-06 08:58:33 +00009860
9861 // These break the otherwise-useful invariant below. Fortunately,
9862 // we don't really need to recurse into them, because any internal
9863 // expressions should have been analyzed already when they were
9864 // built into statements.
9865 if (isa<StmtExpr>(E)) return;
9866
9867 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00009868 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00009869
9870 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00009871 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00009872 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00009873 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Benjamin Kramer642f1732015-07-02 21:03:14 +00009874 for (Stmt *SubStmt : E->children()) {
9875 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00009876 if (!ChildExpr)
9877 continue;
9878
Richard Trieu955231d2014-01-25 01:10:35 +00009879 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00009880 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00009881 // Ignore checking string literals that are in logical and operators.
9882 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00009883 continue;
9884 AnalyzeImplicitConversions(S, ChildExpr, CC);
9885 }
Richard Trieu791b86e2014-11-19 06:08:18 +00009886
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009887 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +00009888 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
9889 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00009890 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +00009891
9892 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
9893 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00009894 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009895 }
Richard Trieu791b86e2014-11-19 06:08:18 +00009896
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009897 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
9898 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +00009899 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009900}
9901
9902} // end anonymous namespace
9903
Anastasia Stulova0df4ac32016-11-14 17:39:58 +00009904/// Diagnose integer type and any valid implicit convertion to it.
9905static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
9906 // Taking into account implicit conversions,
9907 // allow any integer.
9908 if (!E->getType()->isIntegerType()) {
9909 S.Diag(E->getLocStart(),
9910 diag::err_opencl_enqueue_kernel_invalid_local_size_type);
9911 return true;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00009912 }
Anastasia Stulova0df4ac32016-11-14 17:39:58 +00009913 // Potentially emit standard warnings for implicit conversions if enabled
9914 // using -Wconversion.
9915 CheckImplicitConversion(S, E, IntT, E->getLocStart());
9916 return false;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00009917}
9918
Richard Trieuc1888e02014-06-28 23:25:37 +00009919// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
9920// Returns true when emitting a warning about taking the address of a reference.
9921static bool CheckForReference(Sema &SemaRef, const Expr *E,
Benjamin Kramer7320b992016-06-15 14:20:56 +00009922 const PartialDiagnostic &PD) {
Richard Trieuc1888e02014-06-28 23:25:37 +00009923 E = E->IgnoreParenImpCasts();
9924
9925 const FunctionDecl *FD = nullptr;
9926
9927 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9928 if (!DRE->getDecl()->getType()->isReferenceType())
9929 return false;
9930 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9931 if (!M->getMemberDecl()->getType()->isReferenceType())
9932 return false;
9933 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +00009934 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +00009935 return false;
9936 FD = Call->getDirectCallee();
9937 } else {
9938 return false;
9939 }
9940
9941 SemaRef.Diag(E->getExprLoc(), PD);
9942
9943 // If possible, point to location of function.
9944 if (FD) {
9945 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
9946 }
9947
9948 return true;
9949}
9950
Richard Trieu4cbff5c2014-08-08 22:41:43 +00009951// Returns true if the SourceLocation is expanded from any macro body.
9952// Returns false if the SourceLocation is invalid, is from not in a macro
9953// expansion, or is from expanded from a top-level macro argument.
9954static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
9955 if (Loc.isInvalid())
9956 return false;
9957
9958 while (Loc.isMacroID()) {
9959 if (SM.isMacroBodyExpansion(Loc))
9960 return true;
9961 Loc = SM.getImmediateMacroCallerLoc(Loc);
9962 }
9963
9964 return false;
9965}
9966
Richard Trieu3bb8b562014-02-26 02:36:06 +00009967/// \brief Diagnose pointers that are always non-null.
9968/// \param E the expression containing the pointer
9969/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
9970/// compared to a null pointer
9971/// \param IsEqual True when the comparison is equal to a null pointer
9972/// \param Range Extra SourceRange to highlight in the diagnostic
9973void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
9974 Expr::NullPointerConstantKind NullKind,
9975 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00009976 if (!E)
9977 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009978
9979 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +00009980 if (E->getExprLoc().isMacroID()) {
9981 const SourceManager &SM = getSourceManager();
9982 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
9983 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +00009984 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +00009985 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00009986 E = E->IgnoreImpCasts();
9987
9988 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
9989
Richard Trieuf7432752014-06-06 21:39:26 +00009990 if (isa<CXXThisExpr>(E)) {
9991 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
9992 : diag::warn_this_bool_conversion;
9993 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
9994 return;
9995 }
9996
Richard Trieu3bb8b562014-02-26 02:36:06 +00009997 bool IsAddressOf = false;
9998
9999 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
10000 if (UO->getOpcode() != UO_AddrOf)
10001 return;
10002 IsAddressOf = true;
10003 E = UO->getSubExpr();
10004 }
10005
Richard Trieuc1888e02014-06-28 23:25:37 +000010006 if (IsAddressOf) {
10007 unsigned DiagID = IsCompare
10008 ? diag::warn_address_of_reference_null_compare
10009 : diag::warn_address_of_reference_bool_conversion;
10010 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
10011 << IsEqual;
10012 if (CheckForReference(*this, E, PD)) {
10013 return;
10014 }
10015 }
10016
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010017 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
10018 bool IsParam = isa<NonNullAttr>(NonnullAttr);
George Burgess IV850269a2015-12-08 22:02:00 +000010019 std::string Str;
10020 llvm::raw_string_ostream S(Str);
10021 E->printPretty(S, nullptr, getPrintingPolicy());
10022 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
10023 : diag::warn_cast_nonnull_to_bool;
10024 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
10025 << E->getSourceRange() << Range << IsEqual;
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010026 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
George Burgess IV850269a2015-12-08 22:02:00 +000010027 };
10028
10029 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
10030 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
10031 if (auto *Callee = Call->getDirectCallee()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010032 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
10033 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +000010034 return;
10035 }
10036 }
10037 }
10038
Richard Trieu3bb8b562014-02-26 02:36:06 +000010039 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +000010040 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +000010041 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
10042 D = R->getDecl();
10043 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
10044 D = M->getMemberDecl();
10045 }
10046
10047 // Weak Decls can be null.
10048 if (!D || D->isWeak())
10049 return;
George Burgess IV850269a2015-12-08 22:02:00 +000010050
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010051 // Check for parameter decl with nonnull attribute
George Burgess IV850269a2015-12-08 22:02:00 +000010052 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
10053 if (getCurFunction() &&
10054 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010055 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
10056 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +000010057 return;
10058 }
10059
10060 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
David Majnemera3debed2016-06-24 05:33:44 +000010061 auto ParamIter = llvm::find(FD->parameters(), PV);
George Burgess IV850269a2015-12-08 22:02:00 +000010062 assert(ParamIter != FD->param_end());
10063 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
10064
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010065 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
10066 if (!NonNull->args_size()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010067 ComplainAboutNonnullParamOrCall(NonNull);
George Burgess IV850269a2015-12-08 22:02:00 +000010068 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010069 }
George Burgess IV850269a2015-12-08 22:02:00 +000010070
10071 for (unsigned ArgNo : NonNull->args()) {
10072 if (ArgNo == ParamNo) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010073 ComplainAboutNonnullParamOrCall(NonNull);
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010074 return;
10075 }
George Burgess IV850269a2015-12-08 22:02:00 +000010076 }
10077 }
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010078 }
10079 }
George Burgess IV850269a2015-12-08 22:02:00 +000010080 }
10081
Richard Trieu3bb8b562014-02-26 02:36:06 +000010082 QualType T = D->getType();
10083 const bool IsArray = T->isArrayType();
10084 const bool IsFunction = T->isFunctionType();
10085
Richard Trieuc1888e02014-06-28 23:25:37 +000010086 // Address of function is used to silence the function warning.
10087 if (IsAddressOf && IsFunction) {
10088 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +000010089 }
10090
10091 // Found nothing.
10092 if (!IsAddressOf && !IsFunction && !IsArray)
10093 return;
10094
10095 // Pretty print the expression for the diagnostic.
10096 std::string Str;
10097 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +000010098 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +000010099
10100 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
10101 : diag::warn_impcast_pointer_to_bool;
Craig Topperfa1340f2015-12-23 05:44:46 +000010102 enum {
10103 AddressOf,
10104 FunctionPointer,
10105 ArrayPointer
10106 } DiagType;
Richard Trieu3bb8b562014-02-26 02:36:06 +000010107 if (IsAddressOf)
10108 DiagType = AddressOf;
10109 else if (IsFunction)
10110 DiagType = FunctionPointer;
10111 else if (IsArray)
10112 DiagType = ArrayPointer;
10113 else
10114 llvm_unreachable("Could not determine diagnostic.");
10115 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
10116 << Range << IsEqual;
10117
10118 if (!IsFunction)
10119 return;
10120
10121 // Suggest '&' to silence the function warning.
10122 Diag(E->getExprLoc(), diag::note_function_warning_silence)
10123 << FixItHint::CreateInsertion(E->getLocStart(), "&");
10124
10125 // Check to see if '()' fixit should be emitted.
10126 QualType ReturnType;
10127 UnresolvedSet<4> NonTemplateOverloads;
10128 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
10129 if (ReturnType.isNull())
10130 return;
10131
10132 if (IsCompare) {
10133 // There are two cases here. If there is null constant, the only suggest
10134 // for a pointer return type. If the null is 0, then suggest if the return
10135 // type is a pointer or an integer type.
10136 if (!ReturnType->isPointerType()) {
10137 if (NullKind == Expr::NPCK_ZeroExpression ||
10138 NullKind == Expr::NPCK_ZeroLiteral) {
10139 if (!ReturnType->isIntegerType())
10140 return;
10141 } else {
10142 return;
10143 }
10144 }
10145 } else { // !IsCompare
10146 // For function to bool, only suggest if the function pointer has bool
10147 // return type.
10148 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
10149 return;
10150 }
10151 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +000010152 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +000010153}
10154
John McCallcc7e5bf2010-05-06 08:58:33 +000010155/// Diagnoses "dangerous" implicit conversions within the given
10156/// expression (which is a full expression). Implements -Wconversion
10157/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +000010158///
10159/// \param CC the "context" location of the implicit conversion, i.e.
10160/// the most location of the syntactic entity requiring the implicit
10161/// conversion
10162void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +000010163 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +000010164 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +000010165 return;
10166
10167 // Don't diagnose for value- or type-dependent expressions.
10168 if (E->isTypeDependent() || E->isValueDependent())
10169 return;
10170
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010171 // Check for array bounds violations in cases where the check isn't triggered
10172 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
10173 // ArraySubscriptExpr is on the RHS of a variable initialization.
10174 CheckArrayAccess(E);
10175
John McCallacf0ee52010-10-08 02:01:28 +000010176 // This is not the right CC for (e.g.) a variable initialization.
10177 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000010178}
10179
Richard Trieu65724892014-11-15 06:37:39 +000010180/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
10181/// Input argument E is a logical expression.
10182void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
10183 ::CheckBoolLikeConversion(*this, E, CC);
10184}
10185
Richard Smith9f7df0c2017-06-26 23:19:32 +000010186/// Diagnose when expression is an integer constant expression and its evaluation
10187/// results in integer overflow
10188void Sema::CheckForIntOverflow (Expr *E) {
10189 // Use a work list to deal with nested struct initializers.
10190 SmallVector<Expr *, 2> Exprs(1, E);
10191
10192 do {
10193 Expr *E = Exprs.pop_back_val();
10194
10195 if (isa<BinaryOperator>(E->IgnoreParenCasts())) {
10196 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
10197 continue;
10198 }
10199
10200 if (auto InitList = dyn_cast<InitListExpr>(E))
10201 Exprs.append(InitList->inits().begin(), InitList->inits().end());
10202
10203 if (isa<ObjCBoxedExpr>(E))
10204 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
10205 } while (!Exprs.empty());
10206}
10207
Richard Smithc406cb72013-01-17 01:17:56 +000010208namespace {
10209/// \brief Visitor for expressions which looks for unsequenced operations on the
10210/// same object.
10211class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +000010212 typedef EvaluatedExprVisitor<SequenceChecker> Base;
10213
Richard Smithc406cb72013-01-17 01:17:56 +000010214 /// \brief A tree of sequenced regions within an expression. Two regions are
10215 /// unsequenced if one is an ancestor or a descendent of the other. When we
10216 /// finish processing an expression with sequencing, such as a comma
10217 /// expression, we fold its tree nodes into its parent, since they are
10218 /// unsequenced with respect to nodes we will visit later.
10219 class SequenceTree {
10220 struct Value {
10221 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
10222 unsigned Parent : 31;
Aaron Ballmanaffa1c32016-07-06 18:33:01 +000010223 unsigned Merged : 1;
Richard Smithc406cb72013-01-17 01:17:56 +000010224 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010225 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +000010226
10227 public:
10228 /// \brief A region within an expression which may be sequenced with respect
10229 /// to some other region.
10230 class Seq {
10231 explicit Seq(unsigned N) : Index(N) {}
10232 unsigned Index;
10233 friend class SequenceTree;
10234 public:
10235 Seq() : Index(0) {}
10236 };
10237
10238 SequenceTree() { Values.push_back(Value(0)); }
10239 Seq root() const { return Seq(0); }
10240
10241 /// \brief Create a new sequence of operations, which is an unsequenced
10242 /// subset of \p Parent. This sequence of operations is sequenced with
10243 /// respect to other children of \p Parent.
10244 Seq allocate(Seq Parent) {
10245 Values.push_back(Value(Parent.Index));
10246 return Seq(Values.size() - 1);
10247 }
10248
10249 /// \brief Merge a sequence of operations into its parent.
10250 void merge(Seq S) {
10251 Values[S.Index].Merged = true;
10252 }
10253
10254 /// \brief Determine whether two operations are unsequenced. This operation
10255 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
10256 /// should have been merged into its parent as appropriate.
10257 bool isUnsequenced(Seq Cur, Seq Old) {
10258 unsigned C = representative(Cur.Index);
10259 unsigned Target = representative(Old.Index);
10260 while (C >= Target) {
10261 if (C == Target)
10262 return true;
10263 C = Values[C].Parent;
10264 }
10265 return false;
10266 }
10267
10268 private:
10269 /// \brief Pick a representative for a sequence.
10270 unsigned representative(unsigned K) {
10271 if (Values[K].Merged)
10272 // Perform path compression as we go.
10273 return Values[K].Parent = representative(Values[K].Parent);
10274 return K;
10275 }
10276 };
10277
10278 /// An object for which we can track unsequenced uses.
10279 typedef NamedDecl *Object;
10280
10281 /// Different flavors of object usage which we track. We only track the
10282 /// least-sequenced usage of each kind.
10283 enum UsageKind {
10284 /// A read of an object. Multiple unsequenced reads are OK.
10285 UK_Use,
10286 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +000010287 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +000010288 UK_ModAsValue,
10289 /// A modification of an object which is not sequenced before the value
10290 /// computation of the expression, such as n++.
10291 UK_ModAsSideEffect,
10292
10293 UK_Count = UK_ModAsSideEffect + 1
10294 };
10295
10296 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +000010297 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +000010298 Expr *Use;
10299 SequenceTree::Seq Seq;
10300 };
10301
10302 struct UsageInfo {
10303 UsageInfo() : Diagnosed(false) {}
10304 Usage Uses[UK_Count];
10305 /// Have we issued a diagnostic for this variable already?
10306 bool Diagnosed;
10307 };
10308 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
10309
10310 Sema &SemaRef;
10311 /// Sequenced regions within the expression.
10312 SequenceTree Tree;
10313 /// Declaration modifications and references which we have seen.
10314 UsageInfoMap UsageMap;
10315 /// The region we are currently within.
10316 SequenceTree::Seq Region;
10317 /// Filled in with declarations which were modified as a side-effect
10318 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010319 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +000010320 /// Expressions to check later. We defer checking these to reduce
10321 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010322 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +000010323
10324 /// RAII object wrapping the visitation of a sequenced subexpression of an
10325 /// expression. At the end of this process, the side-effects of the evaluation
10326 /// become sequenced with respect to the value computation of the result, so
10327 /// we downgrade any UK_ModAsSideEffect within the evaluation to
10328 /// UK_ModAsValue.
10329 struct SequencedSubexpression {
10330 SequencedSubexpression(SequenceChecker &Self)
10331 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
10332 Self.ModAsSideEffect = &ModAsSideEffect;
10333 }
10334 ~SequencedSubexpression() {
David Majnemerf7e36092016-06-23 00:15:04 +000010335 for (auto &M : llvm::reverse(ModAsSideEffect)) {
10336 UsageInfo &U = Self.UsageMap[M.first];
Richard Smithe8efd992014-12-03 01:05:50 +000010337 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
David Majnemerf7e36092016-06-23 00:15:04 +000010338 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
10339 SideEffectUsage = M.second;
Richard Smithc406cb72013-01-17 01:17:56 +000010340 }
10341 Self.ModAsSideEffect = OldModAsSideEffect;
10342 }
10343
10344 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010345 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
10346 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +000010347 };
10348
Richard Smith40238f02013-06-20 22:21:56 +000010349 /// RAII object wrapping the visitation of a subexpression which we might
10350 /// choose to evaluate as a constant. If any subexpression is evaluated and
10351 /// found to be non-constant, this allows us to suppress the evaluation of
10352 /// the outer expression.
10353 class EvaluationTracker {
10354 public:
10355 EvaluationTracker(SequenceChecker &Self)
10356 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
10357 Self.EvalTracker = this;
10358 }
10359 ~EvaluationTracker() {
10360 Self.EvalTracker = Prev;
10361 if (Prev)
10362 Prev->EvalOK &= EvalOK;
10363 }
10364
10365 bool evaluate(const Expr *E, bool &Result) {
10366 if (!EvalOK || E->isValueDependent())
10367 return false;
10368 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
10369 return EvalOK;
10370 }
10371
10372 private:
10373 SequenceChecker &Self;
10374 EvaluationTracker *Prev;
10375 bool EvalOK;
10376 } *EvalTracker;
10377
Richard Smithc406cb72013-01-17 01:17:56 +000010378 /// \brief Find the object which is produced by the specified expression,
10379 /// if any.
10380 Object getObject(Expr *E, bool Mod) const {
10381 E = E->IgnoreParenCasts();
10382 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
10383 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
10384 return getObject(UO->getSubExpr(), Mod);
10385 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10386 if (BO->getOpcode() == BO_Comma)
10387 return getObject(BO->getRHS(), Mod);
10388 if (Mod && BO->isAssignmentOp())
10389 return getObject(BO->getLHS(), Mod);
10390 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
10391 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
10392 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
10393 return ME->getMemberDecl();
10394 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10395 // FIXME: If this is a reference, map through to its value.
10396 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +000010397 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +000010398 }
10399
10400 /// \brief Note that an object was modified or used by an expression.
10401 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
10402 Usage &U = UI.Uses[UK];
10403 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
10404 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
10405 ModAsSideEffect->push_back(std::make_pair(O, U));
10406 U.Use = Ref;
10407 U.Seq = Region;
10408 }
10409 }
10410 /// \brief Check whether a modification or use conflicts with a prior usage.
10411 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
10412 bool IsModMod) {
10413 if (UI.Diagnosed)
10414 return;
10415
10416 const Usage &U = UI.Uses[OtherKind];
10417 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
10418 return;
10419
10420 Expr *Mod = U.Use;
10421 Expr *ModOrUse = Ref;
10422 if (OtherKind == UK_Use)
10423 std::swap(Mod, ModOrUse);
10424
10425 SemaRef.Diag(Mod->getExprLoc(),
10426 IsModMod ? diag::warn_unsequenced_mod_mod
10427 : diag::warn_unsequenced_mod_use)
10428 << O << SourceRange(ModOrUse->getExprLoc());
10429 UI.Diagnosed = true;
10430 }
10431
10432 void notePreUse(Object O, Expr *Use) {
10433 UsageInfo &U = UsageMap[O];
10434 // Uses conflict with other modifications.
10435 checkUsage(O, U, Use, UK_ModAsValue, false);
10436 }
10437 void notePostUse(Object O, Expr *Use) {
10438 UsageInfo &U = UsageMap[O];
10439 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
10440 addUsage(U, O, Use, UK_Use);
10441 }
10442
10443 void notePreMod(Object O, Expr *Mod) {
10444 UsageInfo &U = UsageMap[O];
10445 // Modifications conflict with other modifications and with uses.
10446 checkUsage(O, U, Mod, UK_ModAsValue, true);
10447 checkUsage(O, U, Mod, UK_Use, false);
10448 }
10449 void notePostMod(Object O, Expr *Use, UsageKind UK) {
10450 UsageInfo &U = UsageMap[O];
10451 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
10452 addUsage(U, O, Use, UK);
10453 }
10454
10455public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010456 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +000010457 : Base(S.Context), SemaRef(S), Region(Tree.root()),
10458 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +000010459 Visit(E);
10460 }
10461
10462 void VisitStmt(Stmt *S) {
10463 // Skip all statements which aren't expressions for now.
10464 }
10465
10466 void VisitExpr(Expr *E) {
10467 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +000010468 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +000010469 }
10470
10471 void VisitCastExpr(CastExpr *E) {
10472 Object O = Object();
10473 if (E->getCastKind() == CK_LValueToRValue)
10474 O = getObject(E->getSubExpr(), false);
10475
10476 if (O)
10477 notePreUse(O, E);
10478 VisitExpr(E);
10479 if (O)
10480 notePostUse(O, E);
10481 }
10482
10483 void VisitBinComma(BinaryOperator *BO) {
10484 // C++11 [expr.comma]p1:
10485 // Every value computation and side effect associated with the left
10486 // expression is sequenced before every value computation and side
10487 // effect associated with the right expression.
10488 SequenceTree::Seq LHS = Tree.allocate(Region);
10489 SequenceTree::Seq RHS = Tree.allocate(Region);
10490 SequenceTree::Seq OldRegion = Region;
10491
10492 {
10493 SequencedSubexpression SeqLHS(*this);
10494 Region = LHS;
10495 Visit(BO->getLHS());
10496 }
10497
10498 Region = RHS;
10499 Visit(BO->getRHS());
10500
10501 Region = OldRegion;
10502
10503 // Forget that LHS and RHS are sequenced. They are both unsequenced
10504 // with respect to other stuff.
10505 Tree.merge(LHS);
10506 Tree.merge(RHS);
10507 }
10508
10509 void VisitBinAssign(BinaryOperator *BO) {
10510 // The modification is sequenced after the value computation of the LHS
10511 // and RHS, so check it before inspecting the operands and update the
10512 // map afterwards.
10513 Object O = getObject(BO->getLHS(), true);
10514 if (!O)
10515 return VisitExpr(BO);
10516
10517 notePreMod(O, BO);
10518
10519 // C++11 [expr.ass]p7:
10520 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
10521 // only once.
10522 //
10523 // Therefore, for a compound assignment operator, O is considered used
10524 // everywhere except within the evaluation of E1 itself.
10525 if (isa<CompoundAssignOperator>(BO))
10526 notePreUse(O, BO);
10527
10528 Visit(BO->getLHS());
10529
10530 if (isa<CompoundAssignOperator>(BO))
10531 notePostUse(O, BO);
10532
10533 Visit(BO->getRHS());
10534
Richard Smith83e37bee2013-06-26 23:16:51 +000010535 // C++11 [expr.ass]p1:
10536 // the assignment is sequenced [...] before the value computation of the
10537 // assignment expression.
10538 // C11 6.5.16/3 has no such rule.
10539 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10540 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000010541 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010542
Richard Smithc406cb72013-01-17 01:17:56 +000010543 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
10544 VisitBinAssign(CAO);
10545 }
10546
10547 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10548 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10549 void VisitUnaryPreIncDec(UnaryOperator *UO) {
10550 Object O = getObject(UO->getSubExpr(), true);
10551 if (!O)
10552 return VisitExpr(UO);
10553
10554 notePreMod(O, UO);
10555 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +000010556 // C++11 [expr.pre.incr]p1:
10557 // the expression ++x is equivalent to x+=1
10558 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10559 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000010560 }
10561
10562 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10563 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10564 void VisitUnaryPostIncDec(UnaryOperator *UO) {
10565 Object O = getObject(UO->getSubExpr(), true);
10566 if (!O)
10567 return VisitExpr(UO);
10568
10569 notePreMod(O, UO);
10570 Visit(UO->getSubExpr());
10571 notePostMod(O, UO, UK_ModAsSideEffect);
10572 }
10573
10574 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
10575 void VisitBinLOr(BinaryOperator *BO) {
10576 // The side-effects of the LHS of an '&&' are sequenced before the
10577 // value computation of the RHS, and hence before the value computation
10578 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
10579 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +000010580 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000010581 {
10582 SequencedSubexpression Sequenced(*this);
10583 Visit(BO->getLHS());
10584 }
10585
10586 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010587 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000010588 if (!Result)
10589 Visit(BO->getRHS());
10590 } else {
10591 // Check for unsequenced operations in the RHS, treating it as an
10592 // entirely separate evaluation.
10593 //
10594 // FIXME: If there are operations in the RHS which are unsequenced
10595 // with respect to operations outside the RHS, and those operations
10596 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +000010597 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000010598 }
Richard Smithc406cb72013-01-17 01:17:56 +000010599 }
10600 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +000010601 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000010602 {
10603 SequencedSubexpression Sequenced(*this);
10604 Visit(BO->getLHS());
10605 }
10606
10607 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010608 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000010609 if (Result)
10610 Visit(BO->getRHS());
10611 } else {
Richard Smithd33f5202013-01-17 23:18:09 +000010612 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000010613 }
Richard Smithc406cb72013-01-17 01:17:56 +000010614 }
10615
10616 // Only visit the condition, unless we can be sure which subexpression will
10617 // be chosen.
10618 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +000010619 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +000010620 {
10621 SequencedSubexpression Sequenced(*this);
10622 Visit(CO->getCond());
10623 }
Richard Smithc406cb72013-01-17 01:17:56 +000010624
10625 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010626 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +000010627 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000010628 else {
Richard Smithd33f5202013-01-17 23:18:09 +000010629 WorkList.push_back(CO->getTrueExpr());
10630 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000010631 }
Richard Smithc406cb72013-01-17 01:17:56 +000010632 }
10633
Richard Smithe3dbfe02013-06-30 10:40:20 +000010634 void VisitCallExpr(CallExpr *CE) {
10635 // C++11 [intro.execution]p15:
10636 // When calling a function [...], every value computation and side effect
10637 // associated with any argument expression, or with the postfix expression
10638 // designating the called function, is sequenced before execution of every
10639 // expression or statement in the body of the function [and thus before
10640 // the value computation of its result].
10641 SequencedSubexpression Sequenced(*this);
10642 Base::VisitCallExpr(CE);
10643
10644 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
10645 }
10646
Richard Smithc406cb72013-01-17 01:17:56 +000010647 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +000010648 // This is a call, so all subexpressions are sequenced before the result.
10649 SequencedSubexpression Sequenced(*this);
10650
Richard Smithc406cb72013-01-17 01:17:56 +000010651 if (!CCE->isListInitialization())
10652 return VisitExpr(CCE);
10653
10654 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010655 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000010656 SequenceTree::Seq Parent = Region;
10657 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
10658 E = CCE->arg_end();
10659 I != E; ++I) {
10660 Region = Tree.allocate(Parent);
10661 Elts.push_back(Region);
10662 Visit(*I);
10663 }
10664
10665 // Forget that the initializers are sequenced.
10666 Region = Parent;
10667 for (unsigned I = 0; I < Elts.size(); ++I)
10668 Tree.merge(Elts[I]);
10669 }
10670
10671 void VisitInitListExpr(InitListExpr *ILE) {
10672 if (!SemaRef.getLangOpts().CPlusPlus11)
10673 return VisitExpr(ILE);
10674
10675 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010676 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000010677 SequenceTree::Seq Parent = Region;
10678 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
10679 Expr *E = ILE->getInit(I);
10680 if (!E) continue;
10681 Region = Tree.allocate(Parent);
10682 Elts.push_back(Region);
10683 Visit(E);
10684 }
10685
10686 // Forget that the initializers are sequenced.
10687 Region = Parent;
10688 for (unsigned I = 0; I < Elts.size(); ++I)
10689 Tree.merge(Elts[I]);
10690 }
10691};
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010692} // end anonymous namespace
Richard Smithc406cb72013-01-17 01:17:56 +000010693
10694void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010695 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +000010696 WorkList.push_back(E);
10697 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +000010698 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +000010699 SequenceChecker(*this, Item, WorkList);
10700 }
Richard Smithc406cb72013-01-17 01:17:56 +000010701}
10702
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010703void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
10704 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +000010705 CheckImplicitConversions(E, CheckLoc);
Richard Trieu71d74d42016-08-05 21:02:34 +000010706 if (!E->isInstantiationDependent())
10707 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010708 if (!IsConstexpr && !E->isValueDependent())
Richard Smith9f7df0c2017-06-26 23:19:32 +000010709 CheckForIntOverflow(E);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000010710 DiagnoseMisalignedMembers();
Richard Smithc406cb72013-01-17 01:17:56 +000010711}
10712
John McCall1f425642010-11-11 03:21:53 +000010713void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
10714 FieldDecl *BitField,
10715 Expr *Init) {
10716 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
10717}
10718
David Majnemer61a5bbf2015-04-07 22:08:51 +000010719static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
10720 SourceLocation Loc) {
10721 if (!PType->isVariablyModifiedType())
10722 return;
10723 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
10724 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
10725 return;
10726 }
David Majnemerdf8f73f2015-04-09 19:53:25 +000010727 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
10728 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
10729 return;
10730 }
David Majnemer61a5bbf2015-04-07 22:08:51 +000010731 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
10732 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
10733 return;
10734 }
10735
10736 const ArrayType *AT = S.Context.getAsArrayType(PType);
10737 if (!AT)
10738 return;
10739
10740 if (AT->getSizeModifier() != ArrayType::Star) {
10741 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
10742 return;
10743 }
10744
10745 S.Diag(Loc, diag::err_array_star_in_function_definition);
10746}
10747
Mike Stump0c2ec772010-01-21 03:59:47 +000010748/// CheckParmsForFunctionDef - Check that the parameters of the given
10749/// function are appropriate for the definition of a function. This
10750/// takes care of any checks that cannot be performed on the
10751/// declaration itself, e.g., that the types of each of the function
10752/// parameters are complete.
David Majnemer59f77922016-06-24 04:05:48 +000010753bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
Douglas Gregorb524d902010-11-01 18:37:59 +000010754 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010755 bool HasInvalidParm = false;
David Majnemer59f77922016-06-24 04:05:48 +000010756 for (ParmVarDecl *Param : Parameters) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010757 // C99 6.7.5.3p4: the parameters in a parameter type list in a
10758 // function declarator that is part of a function definition of
10759 // that function shall not have incomplete type.
10760 //
10761 // This is also C++ [dcl.fct]p6.
10762 if (!Param->isInvalidDecl() &&
10763 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000010764 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010765 Param->setInvalidDecl();
10766 HasInvalidParm = true;
10767 }
10768
10769 // C99 6.9.1p5: If the declarator includes a parameter type list, the
10770 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +000010771 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +000010772 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +000010773 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +000010774 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +000010775 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +000010776
10777 // C99 6.7.5.3p12:
10778 // If the function declarator is not part of a definition of that
10779 // function, parameters may have incomplete type and may use the [*]
10780 // notation in their sequences of declarator specifiers to specify
10781 // variable length array types.
10782 QualType PType = Param->getOriginalType();
David Majnemer61a5bbf2015-04-07 22:08:51 +000010783 // FIXME: This diagnostic should point the '[*]' if source-location
10784 // information is added for it.
10785 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000010786
10787 // MSVC destroys objects passed by value in the callee. Therefore a
10788 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +000010789 // object's destructor. However, we don't perform any direct access check
10790 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +000010791 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
10792 .getCXXABI()
10793 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +000010794 if (!Param->isInvalidDecl()) {
10795 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
10796 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
10797 if (!ClassDecl->isInvalidDecl() &&
10798 !ClassDecl->hasIrrelevantDestructor() &&
10799 !ClassDecl->isDependentContext()) {
10800 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
10801 MarkFunctionReferenced(Param->getLocation(), Destructor);
10802 DiagnoseUseOfDecl(Destructor, Param->getLocation());
10803 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +000010804 }
10805 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000010806 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010807
10808 // Parameters with the pass_object_size attribute only need to be marked
10809 // constant at function definitions. Because we lack information about
10810 // whether we're on a declaration or definition when we're instantiating the
10811 // attribute, we need to check for constness here.
10812 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
10813 if (!Param->getType().isConstQualified())
10814 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
10815 << Attr->getSpelling() << 1;
Mike Stump0c2ec772010-01-21 03:59:47 +000010816 }
10817
10818 return HasInvalidParm;
10819}
John McCall2b5c1b22010-08-12 21:44:57 +000010820
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000010821/// A helper function to get the alignment of a Decl referred to by DeclRefExpr
10822/// or MemberExpr.
10823static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
10824 ASTContext &Context) {
10825 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
10826 return Context.getDeclAlign(DRE->getDecl());
10827
10828 if (const auto *ME = dyn_cast<MemberExpr>(E))
10829 return Context.getDeclAlign(ME->getMemberDecl());
10830
10831 return TypeAlign;
10832}
10833
John McCall2b5c1b22010-08-12 21:44:57 +000010834/// CheckCastAlign - Implements -Wcast-align, which warns when a
10835/// pointer cast increases the alignment requirements.
10836void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
10837 // This is actually a lot of work to potentially be doing on every
10838 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000010839 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +000010840 return;
10841
10842 // Ignore dependent types.
10843 if (T->isDependentType() || Op->getType()->isDependentType())
10844 return;
10845
10846 // Require that the destination be a pointer type.
10847 const PointerType *DestPtr = T->getAs<PointerType>();
10848 if (!DestPtr) return;
10849
10850 // If the destination has alignment 1, we're done.
10851 QualType DestPointee = DestPtr->getPointeeType();
10852 if (DestPointee->isIncompleteType()) return;
10853 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
10854 if (DestAlign.isOne()) return;
10855
10856 // Require that the source be a pointer type.
10857 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
10858 if (!SrcPtr) return;
10859 QualType SrcPointee = SrcPtr->getPointeeType();
10860
10861 // Whitelist casts from cv void*. We already implicitly
10862 // whitelisted casts to cv void*, since they have alignment 1.
10863 // Also whitelist casts involving incomplete types, which implicitly
10864 // includes 'void'.
10865 if (SrcPointee->isIncompleteType()) return;
10866
10867 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000010868
10869 if (auto *CE = dyn_cast<CastExpr>(Op)) {
10870 if (CE->getCastKind() == CK_ArrayToPointerDecay)
10871 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
10872 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
10873 if (UO->getOpcode() == UO_AddrOf)
10874 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
10875 }
10876
John McCall2b5c1b22010-08-12 21:44:57 +000010877 if (SrcAlign >= DestAlign) return;
10878
10879 Diag(TRange.getBegin(), diag::warn_cast_align)
10880 << Op->getType() << T
10881 << static_cast<unsigned>(SrcAlign.getQuantity())
10882 << static_cast<unsigned>(DestAlign.getQuantity())
10883 << TRange << Op->getSourceRange();
10884}
10885
Chandler Carruth28389f02011-08-05 09:10:50 +000010886/// \brief Check whether this array fits the idiom of a size-one tail padded
10887/// array member of a struct.
10888///
10889/// We avoid emitting out-of-bounds access warnings for such arrays as they are
10890/// commonly used to emulate flexible arrays in C89 code.
Benjamin Kramer7320b992016-06-15 14:20:56 +000010891static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
Chandler Carruth28389f02011-08-05 09:10:50 +000010892 const NamedDecl *ND) {
10893 if (Size != 1 || !ND) return false;
10894
10895 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
10896 if (!FD) return false;
10897
10898 // Don't consider sizes resulting from macro expansions or template argument
10899 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +000010900
10901 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000010902 while (TInfo) {
10903 TypeLoc TL = TInfo->getTypeLoc();
10904 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +000010905 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
10906 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000010907 TInfo = TDL->getTypeSourceInfo();
10908 continue;
10909 }
David Blaikie6adc78e2013-02-18 22:06:02 +000010910 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
10911 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +000010912 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
10913 return false;
10914 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +000010915 break;
Sean Callanan06a48a62012-05-04 18:22:53 +000010916 }
Chandler Carruth28389f02011-08-05 09:10:50 +000010917
10918 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +000010919 if (!RD) return false;
10920 if (RD->isUnion()) return false;
10921 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
10922 if (!CRD->isStandardLayout()) return false;
10923 }
Chandler Carruth28389f02011-08-05 09:10:50 +000010924
Benjamin Kramer8c543672011-08-06 03:04:42 +000010925 // See if this is the last field decl in the record.
10926 const Decl *D = FD;
10927 while ((D = D->getNextDeclInContext()))
10928 if (isa<FieldDecl>(D))
10929 return false;
10930 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +000010931}
10932
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010933void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010934 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +000010935 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010936 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010937 if (IndexExpr->isValueDependent())
10938 return;
10939
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000010940 const Type *EffectiveType =
10941 BaseExpr->getType()->getPointeeOrArrayElementType();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010942 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010943 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010944 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010945 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +000010946 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +000010947
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010948 llvm::APSInt index;
Richard Smith0c6124b2015-12-03 01:36:22 +000010949 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
Ted Kremenek64699be2011-02-16 01:57:07 +000010950 return;
Richard Smith13f67182011-12-16 19:31:14 +000010951 if (IndexNegated)
10952 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +000010953
Craig Topperc3ec1492014-05-26 06:22:03 +000010954 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +000010955 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
10956 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +000010957 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +000010958 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +000010959
Ted Kremeneke4b316c2011-02-23 23:06:04 +000010960 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000010961 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +000010962 if (!size.isStrictlyPositive())
10963 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010964
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000010965 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
Nico Weber7c299802011-09-17 22:59:41 +000010966 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010967 // Make sure we're comparing apples to apples when comparing index to size
10968 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
10969 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +000010970 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +000010971 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010972 if (ptrarith_typesize != array_typesize) {
10973 // There's a cast to a different size type involved
10974 uint64_t ratio = array_typesize / ptrarith_typesize;
10975 // TODO: Be smarter about handling cases where array_typesize is not a
10976 // multiple of ptrarith_typesize
10977 if (ptrarith_typesize * ratio == array_typesize)
10978 size *= llvm::APInt(size.getBitWidth(), ratio);
10979 }
10980 }
10981
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010982 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010983 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000010984 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010985 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000010986
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010987 // For array subscripting the index must be less than size, but for pointer
10988 // arithmetic also allow the index (offset) to be equal to size since
10989 // computing the next address after the end of the array is legal and
10990 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010991 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +000010992 return;
10993
10994 // Also don't warn for arrays of size 1 which are members of some
10995 // structure. These are often used to approximate flexible arrays in C89
10996 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010997 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +000010998 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010999
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011000 // Suppress the warning if the subscript expression (as identified by the
11001 // ']' location) and the index expression are both from macro expansions
11002 // within a system header.
11003 if (ASE) {
11004 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
11005 ASE->getRBracketLoc());
11006 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
11007 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
11008 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +000011009 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011010 return;
11011 }
11012 }
11013
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011014 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011015 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011016 DiagID = diag::warn_array_index_exceeds_bounds;
11017
11018 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
11019 PDiag(DiagID) << index.toString(10, true)
11020 << size.toString(10, true)
11021 << (unsigned)size.getLimitedValue(~0U)
11022 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011023 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011024 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011025 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011026 DiagID = diag::warn_ptr_arith_precedes_bounds;
11027 if (index.isNegative()) index = -index;
11028 }
11029
11030 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
11031 PDiag(DiagID) << index.toString(10, true)
11032 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +000011033 }
Chandler Carruth1af88f12011-02-17 21:10:52 +000011034
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000011035 if (!ND) {
11036 // Try harder to find a NamedDecl to point at in the note.
11037 while (const ArraySubscriptExpr *ASE =
11038 dyn_cast<ArraySubscriptExpr>(BaseExpr))
11039 BaseExpr = ASE->getBase()->IgnoreParenCasts();
11040 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
11041 ND = dyn_cast<NamedDecl>(DRE->getDecl());
11042 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
11043 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
11044 }
11045
Chandler Carruth1af88f12011-02-17 21:10:52 +000011046 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011047 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
11048 PDiag(diag::note_array_index_out_of_bounds)
11049 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +000011050}
11051
Ted Kremenekdf26df72011-03-01 18:41:00 +000011052void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011053 int AllowOnePastEnd = 0;
11054 while (expr) {
11055 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +000011056 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011057 case Stmt::ArraySubscriptExprClass: {
11058 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011059 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011060 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +000011061 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011062 }
Alexey Bataev1a3320e2015-08-25 14:24:04 +000011063 case Stmt::OMPArraySectionExprClass: {
11064 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
11065 if (ASE->getLowerBound())
11066 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
11067 /*ASE=*/nullptr, AllowOnePastEnd > 0);
11068 return;
11069 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011070 case Stmt::UnaryOperatorClass: {
11071 // Only unwrap the * and & unary operators
11072 const UnaryOperator *UO = cast<UnaryOperator>(expr);
11073 expr = UO->getSubExpr();
11074 switch (UO->getOpcode()) {
11075 case UO_AddrOf:
11076 AllowOnePastEnd++;
11077 break;
11078 case UO_Deref:
11079 AllowOnePastEnd--;
11080 break;
11081 default:
11082 return;
11083 }
11084 break;
11085 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000011086 case Stmt::ConditionalOperatorClass: {
11087 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
11088 if (const Expr *lhs = cond->getLHS())
11089 CheckArrayAccess(lhs);
11090 if (const Expr *rhs = cond->getRHS())
11091 CheckArrayAccess(rhs);
11092 return;
11093 }
Daniel Marjamaki20a209e2017-02-28 14:53:50 +000011094 case Stmt::CXXOperatorCallExprClass: {
11095 const auto *OCE = cast<CXXOperatorCallExpr>(expr);
11096 for (const auto *Arg : OCE->arguments())
11097 CheckArrayAccess(Arg);
11098 return;
11099 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000011100 default:
11101 return;
11102 }
Peter Collingbourne91147592011-04-15 00:35:48 +000011103 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000011104}
John McCall31168b02011-06-15 23:02:42 +000011105
11106//===--- CHECK: Objective-C retain cycles ----------------------------------//
11107
11108namespace {
11109 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +000011110 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +000011111 VarDecl *Variable;
11112 SourceRange Range;
11113 SourceLocation Loc;
11114 bool Indirect;
11115
11116 void setLocsFrom(Expr *e) {
11117 Loc = e->getExprLoc();
11118 Range = e->getSourceRange();
11119 }
11120 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011121} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +000011122
11123/// Consider whether capturing the given variable can possibly lead to
11124/// a retain cycle.
11125static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +000011126 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +000011127 // lifetime. In MRR, it's captured strongly if the variable is
11128 // __block and has an appropriate type.
11129 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
11130 return false;
11131
11132 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000011133 if (ref)
11134 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +000011135 return true;
11136}
11137
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011138static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +000011139 while (true) {
11140 e = e->IgnoreParens();
11141 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
11142 switch (cast->getCastKind()) {
11143 case CK_BitCast:
11144 case CK_LValueBitCast:
11145 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +000011146 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +000011147 e = cast->getSubExpr();
11148 continue;
11149
John McCall31168b02011-06-15 23:02:42 +000011150 default:
11151 return false;
11152 }
11153 }
11154
11155 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
11156 ObjCIvarDecl *ivar = ref->getDecl();
11157 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
11158 return false;
11159
11160 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011161 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +000011162 return false;
11163
11164 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
11165 owner.Indirect = true;
11166 return true;
11167 }
11168
11169 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
11170 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
11171 if (!var) return false;
11172 return considerVariable(var, ref, owner);
11173 }
11174
John McCall31168b02011-06-15 23:02:42 +000011175 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
11176 if (member->isArrow()) return false;
11177
11178 // Don't count this as an indirect ownership.
11179 e = member->getBase();
11180 continue;
11181 }
11182
John McCallfe96e0b2011-11-06 09:01:30 +000011183 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
11184 // Only pay attention to pseudo-objects on property references.
11185 ObjCPropertyRefExpr *pre
11186 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
11187 ->IgnoreParens());
11188 if (!pre) return false;
11189 if (pre->isImplicitProperty()) return false;
11190 ObjCPropertyDecl *property = pre->getExplicitProperty();
11191 if (!property->isRetaining() &&
11192 !(property->getPropertyIvarDecl() &&
11193 property->getPropertyIvarDecl()->getType()
11194 .getObjCLifetime() == Qualifiers::OCL_Strong))
11195 return false;
11196
11197 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011198 if (pre->isSuperReceiver()) {
11199 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
11200 if (!owner.Variable)
11201 return false;
11202 owner.Loc = pre->getLocation();
11203 owner.Range = pre->getSourceRange();
11204 return true;
11205 }
John McCallfe96e0b2011-11-06 09:01:30 +000011206 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
11207 ->getSourceExpr());
11208 continue;
11209 }
11210
John McCall31168b02011-06-15 23:02:42 +000011211 // Array ivars?
11212
11213 return false;
11214 }
11215}
11216
11217namespace {
11218 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
11219 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
11220 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000011221 Context(Context), Variable(variable), Capturer(nullptr),
11222 VarWillBeReased(false) {}
11223 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +000011224 VarDecl *Variable;
11225 Expr *Capturer;
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000011226 bool VarWillBeReased;
John McCall31168b02011-06-15 23:02:42 +000011227
11228 void VisitDeclRefExpr(DeclRefExpr *ref) {
11229 if (ref->getDecl() == Variable && !Capturer)
11230 Capturer = ref;
11231 }
11232
John McCall31168b02011-06-15 23:02:42 +000011233 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
11234 if (Capturer) return;
11235 Visit(ref->getBase());
11236 if (Capturer && ref->isFreeIvar())
11237 Capturer = ref;
11238 }
11239
11240 void VisitBlockExpr(BlockExpr *block) {
11241 // Look inside nested blocks
11242 if (block->getBlockDecl()->capturesVariable(Variable))
11243 Visit(block->getBlockDecl()->getBody());
11244 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +000011245
11246 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
11247 if (Capturer) return;
11248 if (OVE->getSourceExpr())
11249 Visit(OVE->getSourceExpr());
11250 }
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000011251 void VisitBinaryOperator(BinaryOperator *BinOp) {
11252 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
11253 return;
11254 Expr *LHS = BinOp->getLHS();
11255 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
11256 if (DRE->getDecl() != Variable)
11257 return;
11258 if (Expr *RHS = BinOp->getRHS()) {
11259 RHS = RHS->IgnoreParenCasts();
11260 llvm::APSInt Value;
11261 VarWillBeReased =
11262 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
11263 }
11264 }
11265 }
John McCall31168b02011-06-15 23:02:42 +000011266 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011267} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +000011268
11269/// Check whether the given argument is a block which captures a
11270/// variable.
11271static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
11272 assert(owner.Variable && owner.Loc.isValid());
11273
11274 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +000011275
11276 // Look through [^{...} copy] and Block_copy(^{...}).
11277 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
11278 Selector Cmd = ME->getSelector();
11279 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
11280 e = ME->getInstanceReceiver();
11281 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +000011282 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +000011283 e = e->IgnoreParenCasts();
11284 }
11285 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
11286 if (CE->getNumArgs() == 1) {
11287 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +000011288 if (Fn) {
11289 const IdentifierInfo *FnI = Fn->getIdentifier();
11290 if (FnI && FnI->isStr("_Block_copy")) {
11291 e = CE->getArg(0)->IgnoreParenCasts();
11292 }
11293 }
Jordan Rose67e887c2012-09-17 17:54:30 +000011294 }
11295 }
11296
John McCall31168b02011-06-15 23:02:42 +000011297 BlockExpr *block = dyn_cast<BlockExpr>(e);
11298 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +000011299 return nullptr;
John McCall31168b02011-06-15 23:02:42 +000011300
11301 FindCaptureVisitor visitor(S.Context, owner.Variable);
11302 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000011303 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +000011304}
11305
11306static void diagnoseRetainCycle(Sema &S, Expr *capturer,
11307 RetainCycleOwner &owner) {
11308 assert(capturer);
11309 assert(owner.Variable && owner.Loc.isValid());
11310
11311 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
11312 << owner.Variable << capturer->getSourceRange();
11313 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
11314 << owner.Indirect << owner.Range;
11315}
11316
11317/// Check for a keyword selector that starts with the word 'add' or
11318/// 'set'.
11319static bool isSetterLikeSelector(Selector sel) {
11320 if (sel.isUnarySelector()) return false;
11321
Chris Lattner0e62c1c2011-07-23 10:55:15 +000011322 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +000011323 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +000011324 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +000011325 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +000011326 else if (str.startswith("add")) {
11327 // Specially whitelist 'addOperationWithBlock:'.
11328 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
11329 return false;
11330 str = str.substr(3);
11331 }
John McCall31168b02011-06-15 23:02:42 +000011332 else
11333 return false;
11334
11335 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +000011336 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +000011337}
11338
Benjamin Kramer3a743452015-03-09 15:03:32 +000011339static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
11340 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011341 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
11342 Message->getReceiverInterface(),
11343 NSAPI::ClassId_NSMutableArray);
11344 if (!IsMutableArray) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011345 return None;
11346 }
11347
11348 Selector Sel = Message->getSelector();
11349
11350 Optional<NSAPI::NSArrayMethodKind> MKOpt =
11351 S.NSAPIObj->getNSArrayMethodKind(Sel);
11352 if (!MKOpt) {
11353 return None;
11354 }
11355
11356 NSAPI::NSArrayMethodKind MK = *MKOpt;
11357
11358 switch (MK) {
11359 case NSAPI::NSMutableArr_addObject:
11360 case NSAPI::NSMutableArr_insertObjectAtIndex:
11361 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
11362 return 0;
11363 case NSAPI::NSMutableArr_replaceObjectAtIndex:
11364 return 1;
11365
11366 default:
11367 return None;
11368 }
11369
11370 return None;
11371}
11372
11373static
11374Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
11375 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011376 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
11377 Message->getReceiverInterface(),
11378 NSAPI::ClassId_NSMutableDictionary);
11379 if (!IsMutableDictionary) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011380 return None;
11381 }
11382
11383 Selector Sel = Message->getSelector();
11384
11385 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
11386 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
11387 if (!MKOpt) {
11388 return None;
11389 }
11390
11391 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
11392
11393 switch (MK) {
11394 case NSAPI::NSMutableDict_setObjectForKey:
11395 case NSAPI::NSMutableDict_setValueForKey:
11396 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
11397 return 0;
11398
11399 default:
11400 return None;
11401 }
11402
11403 return None;
11404}
11405
11406static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011407 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
11408 Message->getReceiverInterface(),
11409 NSAPI::ClassId_NSMutableSet);
Alex Denisove1d882c2015-03-04 17:55:52 +000011410
Alex Denisov5dfac812015-08-06 04:51:14 +000011411 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
11412 Message->getReceiverInterface(),
11413 NSAPI::ClassId_NSMutableOrderedSet);
11414 if (!IsMutableSet && !IsMutableOrderedSet) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011415 return None;
11416 }
11417
11418 Selector Sel = Message->getSelector();
11419
11420 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
11421 if (!MKOpt) {
11422 return None;
11423 }
11424
11425 NSAPI::NSSetMethodKind MK = *MKOpt;
11426
11427 switch (MK) {
11428 case NSAPI::NSMutableSet_addObject:
11429 case NSAPI::NSOrderedSet_setObjectAtIndex:
11430 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
11431 case NSAPI::NSOrderedSet_insertObjectAtIndex:
11432 return 0;
11433 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
11434 return 1;
11435 }
11436
11437 return None;
11438}
11439
11440void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
11441 if (!Message->isInstanceMessage()) {
11442 return;
11443 }
11444
11445 Optional<int> ArgOpt;
11446
11447 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
11448 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
11449 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
11450 return;
11451 }
11452
11453 int ArgIndex = *ArgOpt;
11454
Alex Denisove1d882c2015-03-04 17:55:52 +000011455 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
11456 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
11457 Arg = OE->getSourceExpr()->IgnoreImpCasts();
11458 }
11459
Alex Denisov5dfac812015-08-06 04:51:14 +000011460 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011461 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011462 if (ArgRE->isObjCSelfExpr()) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011463 Diag(Message->getSourceRange().getBegin(),
11464 diag::warn_objc_circular_container)
Alex Denisov5dfac812015-08-06 04:51:14 +000011465 << ArgRE->getDecl()->getName() << StringRef("super");
Alex Denisove1d882c2015-03-04 17:55:52 +000011466 }
11467 }
Alex Denisov5dfac812015-08-06 04:51:14 +000011468 } else {
11469 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
11470
11471 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
11472 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
11473 }
11474
11475 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
11476 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
11477 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
11478 ValueDecl *Decl = ReceiverRE->getDecl();
11479 Diag(Message->getSourceRange().getBegin(),
11480 diag::warn_objc_circular_container)
11481 << Decl->getName() << Decl->getName();
11482 if (!ArgRE->isObjCSelfExpr()) {
11483 Diag(Decl->getLocation(),
11484 diag::note_objc_circular_container_declared_here)
11485 << Decl->getName();
11486 }
11487 }
11488 }
11489 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
11490 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
11491 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
11492 ObjCIvarDecl *Decl = IvarRE->getDecl();
11493 Diag(Message->getSourceRange().getBegin(),
11494 diag::warn_objc_circular_container)
11495 << Decl->getName() << Decl->getName();
11496 Diag(Decl->getLocation(),
11497 diag::note_objc_circular_container_declared_here)
11498 << Decl->getName();
11499 }
Alex Denisove1d882c2015-03-04 17:55:52 +000011500 }
11501 }
11502 }
Alex Denisove1d882c2015-03-04 17:55:52 +000011503}
11504
John McCall31168b02011-06-15 23:02:42 +000011505/// Check a message send to see if it's likely to cause a retain cycle.
11506void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
11507 // Only check instance methods whose selector looks like a setter.
11508 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
11509 return;
11510
11511 // Try to find a variable that the receiver is strongly owned by.
11512 RetainCycleOwner owner;
11513 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011514 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +000011515 return;
11516 } else {
11517 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
11518 owner.Variable = getCurMethodDecl()->getSelfDecl();
11519 owner.Loc = msg->getSuperLoc();
11520 owner.Range = msg->getSuperLoc();
11521 }
11522
11523 // Check whether the receiver is captured by any of the arguments.
11524 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
11525 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
11526 return diagnoseRetainCycle(*this, capturer, owner);
11527}
11528
11529/// Check a property assign to see if it's likely to cause a retain cycle.
11530void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
11531 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011532 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +000011533 return;
11534
11535 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
11536 diagnoseRetainCycle(*this, capturer, owner);
11537}
11538
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000011539void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
11540 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +000011541 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000011542 return;
11543
11544 // Because we don't have an expression for the variable, we have to set the
11545 // location explicitly here.
11546 Owner.Loc = Var->getLocation();
11547 Owner.Range = Var->getSourceRange();
11548
11549 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
11550 diagnoseRetainCycle(*this, Capturer, Owner);
11551}
11552
Ted Kremenek9304da92012-12-21 08:04:28 +000011553static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
11554 Expr *RHS, bool isProperty) {
11555 // Check if RHS is an Objective-C object literal, which also can get
11556 // immediately zapped in a weak reference. Note that we explicitly
11557 // allow ObjCStringLiterals, since those are designed to never really die.
11558 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000011559
Ted Kremenek64873352012-12-21 22:46:35 +000011560 // This enum needs to match with the 'select' in
11561 // warn_objc_arc_literal_assign (off-by-1).
11562 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
11563 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
11564 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000011565
11566 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +000011567 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +000011568 << (isProperty ? 0 : 1)
11569 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000011570
11571 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +000011572}
11573
Ted Kremenekc1f014a2012-12-21 19:45:30 +000011574static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
11575 Qualifiers::ObjCLifetime LT,
11576 Expr *RHS, bool isProperty) {
11577 // Strip off any implicit cast added to get to the one ARC-specific.
11578 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
11579 if (cast->getCastKind() == CK_ARCConsumeObject) {
11580 S.Diag(Loc, diag::warn_arc_retained_assign)
11581 << (LT == Qualifiers::OCL_ExplicitNone)
11582 << (isProperty ? 0 : 1)
11583 << RHS->getSourceRange();
11584 return true;
11585 }
11586 RHS = cast->getSubExpr();
11587 }
11588
11589 if (LT == Qualifiers::OCL_Weak &&
11590 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
11591 return true;
11592
11593 return false;
11594}
11595
Ted Kremenekb36234d2012-12-21 08:04:20 +000011596bool Sema::checkUnsafeAssigns(SourceLocation Loc,
11597 QualType LHS, Expr *RHS) {
11598 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
11599
11600 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
11601 return false;
11602
11603 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
11604 return true;
11605
11606 return false;
11607}
11608
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011609void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
11610 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011611 QualType LHSType;
11612 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +000011613 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011614 ObjCPropertyRefExpr *PRE
11615 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
11616 if (PRE && !PRE->isImplicitProperty()) {
11617 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11618 if (PD)
11619 LHSType = PD->getType();
11620 }
11621
11622 if (LHSType.isNull())
11623 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +000011624
11625 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
11626
11627 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000011628 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +000011629 getCurFunction()->markSafeWeakUse(LHS);
11630 }
11631
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011632 if (checkUnsafeAssigns(Loc, LHSType, RHS))
11633 return;
Jordan Rose657b5f42012-09-28 22:21:35 +000011634
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011635 // FIXME. Check for other life times.
11636 if (LT != Qualifiers::OCL_None)
11637 return;
11638
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011639 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011640 if (PRE->isImplicitProperty())
11641 return;
11642 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11643 if (!PD)
11644 return;
11645
Bill Wendling44426052012-12-20 19:22:21 +000011646 unsigned Attributes = PD->getPropertyAttributes();
11647 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011648 // when 'assign' attribute was not explicitly specified
11649 // by user, ignore it and rely on property type itself
11650 // for lifetime info.
11651 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
11652 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
11653 LHSType->isObjCRetainableType())
11654 return;
11655
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011656 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +000011657 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011658 Diag(Loc, diag::warn_arc_retained_property_assign)
11659 << RHS->getSourceRange();
11660 return;
11661 }
11662 RHS = cast->getSubExpr();
11663 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011664 }
Bill Wendling44426052012-12-20 19:22:21 +000011665 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +000011666 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
11667 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +000011668 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011669 }
11670}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011671
11672//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
11673
11674namespace {
11675bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
11676 SourceLocation StmtLoc,
11677 const NullStmt *Body) {
11678 // Do not warn if the body is a macro that expands to nothing, e.g:
11679 //
11680 // #define CALL(x)
11681 // if (condition)
11682 // CALL(0);
11683 //
11684 if (Body->hasLeadingEmptyMacro())
11685 return false;
11686
11687 // Get line numbers of statement and body.
11688 bool StmtLineInvalid;
Dmitri Gribenkoad80af82015-03-15 01:08:23 +000011689 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011690 &StmtLineInvalid);
11691 if (StmtLineInvalid)
11692 return false;
11693
11694 bool BodyLineInvalid;
11695 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
11696 &BodyLineInvalid);
11697 if (BodyLineInvalid)
11698 return false;
11699
11700 // Warn if null statement and body are on the same line.
11701 if (StmtLine != BodyLine)
11702 return false;
11703
11704 return true;
11705}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011706} // end anonymous namespace
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011707
11708void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
11709 const Stmt *Body,
11710 unsigned DiagID) {
11711 // Since this is a syntactic check, don't emit diagnostic for template
11712 // instantiations, this just adds noise.
11713 if (CurrentInstantiationScope)
11714 return;
11715
11716 // The body should be a null statement.
11717 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11718 if (!NBody)
11719 return;
11720
11721 // Do the usual checks.
11722 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11723 return;
11724
11725 Diag(NBody->getSemiLoc(), DiagID);
11726 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11727}
11728
11729void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
11730 const Stmt *PossibleBody) {
11731 assert(!CurrentInstantiationScope); // Ensured by caller
11732
11733 SourceLocation StmtLoc;
11734 const Stmt *Body;
11735 unsigned DiagID;
11736 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
11737 StmtLoc = FS->getRParenLoc();
11738 Body = FS->getBody();
11739 DiagID = diag::warn_empty_for_body;
11740 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
11741 StmtLoc = WS->getCond()->getSourceRange().getEnd();
11742 Body = WS->getBody();
11743 DiagID = diag::warn_empty_while_body;
11744 } else
11745 return; // Neither `for' nor `while'.
11746
11747 // The body should be a null statement.
11748 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11749 if (!NBody)
11750 return;
11751
11752 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000011753 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011754 return;
11755
11756 // Do the usual checks.
11757 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11758 return;
11759
11760 // `for(...);' and `while(...);' are popular idioms, so in order to keep
11761 // noise level low, emit diagnostics only if for/while is followed by a
11762 // CompoundStmt, e.g.:
11763 // for (int i = 0; i < n; i++);
11764 // {
11765 // a(i);
11766 // }
11767 // or if for/while is followed by a statement with more indentation
11768 // than for/while itself:
11769 // for (int i = 0; i < n; i++);
11770 // a(i);
11771 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
11772 if (!ProbableTypo) {
11773 bool BodyColInvalid;
11774 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
11775 PossibleBody->getLocStart(),
11776 &BodyColInvalid);
11777 if (BodyColInvalid)
11778 return;
11779
11780 bool StmtColInvalid;
11781 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
11782 S->getLocStart(),
11783 &StmtColInvalid);
11784 if (StmtColInvalid)
11785 return;
11786
11787 if (BodyCol > StmtCol)
11788 ProbableTypo = true;
11789 }
11790
11791 if (ProbableTypo) {
11792 Diag(NBody->getSemiLoc(), DiagID);
11793 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11794 }
11795}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011796
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011797//===--- CHECK: Warn on self move with std::move. -------------------------===//
11798
11799/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
11800void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
11801 SourceLocation OpLoc) {
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011802 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
11803 return;
11804
Richard Smith51ec0cf2017-02-21 01:17:38 +000011805 if (inTemplateInstantiation())
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011806 return;
11807
11808 // Strip parens and casts away.
11809 LHSExpr = LHSExpr->IgnoreParenImpCasts();
11810 RHSExpr = RHSExpr->IgnoreParenImpCasts();
11811
11812 // Check for a call expression
11813 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
11814 if (!CE || CE->getNumArgs() != 1)
11815 return;
11816
11817 // Check for a call to std::move
Nico Weberb688d132017-09-28 16:16:39 +000011818 if (!CE->isCallToStdMove())
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011819 return;
11820
11821 // Get argument from std::move
11822 RHSExpr = CE->getArg(0);
11823
11824 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
11825 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
11826
11827 // Two DeclRefExpr's, check that the decls are the same.
11828 if (LHSDeclRef && RHSDeclRef) {
11829 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11830 return;
11831 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11832 RHSDeclRef->getDecl()->getCanonicalDecl())
11833 return;
11834
11835 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11836 << LHSExpr->getSourceRange()
11837 << RHSExpr->getSourceRange();
11838 return;
11839 }
11840
11841 // Member variables require a different approach to check for self moves.
11842 // MemberExpr's are the same if every nested MemberExpr refers to the same
11843 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
11844 // the base Expr's are CXXThisExpr's.
11845 const Expr *LHSBase = LHSExpr;
11846 const Expr *RHSBase = RHSExpr;
11847 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
11848 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
11849 if (!LHSME || !RHSME)
11850 return;
11851
11852 while (LHSME && RHSME) {
11853 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
11854 RHSME->getMemberDecl()->getCanonicalDecl())
11855 return;
11856
11857 LHSBase = LHSME->getBase();
11858 RHSBase = RHSME->getBase();
11859 LHSME = dyn_cast<MemberExpr>(LHSBase);
11860 RHSME = dyn_cast<MemberExpr>(RHSBase);
11861 }
11862
11863 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
11864 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
11865 if (LHSDeclRef && RHSDeclRef) {
11866 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11867 return;
11868 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11869 RHSDeclRef->getDecl()->getCanonicalDecl())
11870 return;
11871
11872 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11873 << LHSExpr->getSourceRange()
11874 << RHSExpr->getSourceRange();
11875 return;
11876 }
11877
11878 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
11879 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11880 << LHSExpr->getSourceRange()
11881 << RHSExpr->getSourceRange();
11882}
11883
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011884//===--- Layout compatibility ----------------------------------------------//
11885
11886namespace {
11887
11888bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
11889
11890/// \brief Check if two enumeration types are layout-compatible.
11891bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
11892 // C++11 [dcl.enum] p8:
11893 // Two enumeration types are layout-compatible if they have the same
11894 // underlying type.
11895 return ED1->isComplete() && ED2->isComplete() &&
11896 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
11897}
11898
11899/// \brief Check if two fields are layout-compatible.
11900bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
11901 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
11902 return false;
11903
11904 if (Field1->isBitField() != Field2->isBitField())
11905 return false;
11906
11907 if (Field1->isBitField()) {
11908 // Make sure that the bit-fields are the same length.
11909 unsigned Bits1 = Field1->getBitWidthValue(C);
11910 unsigned Bits2 = Field2->getBitWidthValue(C);
11911
11912 if (Bits1 != Bits2)
11913 return false;
11914 }
11915
11916 return true;
11917}
11918
11919/// \brief Check if two standard-layout structs are layout-compatible.
11920/// (C++11 [class.mem] p17)
11921bool isLayoutCompatibleStruct(ASTContext &C,
11922 RecordDecl *RD1,
11923 RecordDecl *RD2) {
11924 // If both records are C++ classes, check that base classes match.
11925 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
11926 // If one of records is a CXXRecordDecl we are in C++ mode,
11927 // thus the other one is a CXXRecordDecl, too.
11928 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
11929 // Check number of base classes.
11930 if (D1CXX->getNumBases() != D2CXX->getNumBases())
11931 return false;
11932
11933 // Check the base classes.
11934 for (CXXRecordDecl::base_class_const_iterator
11935 Base1 = D1CXX->bases_begin(),
11936 BaseEnd1 = D1CXX->bases_end(),
11937 Base2 = D2CXX->bases_begin();
11938 Base1 != BaseEnd1;
11939 ++Base1, ++Base2) {
11940 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
11941 return false;
11942 }
11943 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
11944 // If only RD2 is a C++ class, it should have zero base classes.
11945 if (D2CXX->getNumBases() > 0)
11946 return false;
11947 }
11948
11949 // Check the fields.
11950 RecordDecl::field_iterator Field2 = RD2->field_begin(),
11951 Field2End = RD2->field_end(),
11952 Field1 = RD1->field_begin(),
11953 Field1End = RD1->field_end();
11954 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
11955 if (!isLayoutCompatible(C, *Field1, *Field2))
11956 return false;
11957 }
11958 if (Field1 != Field1End || Field2 != Field2End)
11959 return false;
11960
11961 return true;
11962}
11963
11964/// \brief Check if two standard-layout unions are layout-compatible.
11965/// (C++11 [class.mem] p18)
11966bool isLayoutCompatibleUnion(ASTContext &C,
11967 RecordDecl *RD1,
11968 RecordDecl *RD2) {
11969 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011970 for (auto *Field2 : RD2->fields())
11971 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011972
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011973 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011974 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
11975 I = UnmatchedFields.begin(),
11976 E = UnmatchedFields.end();
11977
11978 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011979 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011980 bool Result = UnmatchedFields.erase(*I);
11981 (void) Result;
11982 assert(Result);
11983 break;
11984 }
11985 }
11986 if (I == E)
11987 return false;
11988 }
11989
11990 return UnmatchedFields.empty();
11991}
11992
11993bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
11994 if (RD1->isUnion() != RD2->isUnion())
11995 return false;
11996
11997 if (RD1->isUnion())
11998 return isLayoutCompatibleUnion(C, RD1, RD2);
11999 else
12000 return isLayoutCompatibleStruct(C, RD1, RD2);
12001}
12002
12003/// \brief Check if two types are layout-compatible in C++11 sense.
12004bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
12005 if (T1.isNull() || T2.isNull())
12006 return false;
12007
12008 // C++11 [basic.types] p11:
12009 // If two types T1 and T2 are the same type, then T1 and T2 are
12010 // layout-compatible types.
12011 if (C.hasSameType(T1, T2))
12012 return true;
12013
12014 T1 = T1.getCanonicalType().getUnqualifiedType();
12015 T2 = T2.getCanonicalType().getUnqualifiedType();
12016
12017 const Type::TypeClass TC1 = T1->getTypeClass();
12018 const Type::TypeClass TC2 = T2->getTypeClass();
12019
12020 if (TC1 != TC2)
12021 return false;
12022
12023 if (TC1 == Type::Enum) {
12024 return isLayoutCompatible(C,
12025 cast<EnumType>(T1)->getDecl(),
12026 cast<EnumType>(T2)->getDecl());
12027 } else if (TC1 == Type::Record) {
12028 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
12029 return false;
12030
12031 return isLayoutCompatible(C,
12032 cast<RecordType>(T1)->getDecl(),
12033 cast<RecordType>(T2)->getDecl());
12034 }
12035
12036 return false;
12037}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000012038} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012039
12040//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
12041
12042namespace {
12043/// \brief Given a type tag expression find the type tag itself.
12044///
12045/// \param TypeExpr Type tag expression, as it appears in user's code.
12046///
12047/// \param VD Declaration of an identifier that appears in a type tag.
12048///
12049/// \param MagicValue Type tag magic value.
12050bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
12051 const ValueDecl **VD, uint64_t *MagicValue) {
12052 while(true) {
12053 if (!TypeExpr)
12054 return false;
12055
12056 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
12057
12058 switch (TypeExpr->getStmtClass()) {
12059 case Stmt::UnaryOperatorClass: {
12060 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
12061 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
12062 TypeExpr = UO->getSubExpr();
12063 continue;
12064 }
12065 return false;
12066 }
12067
12068 case Stmt::DeclRefExprClass: {
12069 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
12070 *VD = DRE->getDecl();
12071 return true;
12072 }
12073
12074 case Stmt::IntegerLiteralClass: {
12075 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
12076 llvm::APInt MagicValueAPInt = IL->getValue();
12077 if (MagicValueAPInt.getActiveBits() <= 64) {
12078 *MagicValue = MagicValueAPInt.getZExtValue();
12079 return true;
12080 } else
12081 return false;
12082 }
12083
12084 case Stmt::BinaryConditionalOperatorClass:
12085 case Stmt::ConditionalOperatorClass: {
12086 const AbstractConditionalOperator *ACO =
12087 cast<AbstractConditionalOperator>(TypeExpr);
12088 bool Result;
12089 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
12090 if (Result)
12091 TypeExpr = ACO->getTrueExpr();
12092 else
12093 TypeExpr = ACO->getFalseExpr();
12094 continue;
12095 }
12096 return false;
12097 }
12098
12099 case Stmt::BinaryOperatorClass: {
12100 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
12101 if (BO->getOpcode() == BO_Comma) {
12102 TypeExpr = BO->getRHS();
12103 continue;
12104 }
12105 return false;
12106 }
12107
12108 default:
12109 return false;
12110 }
12111 }
12112}
12113
12114/// \brief Retrieve the C type corresponding to type tag TypeExpr.
12115///
12116/// \param TypeExpr Expression that specifies a type tag.
12117///
12118/// \param MagicValues Registered magic values.
12119///
12120/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
12121/// kind.
12122///
12123/// \param TypeInfo Information about the corresponding C type.
12124///
12125/// \returns true if the corresponding C type was found.
12126bool GetMatchingCType(
12127 const IdentifierInfo *ArgumentKind,
12128 const Expr *TypeExpr, const ASTContext &Ctx,
12129 const llvm::DenseMap<Sema::TypeTagMagicValue,
12130 Sema::TypeTagData> *MagicValues,
12131 bool &FoundWrongKind,
12132 Sema::TypeTagData &TypeInfo) {
12133 FoundWrongKind = false;
12134
12135 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +000012136 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012137
12138 uint64_t MagicValue;
12139
12140 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
12141 return false;
12142
12143 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +000012144 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012145 if (I->getArgumentKind() != ArgumentKind) {
12146 FoundWrongKind = true;
12147 return false;
12148 }
12149 TypeInfo.Type = I->getMatchingCType();
12150 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
12151 TypeInfo.MustBeNull = I->getMustBeNull();
12152 return true;
12153 }
12154 return false;
12155 }
12156
12157 if (!MagicValues)
12158 return false;
12159
12160 llvm::DenseMap<Sema::TypeTagMagicValue,
12161 Sema::TypeTagData>::const_iterator I =
12162 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
12163 if (I == MagicValues->end())
12164 return false;
12165
12166 TypeInfo = I->second;
12167 return true;
12168}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000012169} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012170
12171void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
12172 uint64_t MagicValue, QualType Type,
12173 bool LayoutCompatible,
12174 bool MustBeNull) {
12175 if (!TypeTagForDatatypeMagicValues)
12176 TypeTagForDatatypeMagicValues.reset(
12177 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
12178
12179 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
12180 (*TypeTagForDatatypeMagicValues)[Magic] =
12181 TypeTagData(Type, LayoutCompatible, MustBeNull);
12182}
12183
12184namespace {
12185bool IsSameCharType(QualType T1, QualType T2) {
12186 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
12187 if (!BT1)
12188 return false;
12189
12190 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
12191 if (!BT2)
12192 return false;
12193
12194 BuiltinType::Kind T1Kind = BT1->getKind();
12195 BuiltinType::Kind T2Kind = BT2->getKind();
12196
12197 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
12198 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
12199 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
12200 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
12201}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000012202} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012203
12204void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
12205 const Expr * const *ExprArgs) {
12206 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
12207 bool IsPointerAttr = Attr->getIsPointer();
12208
12209 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
12210 bool FoundWrongKind;
12211 TypeTagData TypeInfo;
12212 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
12213 TypeTagForDatatypeMagicValues.get(),
12214 FoundWrongKind, TypeInfo)) {
12215 if (FoundWrongKind)
12216 Diag(TypeTagExpr->getExprLoc(),
12217 diag::warn_type_tag_for_datatype_wrong_kind)
12218 << TypeTagExpr->getSourceRange();
12219 return;
12220 }
12221
12222 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
12223 if (IsPointerAttr) {
12224 // Skip implicit cast of pointer to `void *' (as a function argument).
12225 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +000012226 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +000012227 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012228 ArgumentExpr = ICE->getSubExpr();
12229 }
12230 QualType ArgumentType = ArgumentExpr->getType();
12231
12232 // Passing a `void*' pointer shouldn't trigger a warning.
12233 if (IsPointerAttr && ArgumentType->isVoidPointerType())
12234 return;
12235
12236 if (TypeInfo.MustBeNull) {
12237 // Type tag with matching void type requires a null pointer.
12238 if (!ArgumentExpr->isNullPointerConstant(Context,
12239 Expr::NPC_ValueDependentIsNotNull)) {
12240 Diag(ArgumentExpr->getExprLoc(),
12241 diag::warn_type_safety_null_pointer_required)
12242 << ArgumentKind->getName()
12243 << ArgumentExpr->getSourceRange()
12244 << TypeTagExpr->getSourceRange();
12245 }
12246 return;
12247 }
12248
12249 QualType RequiredType = TypeInfo.Type;
12250 if (IsPointerAttr)
12251 RequiredType = Context.getPointerType(RequiredType);
12252
12253 bool mismatch = false;
12254 if (!TypeInfo.LayoutCompatible) {
12255 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
12256
12257 // C++11 [basic.fundamental] p1:
12258 // Plain char, signed char, and unsigned char are three distinct types.
12259 //
12260 // But we treat plain `char' as equivalent to `signed char' or `unsigned
12261 // char' depending on the current char signedness mode.
12262 if (mismatch)
12263 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
12264 RequiredType->getPointeeType())) ||
12265 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
12266 mismatch = false;
12267 } else
12268 if (IsPointerAttr)
12269 mismatch = !isLayoutCompatible(Context,
12270 ArgumentType->getPointeeType(),
12271 RequiredType->getPointeeType());
12272 else
12273 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
12274
12275 if (mismatch)
12276 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +000012277 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012278 << TypeInfo.LayoutCompatible << RequiredType
12279 << ArgumentExpr->getSourceRange()
12280 << TypeTagExpr->getSourceRange();
12281}
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012282
12283void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
12284 CharUnits Alignment) {
12285 MisalignedMembers.emplace_back(E, RD, MD, Alignment);
12286}
12287
12288void Sema::DiagnoseMisalignedMembers() {
12289 for (MisalignedMember &m : MisalignedMembers) {
Alex Lorenz014181e2016-10-05 09:27:48 +000012290 const NamedDecl *ND = m.RD;
12291 if (ND->getName().empty()) {
12292 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
12293 ND = TD;
12294 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012295 Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member)
Alex Lorenz014181e2016-10-05 09:27:48 +000012296 << m.MD << ND << m.E->getSourceRange();
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012297 }
12298 MisalignedMembers.clear();
12299}
12300
12301void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012302 E = E->IgnoreParens();
12303 if (!T->isPointerType() && !T->isIntegerType())
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012304 return;
12305 if (isa<UnaryOperator>(E) &&
12306 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
12307 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
12308 if (isa<MemberExpr>(Op)) {
12309 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
12310 MisalignedMember(Op));
12311 if (MA != MisalignedMembers.end() &&
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012312 (T->isIntegerType() ||
12313 (T->isPointerType() &&
12314 Context.getTypeAlignInChars(T->getPointeeType()) <= MA->Alignment)))
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012315 MisalignedMembers.erase(MA);
12316 }
12317 }
12318}
12319
12320void Sema::RefersToMemberWithReducedAlignment(
12321 Expr *E,
Benjamin Kramera8c3e672016-12-12 14:41:19 +000012322 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
12323 Action) {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012324 const auto *ME = dyn_cast<MemberExpr>(E);
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012325 if (!ME)
12326 return;
12327
Roger Ferrer Ibanez9f963472017-03-13 13:18:21 +000012328 // No need to check expressions with an __unaligned-qualified type.
12329 if (E->getType().getQualifiers().hasUnaligned())
12330 return;
12331
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012332 // For a chain of MemberExpr like "a.b.c.d" this list
12333 // will keep FieldDecl's like [d, c, b].
12334 SmallVector<FieldDecl *, 4> ReverseMemberChain;
12335 const MemberExpr *TopME = nullptr;
12336 bool AnyIsPacked = false;
12337 do {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012338 QualType BaseType = ME->getBase()->getType();
12339 if (ME->isArrow())
12340 BaseType = BaseType->getPointeeType();
12341 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
Olivier Goffart67049f02017-07-07 09:38:59 +000012342 if (RD->isInvalidDecl())
12343 return;
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012344
12345 ValueDecl *MD = ME->getMemberDecl();
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012346 auto *FD = dyn_cast<FieldDecl>(MD);
12347 // We do not care about non-data members.
12348 if (!FD || FD->isInvalidDecl())
12349 return;
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012350
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012351 AnyIsPacked =
12352 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
12353 ReverseMemberChain.push_back(FD);
12354
12355 TopME = ME;
12356 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
12357 } while (ME);
12358 assert(TopME && "We did not compute a topmost MemberExpr!");
12359
12360 // Not the scope of this diagnostic.
12361 if (!AnyIsPacked)
12362 return;
12363
12364 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
12365 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
12366 // TODO: The innermost base of the member expression may be too complicated.
12367 // For now, just disregard these cases. This is left for future
12368 // improvement.
12369 if (!DRE && !isa<CXXThisExpr>(TopBase))
12370 return;
12371
12372 // Alignment expected by the whole expression.
12373 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
12374
12375 // No need to do anything else with this case.
12376 if (ExpectedAlignment.isOne())
12377 return;
12378
12379 // Synthesize offset of the whole access.
12380 CharUnits Offset;
12381 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
12382 I++) {
12383 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
12384 }
12385
12386 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
12387 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
12388 ReverseMemberChain.back()->getParent()->getTypeForDecl());
12389
12390 // The base expression of the innermost MemberExpr may give
12391 // stronger guarantees than the class containing the member.
12392 if (DRE && !TopME->isArrow()) {
12393 const ValueDecl *VD = DRE->getDecl();
12394 if (!VD->getType()->isReferenceType())
12395 CompleteObjectAlignment =
12396 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
12397 }
12398
12399 // Check if the synthesized offset fulfills the alignment.
12400 if (Offset % ExpectedAlignment != 0 ||
12401 // It may fulfill the offset it but the effective alignment may still be
12402 // lower than the expected expression alignment.
12403 CompleteObjectAlignment < ExpectedAlignment) {
12404 // If this happens, we want to determine a sensible culprit of this.
12405 // Intuitively, watching the chain of member expressions from right to
12406 // left, we start with the required alignment (as required by the field
12407 // type) but some packed attribute in that chain has reduced the alignment.
12408 // It may happen that another packed structure increases it again. But if
12409 // we are here such increase has not been enough. So pointing the first
12410 // FieldDecl that either is packed or else its RecordDecl is,
12411 // seems reasonable.
12412 FieldDecl *FD = nullptr;
12413 CharUnits Alignment;
12414 for (FieldDecl *FDI : ReverseMemberChain) {
12415 if (FDI->hasAttr<PackedAttr>() ||
12416 FDI->getParent()->hasAttr<PackedAttr>()) {
12417 FD = FDI;
12418 Alignment = std::min(
12419 Context.getTypeAlignInChars(FD->getType()),
12420 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
12421 break;
12422 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012423 }
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012424 assert(FD && "We did not find a packed FieldDecl!");
12425 Action(E, FD->getParent(), FD, Alignment);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012426 }
12427}
12428
12429void Sema::CheckAddressOfPackedMember(Expr *rhs) {
12430 using namespace std::placeholders;
12431 RefersToMemberWithReducedAlignment(
12432 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
12433 _2, _3, _4));
12434}
12435