blob: 87634ad57e51490147f6974bf20576b03bafc09d [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:
836 if (SemaBuiltinVAStartARM(TheCall))
837 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 Abdulrasool202aac12014-07-22 02:01:04 +00003927bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
3928 // 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
Benjamin Kramere0ca6e12015-03-01 18:09:50 +00003946 const struct {
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00003947 unsigned ArgNo;
3948 QualType Type;
3949 } ArgumentTypes[] = {
3950 { 1, Context.getPointerType(Context.CharTy.withConst()) },
3951 { 2, Context.getSizeType() },
3952 };
3953
3954 for (const auto &AT : ArgumentTypes) {
3955 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
3956 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
3957 continue;
3958 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
3959 << Arg->getType() << AT.Type << 1 /* different class */
3960 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
3961 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
3962 }
3963
3964 return false;
3965}
3966
Chris Lattner2da14fb2007-12-20 00:26:33 +00003967/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
3968/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00003969bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
3970 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00003971 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00003972 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00003973 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00003974 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003975 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003976 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00003977 << SourceRange(TheCall->getArg(2)->getLocStart(),
3978 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00003979
John Wiegley01296292011-04-08 18:41:53 +00003980 ExprResult OrigArg0 = TheCall->getArg(0);
3981 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00003982
Chris Lattner2da14fb2007-12-20 00:26:33 +00003983 // Do standard promotions between the two arguments, returning their common
3984 // type.
Chris Lattner08464942007-12-28 05:29:59 +00003985 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00003986 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
3987 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00003988
3989 // Make sure any conversions are pushed back into the call; this is
3990 // type safe since unordered compare builtins are declared as "_Bool
3991 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00003992 TheCall->setArg(0, OrigArg0.get());
3993 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00003994
John Wiegley01296292011-04-08 18:41:53 +00003995 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00003996 return false;
3997
Chris Lattner2da14fb2007-12-20 00:26:33 +00003998 // If the common type isn't a real floating type, then the arguments were
3999 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00004000 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00004001 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004002 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00004003 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
4004 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00004005
Chris Lattner2da14fb2007-12-20 00:26:33 +00004006 return false;
4007}
4008
Benjamin Kramer634fc102010-02-15 22:42:31 +00004009/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
4010/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00004011/// to check everything. We expect the last argument to be a floating point
4012/// value.
4013bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
4014 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00004015 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00004016 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00004017 if (TheCall->getNumArgs() > NumArgs)
4018 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00004019 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004020 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00004021 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00004022 (*(TheCall->arg_end()-1))->getLocEnd());
4023
Benjamin Kramer64aae502010-02-16 10:07:31 +00004024 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00004025
Eli Friedman7e4faac2009-08-31 20:06:00 +00004026 if (OrigArg->isTypeDependent())
4027 return false;
4028
Chris Lattner68784ef2010-05-06 05:50:07 +00004029 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00004030 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00004031 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00004032 diag::err_typecheck_call_invalid_unary_fp)
4033 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00004034
Neil Hickey88c0fac2016-12-13 16:22:50 +00004035 // If this is an implicit conversion from float -> float or double, remove it.
Chris Lattner68784ef2010-05-06 05:50:07 +00004036 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
Neil Hickey7b5ddab2016-12-14 13:18:48 +00004037 // Only remove standard FloatCasts, leaving other casts inplace
4038 if (Cast->getCastKind() == CK_FloatingCast) {
4039 Expr *CastArg = Cast->getSubExpr();
4040 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
4041 assert((Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
4042 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float)) &&
4043 "promotion from float to either float or double is the only expected cast here");
4044 Cast->setSubExpr(nullptr);
4045 TheCall->setArg(NumArgs-1, CastArg);
4046 }
Chris Lattner68784ef2010-05-06 05:50:07 +00004047 }
4048 }
4049
Eli Friedman7e4faac2009-08-31 20:06:00 +00004050 return false;
4051}
4052
Tony Jiangbbc48e92017-05-24 15:13:32 +00004053// Customized Sema Checking for VSX builtins that have the following signature:
4054// vector [...] builtinName(vector [...], vector [...], const int);
4055// Which takes the same type of vectors (any legal vector type) for the first
4056// two arguments and takes compile time constant for the third argument.
4057// Example builtins are :
4058// vector double vec_xxpermdi(vector double, vector double, int);
4059// vector short vec_xxsldwi(vector short, vector short, int);
4060bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
4061 unsigned ExpectedNumArgs = 3;
4062 if (TheCall->getNumArgs() < ExpectedNumArgs)
4063 return Diag(TheCall->getLocEnd(),
4064 diag::err_typecheck_call_too_few_args_at_least)
4065 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
4066 << TheCall->getSourceRange();
4067
4068 if (TheCall->getNumArgs() > ExpectedNumArgs)
4069 return Diag(TheCall->getLocEnd(),
4070 diag::err_typecheck_call_too_many_args_at_most)
4071 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
4072 << TheCall->getSourceRange();
4073
4074 // Check the third argument is a compile time constant
4075 llvm::APSInt Value;
4076 if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
4077 return Diag(TheCall->getLocStart(),
4078 diag::err_vsx_builtin_nonconstant_argument)
4079 << 3 /* argument index */ << TheCall->getDirectCallee()
4080 << SourceRange(TheCall->getArg(2)->getLocStart(),
4081 TheCall->getArg(2)->getLocEnd());
4082
4083 QualType Arg1Ty = TheCall->getArg(0)->getType();
4084 QualType Arg2Ty = TheCall->getArg(1)->getType();
4085
4086 // Check the type of argument 1 and argument 2 are vectors.
4087 SourceLocation BuiltinLoc = TheCall->getLocStart();
4088 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
4089 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
4090 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
4091 << TheCall->getDirectCallee()
4092 << SourceRange(TheCall->getArg(0)->getLocStart(),
4093 TheCall->getArg(1)->getLocEnd());
4094 }
4095
4096 // Check the first two arguments are the same type.
4097 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
4098 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
4099 << TheCall->getDirectCallee()
4100 << SourceRange(TheCall->getArg(0)->getLocStart(),
4101 TheCall->getArg(1)->getLocEnd());
4102 }
4103
4104 // When default clang type checking is turned off and the customized type
4105 // checking is used, the returning type of the function must be explicitly
4106 // set. Otherwise it is _Bool by default.
4107 TheCall->setType(Arg1Ty);
4108
4109 return false;
4110}
4111
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004112/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
4113// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00004114ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00004115 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004116 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00004117 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00004118 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
4119 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004120
Nate Begemana0110022010-06-08 00:16:34 +00004121 // Determine which of the following types of shufflevector we're checking:
4122 // 1) unary, vector mask: (lhs, mask)
Craig Topperb3174a82016-05-18 04:11:25 +00004123 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
Nate Begemana0110022010-06-08 00:16:34 +00004124 QualType resType = TheCall->getArg(0)->getType();
4125 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00004126
Douglas Gregorc25f7662009-05-19 22:10:17 +00004127 if (!TheCall->getArg(0)->isTypeDependent() &&
4128 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00004129 QualType LHSType = TheCall->getArg(0)->getType();
4130 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00004131
Craig Topperbaca3892013-07-29 06:47:04 +00004132 if (!LHSType->isVectorType() || !RHSType->isVectorType())
4133 return ExprError(Diag(TheCall->getLocStart(),
Tony Jiangedc78492017-05-24 14:45:57 +00004134 diag::err_vec_builtin_non_vector)
4135 << TheCall->getDirectCallee()
Craig Topperbaca3892013-07-29 06:47:04 +00004136 << SourceRange(TheCall->getArg(0)->getLocStart(),
4137 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00004138
Nate Begemana0110022010-06-08 00:16:34 +00004139 numElements = LHSType->getAs<VectorType>()->getNumElements();
4140 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00004141
Nate Begemana0110022010-06-08 00:16:34 +00004142 // Check to see if we have a call with 2 vector arguments, the unary shuffle
4143 // with mask. If so, verify that RHS is an integer vector type with the
4144 // same number of elts as lhs.
4145 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00004146 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00004147 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00004148 return ExprError(Diag(TheCall->getLocStart(),
Tony Jiangedc78492017-05-24 14:45:57 +00004149 diag::err_vec_builtin_incompatible_vector)
4150 << TheCall->getDirectCallee()
Craig Topperbaca3892013-07-29 06:47:04 +00004151 << SourceRange(TheCall->getArg(1)->getLocStart(),
4152 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00004153 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00004154 return ExprError(Diag(TheCall->getLocStart(),
Tony Jiangedc78492017-05-24 14:45:57 +00004155 diag::err_vec_builtin_incompatible_vector)
4156 << TheCall->getDirectCallee()
Craig Topperbaca3892013-07-29 06:47:04 +00004157 << SourceRange(TheCall->getArg(0)->getLocStart(),
4158 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00004159 } else if (numElements != numResElements) {
4160 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00004161 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00004162 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00004163 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004164 }
4165
4166 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00004167 if (TheCall->getArg(i)->isTypeDependent() ||
4168 TheCall->getArg(i)->isValueDependent())
4169 continue;
4170
Nate Begemana0110022010-06-08 00:16:34 +00004171 llvm::APSInt Result(32);
4172 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
4173 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00004174 diag::err_shufflevector_nonconstant_argument)
4175 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004176
Craig Topper50ad5b72013-08-03 17:40:38 +00004177 // Allow -1 which will be translated to undef in the IR.
4178 if (Result.isSigned() && Result.isAllOnesValue())
4179 continue;
4180
Chris Lattner7ab824e2008-08-10 02:05:13 +00004181 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004182 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00004183 diag::err_shufflevector_argument_too_large)
4184 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004185 }
4186
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004187 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004188
Chris Lattner7ab824e2008-08-10 02:05:13 +00004189 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004190 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00004191 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004192 }
4193
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004194 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
4195 TheCall->getCallee()->getLocStart(),
4196 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004197}
Chris Lattner43be2e62007-12-19 23:59:04 +00004198
Hal Finkelc4d7c822013-09-18 03:29:45 +00004199/// SemaConvertVectorExpr - Handle __builtin_convertvector
4200ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
4201 SourceLocation BuiltinLoc,
4202 SourceLocation RParenLoc) {
4203 ExprValueKind VK = VK_RValue;
4204 ExprObjectKind OK = OK_Ordinary;
4205 QualType DstTy = TInfo->getType();
4206 QualType SrcTy = E->getType();
4207
4208 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
4209 return ExprError(Diag(BuiltinLoc,
4210 diag::err_convertvector_non_vector)
4211 << E->getSourceRange());
4212 if (!DstTy->isVectorType() && !DstTy->isDependentType())
4213 return ExprError(Diag(BuiltinLoc,
4214 diag::err_convertvector_non_vector_type));
4215
4216 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
4217 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
4218 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
4219 if (SrcElts != DstElts)
4220 return ExprError(Diag(BuiltinLoc,
4221 diag::err_convertvector_incompatible_vector)
4222 << E->getSourceRange());
4223 }
4224
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004225 return new (Context)
4226 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00004227}
4228
Daniel Dunbarb7257262008-07-21 22:59:13 +00004229/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
4230// This is declared to take (const void*, ...) and can take two
4231// optional constant int args.
4232bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00004233 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00004234
Chris Lattner3b054132008-11-19 05:08:23 +00004235 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004236 return Diag(TheCall->getLocEnd(),
4237 diag::err_typecheck_call_too_many_args_at_most)
4238 << 0 /*function call*/ << 3 << NumArgs
4239 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00004240
4241 // Argument 0 is checked for us and the remaining arguments must be
4242 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00004243 for (unsigned i = 1; i != NumArgs; ++i)
4244 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00004245 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004246
Warren Hunt20e4a5d2014-02-21 23:08:53 +00004247 return false;
4248}
4249
Hal Finkelf0417332014-07-17 14:25:55 +00004250/// SemaBuiltinAssume - Handle __assume (MS Extension).
4251// __assume does not evaluate its arguments, and should warn if its argument
4252// has side effects.
4253bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
4254 Expr *Arg = TheCall->getArg(0);
4255 if (Arg->isInstantiationDependent()) return false;
4256
4257 if (Arg->HasSideEffects(Context))
David Majnemer51236642015-02-26 00:57:33 +00004258 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00004259 << Arg->getSourceRange()
4260 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
4261
4262 return false;
4263}
4264
David Majnemer86b1bfa2016-10-31 18:07:57 +00004265/// Handle __builtin_alloca_with_align. This is declared
David Majnemer51169932016-10-31 05:37:48 +00004266/// as (size_t, size_t) where the second size_t must be a power of 2 greater
4267/// than 8.
4268bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
4269 // The alignment must be a constant integer.
4270 Expr *Arg = TheCall->getArg(1);
4271
4272 // We can't check the value of a dependent argument.
4273 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
David Majnemer86b1bfa2016-10-31 18:07:57 +00004274 if (const auto *UE =
4275 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
4276 if (UE->getKind() == UETT_AlignOf)
4277 Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof)
4278 << Arg->getSourceRange();
4279
David Majnemer51169932016-10-31 05:37:48 +00004280 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
4281
4282 if (!Result.isPowerOf2())
4283 return Diag(TheCall->getLocStart(),
4284 diag::err_alignment_not_power_of_two)
4285 << Arg->getSourceRange();
4286
4287 if (Result < Context.getCharWidth())
4288 return Diag(TheCall->getLocStart(), diag::err_alignment_too_small)
4289 << (unsigned)Context.getCharWidth()
4290 << Arg->getSourceRange();
4291
4292 if (Result > INT32_MAX)
4293 return Diag(TheCall->getLocStart(), diag::err_alignment_too_big)
4294 << INT32_MAX
4295 << Arg->getSourceRange();
4296 }
4297
4298 return false;
4299}
4300
4301/// Handle __builtin_assume_aligned. This is declared
Hal Finkelbcc06082014-09-07 22:58:14 +00004302/// as (const void*, size_t, ...) and can take one optional constant int arg.
4303bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
4304 unsigned NumArgs = TheCall->getNumArgs();
4305
4306 if (NumArgs > 3)
4307 return Diag(TheCall->getLocEnd(),
4308 diag::err_typecheck_call_too_many_args_at_most)
4309 << 0 /*function call*/ << 3 << NumArgs
4310 << TheCall->getSourceRange();
4311
4312 // The alignment must be a constant integer.
4313 Expr *Arg = TheCall->getArg(1);
4314
4315 // We can't check the value of a dependent argument.
4316 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
4317 llvm::APSInt Result;
4318 if (SemaBuiltinConstantArg(TheCall, 1, Result))
4319 return true;
4320
4321 if (!Result.isPowerOf2())
4322 return Diag(TheCall->getLocStart(),
4323 diag::err_alignment_not_power_of_two)
4324 << Arg->getSourceRange();
4325 }
4326
4327 if (NumArgs > 2) {
4328 ExprResult Arg(TheCall->getArg(2));
4329 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
4330 Context.getSizeType(), false);
4331 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4332 if (Arg.isInvalid()) return true;
4333 TheCall->setArg(2, Arg.get());
4334 }
Hal Finkelf0417332014-07-17 14:25:55 +00004335
4336 return false;
4337}
4338
Mehdi Amini06d367c2016-10-24 20:39:34 +00004339bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
4340 unsigned BuiltinID =
4341 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
4342 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
4343
4344 unsigned NumArgs = TheCall->getNumArgs();
4345 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
4346 if (NumArgs < NumRequiredArgs) {
4347 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4348 << 0 /* function call */ << NumRequiredArgs << NumArgs
4349 << TheCall->getSourceRange();
4350 }
4351 if (NumArgs >= NumRequiredArgs + 0x100) {
4352 return Diag(TheCall->getLocEnd(),
4353 diag::err_typecheck_call_too_many_args_at_most)
4354 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
4355 << TheCall->getSourceRange();
4356 }
4357 unsigned i = 0;
4358
4359 // For formatting call, check buffer arg.
4360 if (!IsSizeCall) {
4361 ExprResult Arg(TheCall->getArg(i));
4362 InitializedEntity Entity = InitializedEntity::InitializeParameter(
4363 Context, Context.VoidPtrTy, false);
4364 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4365 if (Arg.isInvalid())
4366 return true;
4367 TheCall->setArg(i, Arg.get());
4368 i++;
4369 }
4370
4371 // Check string literal arg.
4372 unsigned FormatIdx = i;
4373 {
4374 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
4375 if (Arg.isInvalid())
4376 return true;
4377 TheCall->setArg(i, Arg.get());
4378 i++;
4379 }
4380
4381 // Make sure variadic args are scalar.
4382 unsigned FirstDataArg = i;
4383 while (i < NumArgs) {
4384 ExprResult Arg = DefaultVariadicArgumentPromotion(
4385 TheCall->getArg(i), VariadicFunction, nullptr);
4386 if (Arg.isInvalid())
4387 return true;
4388 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
4389 if (ArgSize.getQuantity() >= 0x100) {
4390 return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big)
4391 << i << (int)ArgSize.getQuantity() << 0xff
4392 << TheCall->getSourceRange();
4393 }
4394 TheCall->setArg(i, Arg.get());
4395 i++;
4396 }
4397
4398 // Check formatting specifiers. NOTE: We're only doing this for the non-size
4399 // call to avoid duplicate diagnostics.
4400 if (!IsSizeCall) {
4401 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
4402 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
4403 bool Success = CheckFormatArguments(
4404 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
4405 VariadicFunction, TheCall->getLocStart(), SourceRange(),
4406 CheckedVarArgs);
4407 if (!Success)
4408 return true;
4409 }
4410
4411 if (IsSizeCall) {
4412 TheCall->setType(Context.getSizeType());
4413 } else {
4414 TheCall->setType(Context.VoidPtrTy);
4415 }
4416 return false;
4417}
4418
Eric Christopher8d0c6212010-04-17 02:26:23 +00004419/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
4420/// TheCall is a constant expression.
4421bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
4422 llvm::APSInt &Result) {
4423 Expr *Arg = TheCall->getArg(ArgNum);
4424 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4425 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4426
4427 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
4428
4429 if (!Arg->isIntegerConstantExpr(Result, Context))
4430 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00004431 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00004432
Chris Lattnerd545ad12009-09-23 06:06:36 +00004433 return false;
4434}
4435
Richard Sandiford28940af2014-04-16 08:47:51 +00004436/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
4437/// TheCall is a constant expression in the range [Low, High].
4438bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
4439 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00004440 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00004441
4442 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00004443 Expr *Arg = TheCall->getArg(ArgNum);
4444 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00004445 return false;
4446
Eric Christopher8d0c6212010-04-17 02:26:23 +00004447 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00004448 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00004449 return true;
4450
Richard Sandiford28940af2014-04-16 08:47:51 +00004451 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00004452 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00004453 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00004454
4455 return false;
4456}
4457
Simon Dardis1f90f2d2016-10-19 17:50:52 +00004458/// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
4459/// TheCall is a constant expression is a multiple of Num..
4460bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
4461 unsigned Num) {
4462 llvm::APSInt Result;
4463
4464 // We can't check the value of a dependent argument.
4465 Expr *Arg = TheCall->getArg(ArgNum);
4466 if (Arg->isTypeDependent() || Arg->isValueDependent())
4467 return false;
4468
4469 // Check constant-ness first.
4470 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4471 return true;
4472
4473 if (Result.getSExtValue() % Num != 0)
4474 return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple)
4475 << Num << Arg->getSourceRange();
4476
4477 return false;
4478}
4479
Luke Cheeseman59b2d832015-06-15 17:51:01 +00004480/// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
4481/// TheCall is an ARM/AArch64 special register string literal.
4482bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
4483 int ArgNum, unsigned ExpectedFieldNum,
4484 bool AllowName) {
4485 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
4486 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
4487 BuiltinID == ARM::BI__builtin_arm_rsr ||
4488 BuiltinID == ARM::BI__builtin_arm_rsrp ||
4489 BuiltinID == ARM::BI__builtin_arm_wsr ||
4490 BuiltinID == ARM::BI__builtin_arm_wsrp;
4491 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
4492 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
4493 BuiltinID == AArch64::BI__builtin_arm_rsr ||
4494 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
4495 BuiltinID == AArch64::BI__builtin_arm_wsr ||
4496 BuiltinID == AArch64::BI__builtin_arm_wsrp;
4497 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
4498
4499 // We can't check the value of a dependent argument.
4500 Expr *Arg = TheCall->getArg(ArgNum);
4501 if (Arg->isTypeDependent() || Arg->isValueDependent())
4502 return false;
4503
4504 // Check if the argument is a string literal.
4505 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4506 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
4507 << Arg->getSourceRange();
4508
4509 // Check the type of special register given.
4510 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4511 SmallVector<StringRef, 6> Fields;
4512 Reg.split(Fields, ":");
4513
4514 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
4515 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4516 << Arg->getSourceRange();
4517
4518 // If the string is the name of a register then we cannot check that it is
4519 // valid here but if the string is of one the forms described in ACLE then we
4520 // can check that the supplied fields are integers and within the valid
4521 // ranges.
4522 if (Fields.size() > 1) {
4523 bool FiveFields = Fields.size() == 5;
4524
4525 bool ValidString = true;
4526 if (IsARMBuiltin) {
4527 ValidString &= Fields[0].startswith_lower("cp") ||
4528 Fields[0].startswith_lower("p");
4529 if (ValidString)
4530 Fields[0] =
4531 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
4532
4533 ValidString &= Fields[2].startswith_lower("c");
4534 if (ValidString)
4535 Fields[2] = Fields[2].drop_front(1);
4536
4537 if (FiveFields) {
4538 ValidString &= Fields[3].startswith_lower("c");
4539 if (ValidString)
4540 Fields[3] = Fields[3].drop_front(1);
4541 }
4542 }
4543
4544 SmallVector<int, 5> Ranges;
4545 if (FiveFields)
Oleg Ranevskyy85d93a82016-11-18 21:00:08 +00004546 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
Luke Cheeseman59b2d832015-06-15 17:51:01 +00004547 else
4548 Ranges.append({15, 7, 15});
4549
4550 for (unsigned i=0; i<Fields.size(); ++i) {
4551 int IntField;
4552 ValidString &= !Fields[i].getAsInteger(10, IntField);
4553 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
4554 }
4555
4556 if (!ValidString)
4557 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4558 << Arg->getSourceRange();
4559
4560 } else if (IsAArch64Builtin && Fields.size() == 1) {
4561 // If the register name is one of those that appear in the condition below
4562 // and the special register builtin being used is one of the write builtins,
4563 // then we require that the argument provided for writing to the register
4564 // is an integer constant expression. This is because it will be lowered to
4565 // an MSR (immediate) instruction, so we need to know the immediate at
4566 // compile time.
4567 if (TheCall->getNumArgs() != 2)
4568 return false;
4569
4570 std::string RegLower = Reg.lower();
4571 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
4572 RegLower != "pan" && RegLower != "uao")
4573 return false;
4574
4575 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
4576 }
4577
4578 return false;
4579}
4580
Eli Friedmanc97d0142009-05-03 06:04:26 +00004581/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004582/// This checks that the target supports __builtin_longjmp and
4583/// that val is a constant 1.
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004584bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004585 if (!Context.getTargetInfo().hasSjLjLowering())
4586 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
4587 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4588
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004589 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00004590 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00004591
Eric Christopher8d0c6212010-04-17 02:26:23 +00004592 // TODO: This is less than ideal. Overload this to take a value.
4593 if (SemaBuiltinConstantArg(TheCall, 1, Result))
4594 return true;
4595
4596 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004597 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
4598 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
4599
4600 return false;
4601}
4602
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004603/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
4604/// This checks that the target supports __builtin_setjmp.
4605bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
4606 if (!Context.getTargetInfo().hasSjLjLowering())
4607 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
4608 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4609 return false;
4610}
4611
Richard Smithd7293d72013-08-05 18:49:43 +00004612namespace {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004613class UncoveredArgHandler {
4614 enum { Unknown = -1, AllCovered = -2 };
4615 signed FirstUncoveredArg;
4616 SmallVector<const Expr *, 4> DiagnosticExprs;
4617
4618public:
4619 UncoveredArgHandler() : FirstUncoveredArg(Unknown) { }
4620
4621 bool hasUncoveredArg() const {
4622 return (FirstUncoveredArg >= 0);
4623 }
4624
4625 unsigned getUncoveredArg() const {
4626 assert(hasUncoveredArg() && "no uncovered argument");
4627 return FirstUncoveredArg;
4628 }
4629
4630 void setAllCovered() {
4631 // A string has been found with all arguments covered, so clear out
4632 // the diagnostics.
4633 DiagnosticExprs.clear();
4634 FirstUncoveredArg = AllCovered;
4635 }
4636
4637 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
4638 assert(NewFirstUncoveredArg >= 0 && "Outside range");
4639
4640 // Don't update if a previous string covers all arguments.
4641 if (FirstUncoveredArg == AllCovered)
4642 return;
4643
4644 // UncoveredArgHandler tracks the highest uncovered argument index
4645 // and with it all the strings that match this index.
4646 if (NewFirstUncoveredArg == FirstUncoveredArg)
4647 DiagnosticExprs.push_back(StrExpr);
4648 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
4649 DiagnosticExprs.clear();
4650 DiagnosticExprs.push_back(StrExpr);
4651 FirstUncoveredArg = NewFirstUncoveredArg;
4652 }
4653 }
4654
4655 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
4656};
4657
Richard Smithd7293d72013-08-05 18:49:43 +00004658enum StringLiteralCheckType {
4659 SLCT_NotALiteral,
4660 SLCT_UncheckedLiteral,
4661 SLCT_CheckedLiteral
4662};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004663} // end anonymous namespace
Richard Smithd7293d72013-08-05 18:49:43 +00004664
Stephen Hines648c3692016-09-16 01:07:04 +00004665static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
4666 BinaryOperatorKind BinOpKind,
4667 bool AddendIsRight) {
4668 unsigned BitWidth = Offset.getBitWidth();
4669 unsigned AddendBitWidth = Addend.getBitWidth();
4670 // There might be negative interim results.
4671 if (Addend.isUnsigned()) {
4672 Addend = Addend.zext(++AddendBitWidth);
4673 Addend.setIsSigned(true);
4674 }
4675 // Adjust the bit width of the APSInts.
4676 if (AddendBitWidth > BitWidth) {
4677 Offset = Offset.sext(AddendBitWidth);
4678 BitWidth = AddendBitWidth;
4679 } else if (BitWidth > AddendBitWidth) {
4680 Addend = Addend.sext(BitWidth);
4681 }
4682
4683 bool Ov = false;
4684 llvm::APSInt ResOffset = Offset;
4685 if (BinOpKind == BO_Add)
4686 ResOffset = Offset.sadd_ov(Addend, Ov);
4687 else {
4688 assert(AddendIsRight && BinOpKind == BO_Sub &&
4689 "operator must be add or sub with addend on the right");
4690 ResOffset = Offset.ssub_ov(Addend, Ov);
4691 }
4692
4693 // We add an offset to a pointer here so we should support an offset as big as
4694 // possible.
4695 if (Ov) {
4696 assert(BitWidth <= UINT_MAX / 2 && "index (intermediate) result too big");
Stephen Hinesfec73ad2016-09-16 07:21:24 +00004697 Offset = Offset.sext(2 * BitWidth);
Stephen Hines648c3692016-09-16 01:07:04 +00004698 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
4699 return;
4700 }
4701
4702 Offset = ResOffset;
4703}
4704
4705namespace {
4706// This is a wrapper class around StringLiteral to support offsetted string
4707// literals as format strings. It takes the offset into account when returning
4708// the string and its length or the source locations to display notes correctly.
4709class FormatStringLiteral {
4710 const StringLiteral *FExpr;
4711 int64_t Offset;
4712
4713 public:
4714 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
4715 : FExpr(fexpr), Offset(Offset) {}
4716
4717 StringRef getString() const {
4718 return FExpr->getString().drop_front(Offset);
4719 }
4720
4721 unsigned getByteLength() const {
4722 return FExpr->getByteLength() - getCharByteWidth() * Offset;
4723 }
4724 unsigned getLength() const { return FExpr->getLength() - Offset; }
4725 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
4726
4727 StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
4728
4729 QualType getType() const { return FExpr->getType(); }
4730
4731 bool isAscii() const { return FExpr->isAscii(); }
4732 bool isWide() const { return FExpr->isWide(); }
4733 bool isUTF8() const { return FExpr->isUTF8(); }
4734 bool isUTF16() const { return FExpr->isUTF16(); }
4735 bool isUTF32() const { return FExpr->isUTF32(); }
4736 bool isPascal() const { return FExpr->isPascal(); }
4737
4738 SourceLocation getLocationOfByte(
4739 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
4740 const TargetInfo &Target, unsigned *StartToken = nullptr,
4741 unsigned *StartTokenByteOffset = nullptr) const {
4742 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
4743 StartToken, StartTokenByteOffset);
4744 }
4745
4746 SourceLocation getLocStart() const LLVM_READONLY {
4747 return FExpr->getLocStart().getLocWithOffset(Offset);
4748 }
4749 SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); }
4750};
4751} // end anonymous namespace
4752
4753static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004754 const Expr *OrigFormatExpr,
4755 ArrayRef<const Expr *> Args,
4756 bool HasVAListArg, unsigned format_idx,
4757 unsigned firstDataArg,
4758 Sema::FormatStringType Type,
4759 bool inFunctionCall,
4760 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004761 llvm::SmallBitVector &CheckedVarArgs,
4762 UncoveredArgHandler &UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004763
Richard Smith55ce3522012-06-25 20:30:08 +00004764// Determine if an expression is a string literal or constant string.
4765// If this function returns false on the arguments to a function expecting a
4766// format string, we will usually need to emit a warning.
4767// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00004768static StringLiteralCheckType
4769checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
4770 bool HasVAListArg, unsigned format_idx,
4771 unsigned firstDataArg, Sema::FormatStringType Type,
4772 Sema::VariadicCallType CallType, bool InFunctionCall,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004773 llvm::SmallBitVector &CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00004774 UncoveredArgHandler &UncoveredArg,
4775 llvm::APSInt Offset) {
Ted Kremenek808829352010-09-09 03:51:39 +00004776 tryAgain:
Stephen Hines648c3692016-09-16 01:07:04 +00004777 assert(Offset.isSigned() && "invalid offset");
4778
Douglas Gregorc25f7662009-05-19 22:10:17 +00004779 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00004780 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004781
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004782 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00004783
Richard Smithd7293d72013-08-05 18:49:43 +00004784 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00004785 // Technically -Wformat-nonliteral does not warn about this case.
4786 // The behavior of printf and friends in this case is implementation
4787 // dependent. Ideally if the format string cannot be null then
4788 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00004789 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00004790
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004791 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00004792 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004793 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00004794 // The expression is a literal if both sub-expressions were, and it was
4795 // completely checked only if both sub-expressions were checked.
4796 const AbstractConditionalOperator *C =
4797 cast<AbstractConditionalOperator>(E);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004798
4799 // Determine whether it is necessary to check both sub-expressions, for
4800 // example, because the condition expression is a constant that can be
4801 // evaluated at compile time.
4802 bool CheckLeft = true, CheckRight = true;
4803
4804 bool Cond;
4805 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
4806 if (Cond)
4807 CheckRight = false;
4808 else
4809 CheckLeft = false;
4810 }
4811
Stephen Hines648c3692016-09-16 01:07:04 +00004812 // We need to maintain the offsets for the right and the left hand side
4813 // separately to check if every possible indexed expression is a valid
4814 // string literal. They might have different offsets for different string
4815 // literals in the end.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004816 StringLiteralCheckType Left;
4817 if (!CheckLeft)
4818 Left = SLCT_UncheckedLiteral;
4819 else {
4820 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
4821 HasVAListArg, format_idx, firstDataArg,
4822 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00004823 CheckedVarArgs, UncoveredArg, Offset);
4824 if (Left == SLCT_NotALiteral || !CheckRight) {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004825 return Left;
Stephen Hines648c3692016-09-16 01:07:04 +00004826 }
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004827 }
4828
Richard Smith55ce3522012-06-25 20:30:08 +00004829 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00004830 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004831 HasVAListArg, format_idx, firstDataArg,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004832 Type, CallType, InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00004833 UncoveredArg, Offset);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004834
4835 return (CheckLeft && Left < Right) ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004836 }
4837
4838 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00004839 E = cast<ImplicitCastExpr>(E)->getSubExpr();
4840 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004841 }
4842
John McCallc07a0c72011-02-17 10:25:35 +00004843 case Stmt::OpaqueValueExprClass:
4844 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
4845 E = src;
4846 goto tryAgain;
4847 }
Richard Smith55ce3522012-06-25 20:30:08 +00004848 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00004849
Ted Kremeneka8890832011-02-24 23:03:04 +00004850 case Stmt::PredefinedExprClass:
4851 // While __func__, etc., are technically not string literals, they
4852 // cannot contain format specifiers and thus are not a security
4853 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00004854 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00004855
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004856 case Stmt::DeclRefExprClass: {
4857 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004858
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004859 // As an exception, do not flag errors for variables binding to
4860 // const string literals.
4861 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
4862 bool isConstant = false;
4863 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004864
Richard Smithd7293d72013-08-05 18:49:43 +00004865 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
4866 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00004867 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00004868 isConstant = T.isConstant(S.Context) &&
4869 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00004870 } else if (T->isObjCObjectPointerType()) {
4871 // In ObjC, there is usually no "const ObjectPointer" type,
4872 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00004873 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004874 }
Mike Stump11289f42009-09-09 15:08:12 +00004875
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004876 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00004877 if (const Expr *Init = VD->getAnyInitializer()) {
4878 // Look through initializers like const char c[] = { "foo" }
4879 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4880 if (InitList->isStringLiteralInit())
4881 Init = InitList->getInit(0)->IgnoreParenImpCasts();
4882 }
Richard Smithd7293d72013-08-05 18:49:43 +00004883 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004884 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004885 firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00004886 /*InFunctionCall*/ false, CheckedVarArgs,
4887 UncoveredArg, Offset);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00004888 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004889 }
Mike Stump11289f42009-09-09 15:08:12 +00004890
Anders Carlssonb012ca92009-06-28 19:55:58 +00004891 // For vprintf* functions (i.e., HasVAListArg==true), we add a
4892 // special check to see if the format string is a function parameter
4893 // of the function calling the printf function. If the function
4894 // has an attribute indicating it is a printf-like function, then we
4895 // should suppress warnings concerning non-literals being used in a call
4896 // to a vprintf function. For example:
4897 //
4898 // void
4899 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
4900 // va_list ap;
4901 // va_start(ap, fmt);
4902 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
4903 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00004904 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004905 if (HasVAListArg) {
4906 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
4907 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
4908 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00004909 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004910 // adjust for implicit parameter
4911 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4912 if (MD->isInstance())
4913 ++PVIndex;
4914 // We also check if the formats are compatible.
4915 // We can't pass a 'scanf' string to a 'printf' function.
4916 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00004917 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00004918 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004919 }
4920 }
4921 }
4922 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004923 }
Mike Stump11289f42009-09-09 15:08:12 +00004924
Richard Smith55ce3522012-06-25 20:30:08 +00004925 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004926 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004927
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00004928 case Stmt::CallExprClass:
4929 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00004930 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00004931 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
4932 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
4933 unsigned ArgIndex = FA->getFormatIdx();
4934 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4935 if (MD->isInstance())
4936 --ArgIndex;
4937 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00004938
Richard Smithd7293d72013-08-05 18:49:43 +00004939 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004940 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00004941 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00004942 CheckedVarArgs, UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004943 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4944 unsigned BuiltinID = FD->getBuiltinID();
4945 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
4946 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
4947 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00004948 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004949 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004950 firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004951 InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00004952 UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004953 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00004954 }
4955 }
Mike Stump11289f42009-09-09 15:08:12 +00004956
Richard Smith55ce3522012-06-25 20:30:08 +00004957 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00004958 }
Alex Lorenzd9007142016-10-24 09:42:34 +00004959 case Stmt::ObjCMessageExprClass: {
4960 const auto *ME = cast<ObjCMessageExpr>(E);
4961 if (const auto *ND = ME->getMethodDecl()) {
4962 if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
4963 unsigned ArgIndex = FA->getFormatIdx();
4964 const Expr *Arg = ME->getArg(ArgIndex - 1);
4965 return checkFormatStringExpr(
4966 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
4967 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
4968 }
4969 }
4970
4971 return SLCT_NotALiteral;
4972 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004973 case Stmt::ObjCStringLiteralClass:
4974 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00004975 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004976
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004977 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004978 StrE = ObjCFExpr->getString();
4979 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004980 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004981
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004982 if (StrE) {
Stephen Hines648c3692016-09-16 01:07:04 +00004983 if (Offset.isNegative() || Offset > StrE->getLength()) {
4984 // TODO: It would be better to have an explicit warning for out of
4985 // bounds literals.
4986 return SLCT_NotALiteral;
4987 }
4988 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
4989 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004990 firstDataArg, Type, InFunctionCall, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004991 CheckedVarArgs, UncoveredArg);
Richard Smith55ce3522012-06-25 20:30:08 +00004992 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004993 }
Mike Stump11289f42009-09-09 15:08:12 +00004994
Richard Smith55ce3522012-06-25 20:30:08 +00004995 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004996 }
Stephen Hines648c3692016-09-16 01:07:04 +00004997 case Stmt::BinaryOperatorClass: {
4998 llvm::APSInt LResult;
4999 llvm::APSInt RResult;
5000
5001 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
5002
5003 // A string literal + an int offset is still a string literal.
5004 if (BinOp->isAdditiveOp()) {
5005 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
5006 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
5007
5008 if (LIsInt != RIsInt) {
5009 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
5010
5011 if (LIsInt) {
5012 if (BinOpKind == BO_Add) {
5013 sumOffsets(Offset, LResult, BinOpKind, RIsInt);
5014 E = BinOp->getRHS();
5015 goto tryAgain;
5016 }
5017 } else {
5018 sumOffsets(Offset, RResult, BinOpKind, RIsInt);
5019 E = BinOp->getLHS();
5020 goto tryAgain;
5021 }
5022 }
Stephen Hines648c3692016-09-16 01:07:04 +00005023 }
George Burgess IVd273aab2016-09-22 00:00:26 +00005024
5025 return SLCT_NotALiteral;
Stephen Hines648c3692016-09-16 01:07:04 +00005026 }
5027 case Stmt::UnaryOperatorClass: {
5028 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
5029 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
5030 if (UnaOp->getOpcode() == clang::UO_AddrOf && ASE) {
5031 llvm::APSInt IndexResult;
5032 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
5033 sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true);
5034 E = ASE->getBase();
5035 goto tryAgain;
5036 }
5037 }
5038
5039 return SLCT_NotALiteral;
5040 }
Mike Stump11289f42009-09-09 15:08:12 +00005041
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005042 default:
Richard Smith55ce3522012-06-25 20:30:08 +00005043 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005044 }
5045}
5046
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005047Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00005048 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Mehdi Amini06d367c2016-10-24 20:39:34 +00005049 .Case("scanf", FST_Scanf)
5050 .Cases("printf", "printf0", FST_Printf)
5051 .Cases("NSString", "CFString", FST_NSString)
5052 .Case("strftime", FST_Strftime)
5053 .Case("strfmon", FST_Strfmon)
5054 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
5055 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
5056 .Case("os_trace", FST_OSLog)
5057 .Case("os_log", FST_OSLog)
5058 .Default(FST_Unknown);
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005059}
5060
Jordan Rose3e0ec582012-07-19 18:10:23 +00005061/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00005062/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00005063/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005064bool Sema::CheckFormatArguments(const FormatAttr *Format,
5065 ArrayRef<const Expr *> Args,
5066 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005067 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00005068 SourceLocation Loc, SourceRange Range,
5069 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00005070 FormatStringInfo FSI;
5071 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005072 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00005073 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00005074 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00005075 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005076}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00005077
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005078bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005079 bool HasVAListArg, unsigned format_idx,
5080 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005081 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00005082 SourceLocation Loc, SourceRange Range,
5083 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00005084 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005085 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005086 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00005087 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00005088 }
Mike Stump11289f42009-09-09 15:08:12 +00005089
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005090 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00005091
Chris Lattnerb87b1b32007-08-10 20:18:51 +00005092 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00005093 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00005094 // Dynamically generated format strings are difficult to
5095 // automatically vet at compile time. Requiring that format strings
5096 // are string literals: (1) permits the checking of format strings by
5097 // the compiler and thereby (2) can practically remove the source of
5098 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00005099
Mike Stump11289f42009-09-09 15:08:12 +00005100 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00005101 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00005102 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00005103 // the same format string checking logic for both ObjC and C strings.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005104 UncoveredArgHandler UncoveredArg;
Richard Smith55ce3522012-06-25 20:30:08 +00005105 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00005106 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
5107 format_idx, firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00005108 /*IsFunctionCall*/ true, CheckedVarArgs,
5109 UncoveredArg,
5110 /*no string offset*/ llvm::APSInt(64, false) = 0);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005111
5112 // Generate a diagnostic where an uncovered argument is detected.
5113 if (UncoveredArg.hasUncoveredArg()) {
5114 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
5115 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
5116 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
5117 }
5118
Richard Smith55ce3522012-06-25 20:30:08 +00005119 if (CT != SLCT_NotALiteral)
5120 // Literal format string found, check done!
5121 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00005122
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00005123 // Strftime is particular as it always uses a single 'time' argument,
5124 // so it is safe to pass a non-literal string.
5125 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00005126 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00005127
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00005128 // Do not emit diag when the string param is a macro expansion and the
5129 // format is either NSString or CFString. This is a hack to prevent
5130 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
5131 // which are usually used in place of NS and CF string literals.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005132 SourceLocation FormatLoc = Args[format_idx]->getLocStart();
5133 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
Richard Smith55ce3522012-06-25 20:30:08 +00005134 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00005135
Chris Lattnercc5d1c22009-04-29 04:59:47 +00005136 // If there are no arguments specified, warn with -Wformat-security, otherwise
5137 // warn only with -Wformat-nonliteral.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005138 if (Args.size() == firstDataArg) {
Bob Wilson57819fc2016-03-15 20:56:38 +00005139 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
5140 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005141 switch (Type) {
5142 default:
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005143 break;
5144 case FST_Kprintf:
5145 case FST_FreeBSDKPrintf:
5146 case FST_Printf:
Bob Wilson57819fc2016-03-15 20:56:38 +00005147 Diag(FormatLoc, diag::note_format_security_fixit)
5148 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005149 break;
5150 case FST_NSString:
Bob Wilson57819fc2016-03-15 20:56:38 +00005151 Diag(FormatLoc, diag::note_format_security_fixit)
5152 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005153 break;
5154 }
5155 } else {
5156 Diag(FormatLoc, diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00005157 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005158 }
Richard Smith55ce3522012-06-25 20:30:08 +00005159 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005160}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00005161
Ted Kremenekab278de2010-01-28 23:39:18 +00005162namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00005163class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
5164protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00005165 Sema &S;
Stephen Hines648c3692016-09-16 01:07:04 +00005166 const FormatStringLiteral *FExpr;
Ted Kremenekab278de2010-01-28 23:39:18 +00005167 const Expr *OrigFormatExpr;
Mehdi Amini06d367c2016-10-24 20:39:34 +00005168 const Sema::FormatStringType FSType;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00005169 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00005170 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00005171 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00005172 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005173 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00005174 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00005175 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00005176 bool usesPositionalArgs;
5177 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00005178 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00005179 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00005180 llvm::SmallBitVector &CheckedVarArgs;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005181 UncoveredArgHandler &UncoveredArg;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005182
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005183public:
Stephen Hines648c3692016-09-16 01:07:04 +00005184 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00005185 const Expr *origFormatExpr,
5186 const Sema::FormatStringType type, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005187 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Mehdi Amini06d367c2016-10-24 20:39:34 +00005188 ArrayRef<const Expr *> Args, unsigned formatIdx,
5189 bool inFunctionCall, Sema::VariadicCallType callType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005190 llvm::SmallBitVector &CheckedVarArgs,
5191 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00005192 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
5193 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
5194 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
5195 usesPositionalArgs(false), atFirstArg(true),
5196 inFunctionCall(inFunctionCall), CallType(callType),
5197 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
Richard Smithd7293d72013-08-05 18:49:43 +00005198 CoveredArgs.resize(numDataArgs);
5199 CoveredArgs.reset();
5200 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005201
Ted Kremenek019d2242010-01-29 01:50:07 +00005202 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005203
Ted Kremenek02087932010-07-16 02:11:22 +00005204 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005205 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005206
Jordan Rose92303592012-09-08 04:00:03 +00005207 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005208 const analyze_format_string::FormatSpecifier &FS,
5209 const analyze_format_string::ConversionSpecifier &CS,
5210 const char *startSpecifier, unsigned specifierLen,
5211 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00005212
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005213 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005214 const analyze_format_string::FormatSpecifier &FS,
5215 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005216
5217 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005218 const analyze_format_string::ConversionSpecifier &CS,
5219 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005220
Craig Toppere14c0f82014-03-12 04:55:44 +00005221 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00005222
Craig Toppere14c0f82014-03-12 04:55:44 +00005223 void HandleInvalidPosition(const char *startSpecifier,
5224 unsigned specifierLen,
5225 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00005226
Craig Toppere14c0f82014-03-12 04:55:44 +00005227 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00005228
Craig Toppere14c0f82014-03-12 04:55:44 +00005229 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005230
Richard Trieu03cf7b72011-10-28 00:41:25 +00005231 template <typename Range>
Benjamin Kramer7320b992016-06-15 14:20:56 +00005232 static void
5233 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
5234 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
5235 bool IsStringLocation, Range StringRange,
5236 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005237
Ted Kremenek02087932010-07-16 02:11:22 +00005238protected:
Ted Kremenekce815422010-07-19 21:25:57 +00005239 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
5240 const char *startSpec,
5241 unsigned specifierLen,
5242 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005243
5244 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
5245 const char *startSpec,
5246 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00005247
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005248 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00005249 CharSourceRange getSpecifierRange(const char *startSpecifier,
5250 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00005251 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005252
Ted Kremenek5739de72010-01-29 01:06:55 +00005253 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005254
5255 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
5256 const analyze_format_string::ConversionSpecifier &CS,
5257 const char *startSpecifier, unsigned specifierLen,
5258 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005259
5260 template <typename Range>
5261 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5262 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00005263 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00005264};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005265} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00005266
Ted Kremenek02087932010-07-16 02:11:22 +00005267SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00005268 return OrigFormatExpr->getSourceRange();
5269}
5270
Ted Kremenek02087932010-07-16 02:11:22 +00005271CharSourceRange CheckFormatHandler::
5272getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00005273 SourceLocation Start = getLocationOfByte(startSpecifier);
5274 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
5275
5276 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00005277 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00005278
5279 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005280}
5281
Ted Kremenek02087932010-07-16 02:11:22 +00005282SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Stephen Hines648c3692016-09-16 01:07:04 +00005283 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
5284 S.getLangOpts(), S.Context.getTargetInfo());
Ted Kremenekab278de2010-01-28 23:39:18 +00005285}
5286
Ted Kremenek02087932010-07-16 02:11:22 +00005287void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
5288 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00005289 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
5290 getLocationOfByte(startSpecifier),
5291 /*IsStringLocation*/true,
5292 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00005293}
5294
Jordan Rose92303592012-09-08 04:00:03 +00005295void CheckFormatHandler::HandleInvalidLengthModifier(
5296 const analyze_format_string::FormatSpecifier &FS,
5297 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00005298 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00005299 using namespace analyze_format_string;
5300
5301 const LengthModifier &LM = FS.getLengthModifier();
5302 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5303
5304 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00005305 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00005306 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005307 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00005308 getLocationOfByte(LM.getStart()),
5309 /*IsStringLocation*/true,
5310 getSpecifierRange(startSpecifier, specifierLen));
5311
5312 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5313 << FixedLM->toString()
5314 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5315
5316 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005317 FixItHint Hint;
5318 if (DiagID == diag::warn_format_nonsensical_length)
5319 Hint = FixItHint::CreateRemoval(LMRange);
5320
5321 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00005322 getLocationOfByte(LM.getStart()),
5323 /*IsStringLocation*/true,
5324 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00005325 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00005326 }
5327}
5328
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005329void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00005330 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005331 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005332 using namespace analyze_format_string;
5333
5334 const LengthModifier &LM = FS.getLengthModifier();
5335 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5336
5337 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00005338 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00005339 if (FixedLM) {
5340 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5341 << LM.toString() << 0,
5342 getLocationOfByte(LM.getStart()),
5343 /*IsStringLocation*/true,
5344 getSpecifierRange(startSpecifier, specifierLen));
5345
5346 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5347 << FixedLM->toString()
5348 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5349
5350 } else {
5351 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5352 << LM.toString() << 0,
5353 getLocationOfByte(LM.getStart()),
5354 /*IsStringLocation*/true,
5355 getSpecifierRange(startSpecifier, specifierLen));
5356 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005357}
5358
5359void CheckFormatHandler::HandleNonStandardConversionSpecifier(
5360 const analyze_format_string::ConversionSpecifier &CS,
5361 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00005362 using namespace analyze_format_string;
5363
5364 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00005365 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00005366 if (FixedCS) {
5367 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5368 << CS.toString() << /*conversion specifier*/1,
5369 getLocationOfByte(CS.getStart()),
5370 /*IsStringLocation*/true,
5371 getSpecifierRange(startSpecifier, specifierLen));
5372
5373 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
5374 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
5375 << FixedCS->toString()
5376 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
5377 } else {
5378 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5379 << CS.toString() << /*conversion specifier*/1,
5380 getLocationOfByte(CS.getStart()),
5381 /*IsStringLocation*/true,
5382 getSpecifierRange(startSpecifier, specifierLen));
5383 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005384}
5385
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00005386void CheckFormatHandler::HandlePosition(const char *startPos,
5387 unsigned posLen) {
5388 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
5389 getLocationOfByte(startPos),
5390 /*IsStringLocation*/true,
5391 getSpecifierRange(startPos, posLen));
5392}
5393
Ted Kremenekd1668192010-02-27 01:41:03 +00005394void
Ted Kremenek02087932010-07-16 02:11:22 +00005395CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
5396 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005397 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
5398 << (unsigned) p,
5399 getLocationOfByte(startPos), /*IsStringLocation*/true,
5400 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00005401}
5402
Ted Kremenek02087932010-07-16 02:11:22 +00005403void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00005404 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005405 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
5406 getLocationOfByte(startPos),
5407 /*IsStringLocation*/true,
5408 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00005409}
5410
Ted Kremenek02087932010-07-16 02:11:22 +00005411void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005412 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00005413 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00005414 EmitFormatDiagnostic(
5415 S.PDiag(diag::warn_printf_format_string_contains_null_char),
5416 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
5417 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00005418 }
Ted Kremenek02087932010-07-16 02:11:22 +00005419}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005420
Jordan Rose58bbe422012-07-19 18:10:08 +00005421// Note that this may return NULL if there was an error parsing or building
5422// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00005423const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005424 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00005425}
5426
5427void CheckFormatHandler::DoneProcessing() {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005428 // Does the number of data arguments exceed the number of
5429 // format conversions in the format string?
Ted Kremenek02087932010-07-16 02:11:22 +00005430 if (!HasVAListArg) {
5431 // Find any arguments that weren't covered.
5432 CoveredArgs.flip();
5433 signed notCoveredArg = CoveredArgs.find_first();
5434 if (notCoveredArg >= 0) {
5435 assert((unsigned)notCoveredArg < NumDataArgs);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005436 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
5437 } else {
5438 UncoveredArg.setAllCovered();
Ted Kremenek02087932010-07-16 02:11:22 +00005439 }
5440 }
5441}
5442
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005443void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
5444 const Expr *ArgExpr) {
5445 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
5446 "Invalid state");
5447
5448 if (!ArgExpr)
5449 return;
5450
5451 SourceLocation Loc = ArgExpr->getLocStart();
5452
5453 if (S.getSourceManager().isInSystemMacro(Loc))
5454 return;
5455
5456 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
5457 for (auto E : DiagnosticExprs)
5458 PDiag << E->getSourceRange();
5459
5460 CheckFormatHandler::EmitFormatDiagnostic(
5461 S, IsFunctionCall, DiagnosticExprs[0],
5462 PDiag, Loc, /*IsStringLocation*/false,
5463 DiagnosticExprs[0]->getSourceRange());
5464}
5465
Ted Kremenekce815422010-07-19 21:25:57 +00005466bool
5467CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
5468 SourceLocation Loc,
5469 const char *startSpec,
5470 unsigned specifierLen,
5471 const char *csStart,
5472 unsigned csLen) {
Ted Kremenekce815422010-07-19 21:25:57 +00005473 bool keepGoing = true;
5474 if (argIndex < NumDataArgs) {
5475 // Consider the argument coverered, even though the specifier doesn't
5476 // make sense.
5477 CoveredArgs.set(argIndex);
5478 }
5479 else {
5480 // If argIndex exceeds the number of data arguments we
5481 // don't issue a warning because that is just a cascade of warnings (and
5482 // they may have intended '%%' anyway). We don't want to continue processing
5483 // the format string after this point, however, as we will like just get
5484 // gibberish when trying to match arguments.
5485 keepGoing = false;
5486 }
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005487
5488 StringRef Specifier(csStart, csLen);
5489
5490 // If the specifier in non-printable, it could be the first byte of a UTF-8
5491 // sequence. In that case, print the UTF-8 code point. If not, print the byte
5492 // hex value.
5493 std::string CodePointStr;
5494 if (!llvm::sys::locale::isPrint(*csStart)) {
Justin Lebar90910552016-09-30 00:38:45 +00005495 llvm::UTF32 CodePoint;
5496 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
5497 const llvm::UTF8 *E =
5498 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
5499 llvm::ConversionResult Result =
5500 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005501
Justin Lebar90910552016-09-30 00:38:45 +00005502 if (Result != llvm::conversionOK) {
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005503 unsigned char FirstChar = *csStart;
Justin Lebar90910552016-09-30 00:38:45 +00005504 CodePoint = (llvm::UTF32)FirstChar;
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005505 }
5506
5507 llvm::raw_string_ostream OS(CodePointStr);
5508 if (CodePoint < 256)
5509 OS << "\\x" << llvm::format("%02x", CodePoint);
5510 else if (CodePoint <= 0xFFFF)
5511 OS << "\\u" << llvm::format("%04x", CodePoint);
5512 else
5513 OS << "\\U" << llvm::format("%08x", CodePoint);
5514 OS.flush();
5515 Specifier = CodePointStr;
5516 }
5517
5518 EmitFormatDiagnostic(
5519 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
5520 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
5521
Ted Kremenekce815422010-07-19 21:25:57 +00005522 return keepGoing;
5523}
5524
Richard Trieu03cf7b72011-10-28 00:41:25 +00005525void
5526CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
5527 const char *startSpec,
5528 unsigned specifierLen) {
5529 EmitFormatDiagnostic(
5530 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
5531 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
5532}
5533
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005534bool
5535CheckFormatHandler::CheckNumArgs(
5536 const analyze_format_string::FormatSpecifier &FS,
5537 const analyze_format_string::ConversionSpecifier &CS,
5538 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
5539
5540 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005541 PartialDiagnostic PDiag = FS.usesPositionalArg()
5542 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
5543 << (argIndex+1) << NumDataArgs)
5544 : S.PDiag(diag::warn_printf_insufficient_data_args);
5545 EmitFormatDiagnostic(
5546 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
5547 getSpecifierRange(startSpecifier, specifierLen));
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005548
5549 // Since more arguments than conversion tokens are given, by extension
5550 // all arguments are covered, so mark this as so.
5551 UncoveredArg.setAllCovered();
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005552 return false;
5553 }
5554 return true;
5555}
5556
Richard Trieu03cf7b72011-10-28 00:41:25 +00005557template<typename Range>
5558void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
5559 SourceLocation Loc,
5560 bool IsStringLocation,
5561 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00005562 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005563 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00005564 Loc, IsStringLocation, StringRange, FixIt);
5565}
5566
5567/// \brief If the format string is not within the funcion call, emit a note
5568/// so that the function call and string are in diagnostic messages.
5569///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00005570/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00005571/// call and only one diagnostic message will be produced. Otherwise, an
5572/// extra note will be emitted pointing to location of the format string.
5573///
5574/// \param ArgumentExpr the expression that is passed as the format string
5575/// argument in the function call. Used for getting locations when two
5576/// diagnostics are emitted.
5577///
5578/// \param PDiag the callee should already have provided any strings for the
5579/// diagnostic message. This function only adds locations and fixits
5580/// to diagnostics.
5581///
5582/// \param Loc primary location for diagnostic. If two diagnostics are
5583/// required, one will be at Loc and a new SourceLocation will be created for
5584/// the other one.
5585///
5586/// \param IsStringLocation if true, Loc points to the format string should be
5587/// used for the note. Otherwise, Loc points to the argument list and will
5588/// be used with PDiag.
5589///
5590/// \param StringRange some or all of the string to highlight. This is
5591/// templated so it can accept either a CharSourceRange or a SourceRange.
5592///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00005593/// \param FixIt optional fix it hint for the format string.
Benjamin Kramer7320b992016-06-15 14:20:56 +00005594template <typename Range>
5595void CheckFormatHandler::EmitFormatDiagnostic(
5596 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
5597 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
5598 Range StringRange, ArrayRef<FixItHint> FixIt) {
Jordan Roseaee34382012-09-05 22:56:26 +00005599 if (InFunctionCall) {
5600 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
5601 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00005602 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00005603 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005604 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
5605 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00005606
5607 const Sema::SemaDiagnosticBuilder &Note =
5608 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
5609 diag::note_format_string_defined);
5610
5611 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00005612 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00005613 }
5614}
5615
Ted Kremenek02087932010-07-16 02:11:22 +00005616//===--- CHECK: Printf format string checking ------------------------------===//
5617
5618namespace {
5619class CheckPrintfHandler : public CheckFormatHandler {
5620public:
Stephen Hines648c3692016-09-16 01:07:04 +00005621 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00005622 const Expr *origFormatExpr,
5623 const Sema::FormatStringType type, unsigned firstDataArg,
5624 unsigned numDataArgs, bool isObjC, const char *beg,
5625 bool hasVAListArg, ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005626 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00005627 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005628 llvm::SmallBitVector &CheckedVarArgs,
5629 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00005630 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
5631 numDataArgs, beg, hasVAListArg, Args, formatIdx,
5632 inFunctionCall, CallType, CheckedVarArgs,
5633 UncoveredArg) {}
5634
5635 bool isObjCContext() const { return FSType == Sema::FST_NSString; }
5636
5637 /// Returns true if '%@' specifiers are allowed in the format string.
5638 bool allowsObjCArg() const {
5639 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
5640 FSType == Sema::FST_OSTrace;
5641 }
Jordan Rose3e0ec582012-07-19 18:10:23 +00005642
Ted Kremenek02087932010-07-16 02:11:22 +00005643 bool HandleInvalidPrintfConversionSpecifier(
5644 const analyze_printf::PrintfSpecifier &FS,
5645 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005646 unsigned specifierLen) override;
5647
Ted Kremenek02087932010-07-16 02:11:22 +00005648 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
5649 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005650 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00005651 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5652 const char *StartSpecifier,
5653 unsigned SpecifierLen,
5654 const Expr *E);
5655
Ted Kremenek02087932010-07-16 02:11:22 +00005656 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
5657 const char *startSpecifier, unsigned specifierLen);
5658 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
5659 const analyze_printf::OptionalAmount &Amt,
5660 unsigned type,
5661 const char *startSpecifier, unsigned specifierLen);
5662 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
5663 const analyze_printf::OptionalFlag &flag,
5664 const char *startSpecifier, unsigned specifierLen);
5665 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
5666 const analyze_printf::OptionalFlag &ignoredFlag,
5667 const analyze_printf::OptionalFlag &flag,
5668 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005669 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00005670 const Expr *E);
Ted Kremenek2b417712015-07-02 05:39:16 +00005671
5672 void HandleEmptyObjCModifierFlag(const char *startFlag,
5673 unsigned flagLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00005674
Ted Kremenek2b417712015-07-02 05:39:16 +00005675 void HandleInvalidObjCModifierFlag(const char *startFlag,
5676 unsigned flagLen) override;
5677
5678 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
5679 const char *flagsEnd,
5680 const char *conversionPosition)
5681 override;
5682};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005683} // end anonymous namespace
Ted Kremenek02087932010-07-16 02:11:22 +00005684
5685bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
5686 const analyze_printf::PrintfSpecifier &FS,
5687 const char *startSpecifier,
5688 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005689 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00005690 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00005691
Ted Kremenekce815422010-07-19 21:25:57 +00005692 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
5693 getLocationOfByte(CS.getStart()),
5694 startSpecifier, specifierLen,
5695 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00005696}
5697
Ted Kremenek02087932010-07-16 02:11:22 +00005698bool CheckPrintfHandler::HandleAmount(
5699 const analyze_format_string::OptionalAmount &Amt,
5700 unsigned k, const char *startSpecifier,
5701 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00005702 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00005703 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00005704 unsigned argIndex = Amt.getArgIndex();
5705 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005706 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
5707 << k,
5708 getLocationOfByte(Amt.getStart()),
5709 /*IsStringLocation*/true,
5710 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00005711 // Don't do any more checking. We will just emit
5712 // spurious errors.
5713 return false;
5714 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005715
Ted Kremenek5739de72010-01-29 01:06:55 +00005716 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00005717 // Although not in conformance with C99, we also allow the argument to be
5718 // an 'unsigned int' as that is a reasonably safe case. GCC also
5719 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00005720 CoveredArgs.set(argIndex);
5721 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00005722 if (!Arg)
5723 return false;
5724
Ted Kremenek5739de72010-01-29 01:06:55 +00005725 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005726
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005727 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
5728 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005729
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005730 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005731 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005732 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00005733 << T << Arg->getSourceRange(),
5734 getLocationOfByte(Amt.getStart()),
5735 /*IsStringLocation*/true,
5736 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00005737 // Don't do any more checking. We will just emit
5738 // spurious errors.
5739 return false;
5740 }
5741 }
5742 }
5743 return true;
5744}
Ted Kremenek5739de72010-01-29 01:06:55 +00005745
Tom Careb49ec692010-06-17 19:00:27 +00005746void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00005747 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005748 const analyze_printf::OptionalAmount &Amt,
5749 unsigned type,
5750 const char *startSpecifier,
5751 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005752 const analyze_printf::PrintfConversionSpecifier &CS =
5753 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00005754
Richard Trieu03cf7b72011-10-28 00:41:25 +00005755 FixItHint fixit =
5756 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
5757 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
5758 Amt.getConstantLength()))
5759 : FixItHint();
5760
5761 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
5762 << type << CS.toString(),
5763 getLocationOfByte(Amt.getStart()),
5764 /*IsStringLocation*/true,
5765 getSpecifierRange(startSpecifier, specifierLen),
5766 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00005767}
5768
Ted Kremenek02087932010-07-16 02:11:22 +00005769void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005770 const analyze_printf::OptionalFlag &flag,
5771 const char *startSpecifier,
5772 unsigned specifierLen) {
5773 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005774 const analyze_printf::PrintfConversionSpecifier &CS =
5775 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00005776 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
5777 << flag.toString() << CS.toString(),
5778 getLocationOfByte(flag.getPosition()),
5779 /*IsStringLocation*/true,
5780 getSpecifierRange(startSpecifier, specifierLen),
5781 FixItHint::CreateRemoval(
5782 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00005783}
5784
5785void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00005786 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005787 const analyze_printf::OptionalFlag &ignoredFlag,
5788 const analyze_printf::OptionalFlag &flag,
5789 const char *startSpecifier,
5790 unsigned specifierLen) {
5791 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00005792 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
5793 << ignoredFlag.toString() << flag.toString(),
5794 getLocationOfByte(ignoredFlag.getPosition()),
5795 /*IsStringLocation*/true,
5796 getSpecifierRange(startSpecifier, specifierLen),
5797 FixItHint::CreateRemoval(
5798 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00005799}
5800
Ted Kremenek2b417712015-07-02 05:39:16 +00005801// void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5802// bool IsStringLocation, Range StringRange,
5803// ArrayRef<FixItHint> Fixit = None);
5804
5805void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
5806 unsigned flagLen) {
5807 // Warn about an empty flag.
5808 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
5809 getLocationOfByte(startFlag),
5810 /*IsStringLocation*/true,
5811 getSpecifierRange(startFlag, flagLen));
5812}
5813
5814void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
5815 unsigned flagLen) {
5816 // Warn about an invalid flag.
5817 auto Range = getSpecifierRange(startFlag, flagLen);
5818 StringRef flag(startFlag, flagLen);
5819 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
5820 getLocationOfByte(startFlag),
5821 /*IsStringLocation*/true,
5822 Range, FixItHint::CreateRemoval(Range));
5823}
5824
5825void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
5826 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
5827 // Warn about using '[...]' without a '@' conversion.
5828 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
5829 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
5830 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
5831 getLocationOfByte(conversionPosition),
5832 /*IsStringLocation*/true,
5833 Range, FixItHint::CreateRemoval(Range));
5834}
5835
Richard Smith55ce3522012-06-25 20:30:08 +00005836// Determines if the specified is a C++ class or struct containing
5837// a member with the specified name and kind (e.g. a CXXMethodDecl named
5838// "c_str()").
5839template<typename MemberKind>
5840static llvm::SmallPtrSet<MemberKind*, 1>
5841CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
5842 const RecordType *RT = Ty->getAs<RecordType>();
5843 llvm::SmallPtrSet<MemberKind*, 1> Results;
5844
5845 if (!RT)
5846 return Results;
5847 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00005848 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00005849 return Results;
5850
Alp Tokerb6cc5922014-05-03 03:45:55 +00005851 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00005852 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00005853 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00005854
5855 // We just need to include all members of the right kind turned up by the
5856 // filter, at this point.
5857 if (S.LookupQualifiedName(R, RT->getDecl()))
5858 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
5859 NamedDecl *decl = (*I)->getUnderlyingDecl();
5860 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
5861 Results.insert(FK);
5862 }
5863 return Results;
5864}
5865
Richard Smith2868a732014-02-28 01:36:39 +00005866/// Check if we could call '.c_str()' on an object.
5867///
5868/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
5869/// allow the call, or if it would be ambiguous).
5870bool Sema::hasCStrMethod(const Expr *E) {
5871 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5872 MethodSet Results =
5873 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
5874 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5875 MI != ME; ++MI)
5876 if ((*MI)->getMinRequiredArguments() == 0)
5877 return true;
5878 return false;
5879}
5880
Richard Smith55ce3522012-06-25 20:30:08 +00005881// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005882// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00005883// Returns true when a c_str() conversion method is found.
5884bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00005885 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00005886 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5887
5888 MethodSet Results =
5889 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
5890
5891 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5892 MI != ME; ++MI) {
5893 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00005894 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00005895 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00005896 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00005897 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00005898 S.Diag(E->getLocStart(), diag::note_printf_c_str)
5899 << "c_str()"
5900 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
5901 return true;
5902 }
5903 }
5904
5905 return false;
5906}
5907
Ted Kremenekab278de2010-01-28 23:39:18 +00005908bool
Ted Kremenek02087932010-07-16 02:11:22 +00005909CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00005910 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00005911 const char *startSpecifier,
5912 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005913 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00005914 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005915 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00005916
Ted Kremenek6cd69422010-07-19 22:01:06 +00005917 if (FS.consumesDataArgument()) {
5918 if (atFirstArg) {
5919 atFirstArg = false;
5920 usesPositionalArgs = FS.usesPositionalArg();
5921 }
5922 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005923 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
5924 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00005925 return false;
5926 }
Ted Kremenek5739de72010-01-29 01:06:55 +00005927 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005928
Ted Kremenekd1668192010-02-27 01:41:03 +00005929 // First check if the field width, precision, and conversion specifier
5930 // have matching data arguments.
5931 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
5932 startSpecifier, specifierLen)) {
5933 return false;
5934 }
5935
5936 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
5937 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00005938 return false;
5939 }
5940
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005941 if (!CS.consumesDataArgument()) {
5942 // FIXME: Technically specifying a precision or field width here
5943 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00005944 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005945 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005946
Ted Kremenek4a49d982010-02-26 19:18:41 +00005947 // Consume the argument.
5948 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00005949 if (argIndex < NumDataArgs) {
5950 // The check to see if the argIndex is valid will come later.
5951 // We set the bit here because we may exit early from this
5952 // function if we encounter some other error.
5953 CoveredArgs.set(argIndex);
5954 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00005955
Dimitry Andric6b5ed342015-02-19 22:32:33 +00005956 // FreeBSD kernel extensions.
5957 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
5958 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
5959 // We need at least two arguments.
5960 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
5961 return false;
5962
5963 // Claim the second argument.
5964 CoveredArgs.set(argIndex + 1);
5965
5966 // Type check the first argument (int for %b, pointer for %D)
5967 const Expr *Ex = getDataArg(argIndex);
5968 const analyze_printf::ArgType &AT =
5969 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
5970 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
5971 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
5972 EmitFormatDiagnostic(
5973 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5974 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
5975 << false << Ex->getSourceRange(),
5976 Ex->getLocStart(), /*IsStringLocation*/false,
5977 getSpecifierRange(startSpecifier, specifierLen));
5978
5979 // Type check the second argument (char * for both %b and %D)
5980 Ex = getDataArg(argIndex + 1);
5981 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
5982 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
5983 EmitFormatDiagnostic(
5984 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5985 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
5986 << false << Ex->getSourceRange(),
5987 Ex->getLocStart(), /*IsStringLocation*/false,
5988 getSpecifierRange(startSpecifier, specifierLen));
5989
5990 return true;
5991 }
5992
Ted Kremenek4a49d982010-02-26 19:18:41 +00005993 // Check for using an Objective-C specific conversion specifier
5994 // in a non-ObjC literal.
Mehdi Amini06d367c2016-10-24 20:39:34 +00005995 if (!allowsObjCArg() && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00005996 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5997 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00005998 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005999
Mehdi Amini06d367c2016-10-24 20:39:34 +00006000 // %P can only be used with os_log.
6001 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
6002 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6003 specifierLen);
6004 }
6005
6006 // %n is not allowed with os_log.
6007 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
6008 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
6009 getLocationOfByte(CS.getStart()),
6010 /*IsStringLocation*/ false,
6011 getSpecifierRange(startSpecifier, specifierLen));
6012
6013 return true;
6014 }
6015
6016 // Only scalars are allowed for os_trace.
6017 if (FSType == Sema::FST_OSTrace &&
6018 (CS.getKind() == ConversionSpecifier::PArg ||
6019 CS.getKind() == ConversionSpecifier::sArg ||
6020 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
6021 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6022 specifierLen);
6023 }
6024
6025 // Check for use of public/private annotation outside of os_log().
6026 if (FSType != Sema::FST_OSLog) {
6027 if (FS.isPublic().isSet()) {
6028 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
6029 << "public",
6030 getLocationOfByte(FS.isPublic().getPosition()),
6031 /*IsStringLocation*/ false,
6032 getSpecifierRange(startSpecifier, specifierLen));
6033 }
6034 if (FS.isPrivate().isSet()) {
6035 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
6036 << "private",
6037 getLocationOfByte(FS.isPrivate().getPosition()),
6038 /*IsStringLocation*/ false,
6039 getSpecifierRange(startSpecifier, specifierLen));
6040 }
6041 }
6042
Tom Careb49ec692010-06-17 19:00:27 +00006043 // Check for invalid use of field width
6044 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00006045 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00006046 startSpecifier, specifierLen);
6047 }
6048
6049 // Check for invalid use of precision
6050 if (!FS.hasValidPrecision()) {
6051 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
6052 startSpecifier, specifierLen);
6053 }
6054
Mehdi Amini06d367c2016-10-24 20:39:34 +00006055 // Precision is mandatory for %P specifier.
6056 if (CS.getKind() == ConversionSpecifier::PArg &&
6057 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
6058 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
6059 getLocationOfByte(startSpecifier),
6060 /*IsStringLocation*/ false,
6061 getSpecifierRange(startSpecifier, specifierLen));
6062 }
6063
Tom Careb49ec692010-06-17 19:00:27 +00006064 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00006065 if (!FS.hasValidThousandsGroupingPrefix())
6066 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00006067 if (!FS.hasValidLeadingZeros())
6068 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
6069 if (!FS.hasValidPlusPrefix())
6070 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00006071 if (!FS.hasValidSpacePrefix())
6072 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00006073 if (!FS.hasValidAlternativeForm())
6074 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
6075 if (!FS.hasValidLeftJustified())
6076 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
6077
6078 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00006079 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
6080 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
6081 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00006082 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
6083 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
6084 startSpecifier, specifierLen);
6085
6086 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00006087 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00006088 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6089 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00006090 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006091 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00006092 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006093 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6094 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00006095
Jordan Rose92303592012-09-08 04:00:03 +00006096 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6097 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6098
Ted Kremenek9fcd8302010-01-29 01:43:31 +00006099 // The remaining checks depend on the data arguments.
6100 if (HasVAListArg)
6101 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006102
Ted Kremenek6adb7e32010-07-26 19:45:42 +00006103 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00006104 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006105
Jordan Rose58bbe422012-07-19 18:10:08 +00006106 const Expr *Arg = getDataArg(argIndex);
6107 if (!Arg)
6108 return true;
6109
6110 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00006111}
6112
Jordan Roseaee34382012-09-05 22:56:26 +00006113static bool requiresParensToAddCast(const Expr *E) {
6114 // FIXME: We should have a general way to reason about operator
6115 // precedence and whether parens are actually needed here.
6116 // Take care of a few common cases where they aren't.
6117 const Expr *Inside = E->IgnoreImpCasts();
6118 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
6119 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
6120
6121 switch (Inside->getStmtClass()) {
6122 case Stmt::ArraySubscriptExprClass:
6123 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006124 case Stmt::CharacterLiteralClass:
6125 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006126 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006127 case Stmt::FloatingLiteralClass:
6128 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006129 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006130 case Stmt::ObjCArrayLiteralClass:
6131 case Stmt::ObjCBoolLiteralExprClass:
6132 case Stmt::ObjCBoxedExprClass:
6133 case Stmt::ObjCDictionaryLiteralClass:
6134 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006135 case Stmt::ObjCIvarRefExprClass:
6136 case Stmt::ObjCMessageExprClass:
6137 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006138 case Stmt::ObjCStringLiteralClass:
6139 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006140 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006141 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006142 case Stmt::UnaryOperatorClass:
6143 return false;
6144 default:
6145 return true;
6146 }
6147}
6148
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006149static std::pair<QualType, StringRef>
6150shouldNotPrintDirectly(const ASTContext &Context,
6151 QualType IntendedTy,
6152 const Expr *E) {
6153 // Use a 'while' to peel off layers of typedefs.
6154 QualType TyTy = IntendedTy;
6155 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
6156 StringRef Name = UserTy->getDecl()->getName();
6157 QualType CastTy = llvm::StringSwitch<QualType>(Name)
Alexander Shaposhnikov62351372017-06-26 23:02:27 +00006158 .Case("CFIndex", Context.LongTy)
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006159 .Case("NSInteger", Context.LongTy)
6160 .Case("NSUInteger", Context.UnsignedLongTy)
6161 .Case("SInt32", Context.IntTy)
6162 .Case("UInt32", Context.UnsignedIntTy)
6163 .Default(QualType());
6164
6165 if (!CastTy.isNull())
6166 return std::make_pair(CastTy, Name);
6167
6168 TyTy = UserTy->desugar();
6169 }
6170
6171 // Strip parens if necessary.
6172 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
6173 return shouldNotPrintDirectly(Context,
6174 PE->getSubExpr()->getType(),
6175 PE->getSubExpr());
6176
6177 // If this is a conditional expression, then its result type is constructed
6178 // via usual arithmetic conversions and thus there might be no necessary
6179 // typedef sugar there. Recurse to operands to check for NSInteger &
6180 // Co. usage condition.
6181 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
6182 QualType TrueTy, FalseTy;
6183 StringRef TrueName, FalseName;
6184
6185 std::tie(TrueTy, TrueName) =
6186 shouldNotPrintDirectly(Context,
6187 CO->getTrueExpr()->getType(),
6188 CO->getTrueExpr());
6189 std::tie(FalseTy, FalseName) =
6190 shouldNotPrintDirectly(Context,
6191 CO->getFalseExpr()->getType(),
6192 CO->getFalseExpr());
6193
6194 if (TrueTy == FalseTy)
6195 return std::make_pair(TrueTy, TrueName);
6196 else if (TrueTy.isNull())
6197 return std::make_pair(FalseTy, FalseName);
6198 else if (FalseTy.isNull())
6199 return std::make_pair(TrueTy, TrueName);
6200 }
6201
6202 return std::make_pair(QualType(), StringRef());
6203}
6204
Richard Smith55ce3522012-06-25 20:30:08 +00006205bool
6206CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
6207 const char *StartSpecifier,
6208 unsigned SpecifierLen,
6209 const Expr *E) {
6210 using namespace analyze_format_string;
6211 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006212 // Now type check the data expression that matches the
6213 // format specifier.
Mehdi Amini06d367c2016-10-24 20:39:34 +00006214 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
Jordan Rose22b74712012-09-05 22:56:19 +00006215 if (!AT.isValid())
6216 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00006217
Jordan Rose598ec092012-12-05 18:44:40 +00006218 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00006219 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
6220 ExprTy = TET->getUnderlyingExpr()->getType();
6221 }
6222
Seth Cantrellb4802962015-03-04 03:12:10 +00006223 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
6224
6225 if (match == analyze_printf::ArgType::Match) {
Jordan Rose22b74712012-09-05 22:56:19 +00006226 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00006227 }
Jordan Rose98709982012-06-04 22:48:57 +00006228
Jordan Rose22b74712012-09-05 22:56:19 +00006229 // Look through argument promotions for our error message's reported type.
6230 // This includes the integral and floating promotions, but excludes array
6231 // and function pointer decay; seeing that an argument intended to be a
6232 // string has type 'char [6]' is probably more confusing than 'char *'.
6233 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6234 if (ICE->getCastKind() == CK_IntegralCast ||
6235 ICE->getCastKind() == CK_FloatingCast) {
6236 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00006237 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00006238
6239 // Check if we didn't match because of an implicit cast from a 'char'
6240 // or 'short' to an 'int'. This is done because printf is a varargs
6241 // function.
6242 if (ICE->getType() == S.Context.IntTy ||
6243 ICE->getType() == S.Context.UnsignedIntTy) {
6244 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00006245 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00006246 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00006247 }
Jordan Rose98709982012-06-04 22:48:57 +00006248 }
Jordan Rose598ec092012-12-05 18:44:40 +00006249 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
6250 // Special case for 'a', which has type 'int' in C.
6251 // Note, however, that we do /not/ want to treat multibyte constants like
6252 // 'MooV' as characters! This form is deprecated but still exists.
6253 if (ExprTy == S.Context.IntTy)
6254 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
6255 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00006256 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006257
Jordan Rosebc53ed12014-05-31 04:12:14 +00006258 // Look through enums to their underlying type.
6259 bool IsEnum = false;
6260 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
6261 ExprTy = EnumTy->getDecl()->getIntegerType();
6262 IsEnum = true;
6263 }
6264
Jordan Rose0e5badd2012-12-05 18:44:49 +00006265 // %C in an Objective-C context prints a unichar, not a wchar_t.
6266 // If the argument is an integer of some kind, believe the %C and suggest
6267 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00006268 QualType IntendedTy = ExprTy;
Mehdi Amini06d367c2016-10-24 20:39:34 +00006269 if (isObjCContext() &&
Jordan Rose0e5badd2012-12-05 18:44:49 +00006270 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
6271 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
6272 !ExprTy->isCharType()) {
6273 // 'unichar' is defined as a typedef of unsigned short, but we should
6274 // prefer using the typedef if it is visible.
6275 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00006276
6277 // While we are here, check if the value is an IntegerLiteral that happens
6278 // to be within the valid range.
6279 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
6280 const llvm::APInt &V = IL->getValue();
6281 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
6282 return true;
6283 }
6284
Jordan Rose0e5badd2012-12-05 18:44:49 +00006285 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
6286 Sema::LookupOrdinaryName);
6287 if (S.LookupName(Result, S.getCurScope())) {
6288 NamedDecl *ND = Result.getFoundDecl();
6289 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
6290 if (TD->getUnderlyingType() == IntendedTy)
6291 IntendedTy = S.Context.getTypedefType(TD);
6292 }
6293 }
6294 }
6295
6296 // Special-case some of Darwin's platform-independence types by suggesting
6297 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006298 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00006299 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006300 QualType CastTy;
6301 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
6302 if (!CastTy.isNull()) {
6303 IntendedTy = CastTy;
6304 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00006305 }
6306 }
6307
Jordan Rose22b74712012-09-05 22:56:19 +00006308 // We may be able to offer a FixItHint if it is a supported type.
6309 PrintfSpecifier fixedFS = FS;
Mehdi Amini06d367c2016-10-24 20:39:34 +00006310 bool success =
6311 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006312
Jordan Rose22b74712012-09-05 22:56:19 +00006313 if (success) {
6314 // Get the fix string from the fixed format specifier
6315 SmallString<16> buf;
6316 llvm::raw_svector_ostream os(buf);
6317 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006318
Jordan Roseaee34382012-09-05 22:56:26 +00006319 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
6320
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006321 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Daniel Jasperad8d8492015-03-04 14:18:20 +00006322 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6323 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6324 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6325 }
Jordan Rose0e5badd2012-12-05 18:44:49 +00006326 // In this case, the specifier is wrong and should be changed to match
6327 // the argument.
Daniel Jasperad8d8492015-03-04 14:18:20 +00006328 EmitFormatDiagnostic(S.PDiag(diag)
6329 << AT.getRepresentativeTypeName(S.Context)
6330 << IntendedTy << IsEnum << E->getSourceRange(),
6331 E->getLocStart(),
6332 /*IsStringLocation*/ false, SpecRange,
6333 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00006334 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00006335 // The canonical type for formatting this value is different from the
6336 // actual type of the expression. (This occurs, for example, with Darwin's
6337 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
6338 // should be printed as 'long' for 64-bit compatibility.)
6339 // Rather than emitting a normal format/argument mismatch, we want to
6340 // add a cast to the recommended type (and correct the format string
6341 // if necessary).
6342 SmallString<16> CastBuf;
6343 llvm::raw_svector_ostream CastFix(CastBuf);
6344 CastFix << "(";
6345 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
6346 CastFix << ")";
6347
6348 SmallVector<FixItHint,4> Hints;
6349 if (!AT.matchesType(S.Context, IntendedTy))
6350 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
6351
6352 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
6353 // If there's already a cast present, just replace it.
6354 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
6355 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
6356
6357 } else if (!requiresParensToAddCast(E)) {
6358 // If the expression has high enough precedence,
6359 // just write the C-style cast.
6360 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6361 CastFix.str()));
6362 } else {
6363 // Otherwise, add parens around the expression as well as the cast.
6364 CastFix << "(";
6365 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6366 CastFix.str()));
6367
Alp Tokerb6cc5922014-05-03 03:45:55 +00006368 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00006369 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
6370 }
6371
Jordan Rose0e5badd2012-12-05 18:44:49 +00006372 if (ShouldNotPrintDirectly) {
6373 // The expression has a type that should not be printed directly.
6374 // We extract the name from the typedef because we don't want to show
6375 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006376 StringRef Name;
6377 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
6378 Name = TypedefTy->getDecl()->getName();
6379 else
6380 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00006381 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00006382 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00006383 << E->getSourceRange(),
6384 E->getLocStart(), /*IsStringLocation=*/false,
6385 SpecRange, Hints);
6386 } else {
6387 // In this case, the expression could be printed using a different
6388 // specifier, but we've decided that the specifier is probably correct
6389 // and we should cast instead. Just use the normal warning message.
6390 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00006391 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6392 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00006393 << E->getSourceRange(),
6394 E->getLocStart(), /*IsStringLocation*/false,
6395 SpecRange, Hints);
6396 }
Jordan Roseaee34382012-09-05 22:56:26 +00006397 }
Jordan Rose22b74712012-09-05 22:56:19 +00006398 } else {
6399 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
6400 SpecifierLen);
6401 // Since the warning for passing non-POD types to variadic functions
6402 // was deferred until now, we emit a warning for non-POD
6403 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00006404 switch (S.isValidVarArgType(ExprTy)) {
6405 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00006406 case Sema::VAK_ValidInCXX11: {
6407 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6408 if (match == analyze_printf::ArgType::NoMatchPedantic) {
6409 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6410 }
Richard Smithd7293d72013-08-05 18:49:43 +00006411
Seth Cantrellb4802962015-03-04 03:12:10 +00006412 EmitFormatDiagnostic(
6413 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
6414 << IsEnum << CSR << E->getSourceRange(),
6415 E->getLocStart(), /*IsStringLocation*/ false, CSR);
6416 break;
6417 }
Richard Smithd7293d72013-08-05 18:49:43 +00006418 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00006419 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00006420 EmitFormatDiagnostic(
6421 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006422 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00006423 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00006424 << CallType
6425 << AT.getRepresentativeTypeName(S.Context)
6426 << CSR
6427 << E->getSourceRange(),
6428 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00006429 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00006430 break;
6431
6432 case Sema::VAK_Invalid:
6433 if (ExprTy->isObjCObjectType())
6434 EmitFormatDiagnostic(
6435 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
6436 << S.getLangOpts().CPlusPlus11
6437 << ExprTy
6438 << CallType
6439 << AT.getRepresentativeTypeName(S.Context)
6440 << CSR
6441 << E->getSourceRange(),
6442 E->getLocStart(), /*IsStringLocation*/false, CSR);
6443 else
6444 // FIXME: If this is an initializer list, suggest removing the braces
6445 // or inserting a cast to the target type.
6446 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
6447 << isa<InitListExpr>(E) << ExprTy << CallType
6448 << AT.getRepresentativeTypeName(S.Context)
6449 << E->getSourceRange();
6450 break;
6451 }
6452
6453 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
6454 "format string specifier index out of range");
6455 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006456 }
6457
Ted Kremenekab278de2010-01-28 23:39:18 +00006458 return true;
6459}
6460
Ted Kremenek02087932010-07-16 02:11:22 +00006461//===--- CHECK: Scanf format string checking ------------------------------===//
6462
6463namespace {
6464class CheckScanfHandler : public CheckFormatHandler {
6465public:
Stephen Hines648c3692016-09-16 01:07:04 +00006466 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00006467 const Expr *origFormatExpr, Sema::FormatStringType type,
6468 unsigned firstDataArg, unsigned numDataArgs,
6469 const char *beg, bool hasVAListArg,
6470 ArrayRef<const Expr *> Args, unsigned formatIdx,
6471 bool inFunctionCall, Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006472 llvm::SmallBitVector &CheckedVarArgs,
6473 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00006474 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
6475 numDataArgs, beg, hasVAListArg, Args, formatIdx,
6476 inFunctionCall, CallType, CheckedVarArgs,
6477 UncoveredArg) {}
6478
Ted Kremenek02087932010-07-16 02:11:22 +00006479 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
6480 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006481 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00006482
6483 bool HandleInvalidScanfConversionSpecifier(
6484 const analyze_scanf::ScanfSpecifier &FS,
6485 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006486 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006487
Craig Toppere14c0f82014-03-12 04:55:44 +00006488 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00006489};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006490} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00006491
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006492void CheckScanfHandler::HandleIncompleteScanList(const char *start,
6493 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006494 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
6495 getLocationOfByte(end), /*IsStringLocation*/true,
6496 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006497}
6498
Ted Kremenekce815422010-07-19 21:25:57 +00006499bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
6500 const analyze_scanf::ScanfSpecifier &FS,
6501 const char *startSpecifier,
6502 unsigned specifierLen) {
6503
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006504 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00006505 FS.getConversionSpecifier();
6506
6507 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
6508 getLocationOfByte(CS.getStart()),
6509 startSpecifier, specifierLen,
6510 CS.getStart(), CS.getLength());
6511}
6512
Ted Kremenek02087932010-07-16 02:11:22 +00006513bool CheckScanfHandler::HandleScanfSpecifier(
6514 const analyze_scanf::ScanfSpecifier &FS,
6515 const char *startSpecifier,
6516 unsigned specifierLen) {
Ted Kremenek02087932010-07-16 02:11:22 +00006517 using namespace analyze_scanf;
6518 using namespace analyze_format_string;
6519
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006520 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00006521
Ted Kremenek6cd69422010-07-19 22:01:06 +00006522 // Handle case where '%' and '*' don't consume an argument. These shouldn't
6523 // be used to decide if we are using positional arguments consistently.
6524 if (FS.consumesDataArgument()) {
6525 if (atFirstArg) {
6526 atFirstArg = false;
6527 usesPositionalArgs = FS.usesPositionalArg();
6528 }
6529 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006530 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
6531 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00006532 return false;
6533 }
Ted Kremenek02087932010-07-16 02:11:22 +00006534 }
6535
6536 // Check if the field with is non-zero.
6537 const OptionalAmount &Amt = FS.getFieldWidth();
6538 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
6539 if (Amt.getConstantAmount() == 0) {
6540 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
6541 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00006542 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
6543 getLocationOfByte(Amt.getStart()),
6544 /*IsStringLocation*/true, R,
6545 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00006546 }
6547 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006548
Ted Kremenek02087932010-07-16 02:11:22 +00006549 if (!FS.consumesDataArgument()) {
6550 // FIXME: Technically specifying a precision or field width here
6551 // makes no sense. Worth issuing a warning at some point.
6552 return true;
6553 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006554
Ted Kremenek02087932010-07-16 02:11:22 +00006555 // Consume the argument.
6556 unsigned argIndex = FS.getArgIndex();
6557 if (argIndex < NumDataArgs) {
6558 // The check to see if the argIndex is valid will come later.
6559 // We set the bit here because we may exit early from this
6560 // function if we encounter some other error.
6561 CoveredArgs.set(argIndex);
6562 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006563
Ted Kremenek4407ea42010-07-20 20:04:47 +00006564 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00006565 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00006566 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6567 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00006568 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006569 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00006570 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006571 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6572 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00006573
Jordan Rose92303592012-09-08 04:00:03 +00006574 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6575 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6576
Ted Kremenek02087932010-07-16 02:11:22 +00006577 // The remaining checks depend on the data arguments.
6578 if (HasVAListArg)
6579 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00006580
Ted Kremenek6adb7e32010-07-26 19:45:42 +00006581 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00006582 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00006583
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006584 // Check that the argument type matches the format specifier.
6585 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00006586 if (!Ex)
6587 return true;
6588
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00006589 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00006590
6591 if (!AT.isValid()) {
6592 return true;
6593 }
6594
Seth Cantrellb4802962015-03-04 03:12:10 +00006595 analyze_format_string::ArgType::MatchKind match =
6596 AT.matchesType(S.Context, Ex->getType());
Seth Cantrell79340072015-03-04 05:58:08 +00006597 if (match == analyze_format_string::ArgType::Match) {
6598 return true;
6599 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006600
Seth Cantrell79340072015-03-04 05:58:08 +00006601 ScanfSpecifier fixedFS = FS;
6602 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
6603 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006604
Seth Cantrell79340072015-03-04 05:58:08 +00006605 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6606 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6607 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6608 }
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006609
Seth Cantrell79340072015-03-04 05:58:08 +00006610 if (success) {
6611 // Get the fix string from the fixed format specifier.
6612 SmallString<128> buf;
6613 llvm::raw_svector_ostream os(buf);
6614 fixedFS.toString(os);
6615
6616 EmitFormatDiagnostic(
6617 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
6618 << Ex->getType() << false << Ex->getSourceRange(),
6619 Ex->getLocStart(),
6620 /*IsStringLocation*/ false,
6621 getSpecifierRange(startSpecifier, specifierLen),
6622 FixItHint::CreateReplacement(
6623 getSpecifierRange(startSpecifier, specifierLen), os.str()));
6624 } else {
6625 EmitFormatDiagnostic(S.PDiag(diag)
6626 << AT.getRepresentativeTypeName(S.Context)
6627 << Ex->getType() << false << Ex->getSourceRange(),
6628 Ex->getLocStart(),
6629 /*IsStringLocation*/ false,
6630 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006631 }
6632
Ted Kremenek02087932010-07-16 02:11:22 +00006633 return true;
6634}
6635
Stephen Hines648c3692016-09-16 01:07:04 +00006636static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006637 const Expr *OrigFormatExpr,
6638 ArrayRef<const Expr *> Args,
6639 bool HasVAListArg, unsigned format_idx,
6640 unsigned firstDataArg,
6641 Sema::FormatStringType Type,
6642 bool inFunctionCall,
6643 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006644 llvm::SmallBitVector &CheckedVarArgs,
6645 UncoveredArgHandler &UncoveredArg) {
Ted Kremenekab278de2010-01-28 23:39:18 +00006646 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00006647 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006648 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006649 S, inFunctionCall, Args[format_idx],
6650 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00006651 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00006652 return;
6653 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006654
Ted Kremenekab278de2010-01-28 23:39:18 +00006655 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006656 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00006657 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006658 // Account for cases where the string literal is truncated in a declaration.
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006659 const ConstantArrayType *T =
6660 S.Context.getAsConstantArrayType(FExpr->getType());
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006661 assert(T && "String literal not of constant array type!");
6662 size_t TypeSize = T->getSize().getZExtValue();
6663 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00006664 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006665
6666 // Emit a warning if the string literal is truncated and does not contain an
6667 // embedded null character.
6668 if (TypeSize <= StrRef.size() &&
6669 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
6670 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006671 S, inFunctionCall, Args[format_idx],
6672 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006673 FExpr->getLocStart(),
6674 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
6675 return;
6676 }
6677
Ted Kremenekab278de2010-01-28 23:39:18 +00006678 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00006679 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006680 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006681 S, inFunctionCall, Args[format_idx],
6682 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00006683 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00006684 return;
6685 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006686
6687 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
Mehdi Amini06d367c2016-10-24 20:39:34 +00006688 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
6689 Type == Sema::FST_OSTrace) {
6690 CheckPrintfHandler H(
6691 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
6692 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
6693 HasVAListArg, Args, format_idx, inFunctionCall, CallType,
6694 CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006695
Hans Wennborg23926bd2011-12-15 10:25:47 +00006696 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006697 S.getLangOpts(),
6698 S.Context.getTargetInfo(),
6699 Type == Sema::FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00006700 H.DoneProcessing();
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006701 } else if (Type == Sema::FST_Scanf) {
Mehdi Amini06d367c2016-10-24 20:39:34 +00006702 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
6703 numDataArgs, Str, HasVAListArg, Args, format_idx,
6704 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006705
Hans Wennborg23926bd2011-12-15 10:25:47 +00006706 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006707 S.getLangOpts(),
6708 S.Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00006709 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00006710 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00006711}
6712
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00006713bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
6714 // Str - The format string. NOTE: this is NOT null-terminated!
6715 StringRef StrRef = FExpr->getString();
6716 const char *Str = StrRef.data();
6717 // Account for cases where the string literal is truncated in a declaration.
6718 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
6719 assert(T && "String literal not of constant array type!");
6720 size_t TypeSize = T->getSize().getZExtValue();
6721 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
6722 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
6723 getLangOpts(),
6724 Context.getTargetInfo());
6725}
6726
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006727//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
6728
6729// Returns the related absolute value function that is larger, of 0 if one
6730// does not exist.
6731static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
6732 switch (AbsFunction) {
6733 default:
6734 return 0;
6735
6736 case Builtin::BI__builtin_abs:
6737 return Builtin::BI__builtin_labs;
6738 case Builtin::BI__builtin_labs:
6739 return Builtin::BI__builtin_llabs;
6740 case Builtin::BI__builtin_llabs:
6741 return 0;
6742
6743 case Builtin::BI__builtin_fabsf:
6744 return Builtin::BI__builtin_fabs;
6745 case Builtin::BI__builtin_fabs:
6746 return Builtin::BI__builtin_fabsl;
6747 case Builtin::BI__builtin_fabsl:
6748 return 0;
6749
6750 case Builtin::BI__builtin_cabsf:
6751 return Builtin::BI__builtin_cabs;
6752 case Builtin::BI__builtin_cabs:
6753 return Builtin::BI__builtin_cabsl;
6754 case Builtin::BI__builtin_cabsl:
6755 return 0;
6756
6757 case Builtin::BIabs:
6758 return Builtin::BIlabs;
6759 case Builtin::BIlabs:
6760 return Builtin::BIllabs;
6761 case Builtin::BIllabs:
6762 return 0;
6763
6764 case Builtin::BIfabsf:
6765 return Builtin::BIfabs;
6766 case Builtin::BIfabs:
6767 return Builtin::BIfabsl;
6768 case Builtin::BIfabsl:
6769 return 0;
6770
6771 case Builtin::BIcabsf:
6772 return Builtin::BIcabs;
6773 case Builtin::BIcabs:
6774 return Builtin::BIcabsl;
6775 case Builtin::BIcabsl:
6776 return 0;
6777 }
6778}
6779
6780// Returns the argument type of the absolute value function.
6781static QualType getAbsoluteValueArgumentType(ASTContext &Context,
6782 unsigned AbsType) {
6783 if (AbsType == 0)
6784 return QualType();
6785
6786 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
6787 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
6788 if (Error != ASTContext::GE_None)
6789 return QualType();
6790
6791 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
6792 if (!FT)
6793 return QualType();
6794
6795 if (FT->getNumParams() != 1)
6796 return QualType();
6797
6798 return FT->getParamType(0);
6799}
6800
6801// Returns the best absolute value function, or zero, based on type and
6802// current absolute value function.
6803static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
6804 unsigned AbsFunctionKind) {
6805 unsigned BestKind = 0;
6806 uint64_t ArgSize = Context.getTypeSize(ArgType);
6807 for (unsigned Kind = AbsFunctionKind; Kind != 0;
6808 Kind = getLargerAbsoluteValueFunction(Kind)) {
6809 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
6810 if (Context.getTypeSize(ParamType) >= ArgSize) {
6811 if (BestKind == 0)
6812 BestKind = Kind;
6813 else if (Context.hasSameType(ParamType, ArgType)) {
6814 BestKind = Kind;
6815 break;
6816 }
6817 }
6818 }
6819 return BestKind;
6820}
6821
6822enum AbsoluteValueKind {
6823 AVK_Integer,
6824 AVK_Floating,
6825 AVK_Complex
6826};
6827
6828static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
6829 if (T->isIntegralOrEnumerationType())
6830 return AVK_Integer;
6831 if (T->isRealFloatingType())
6832 return AVK_Floating;
6833 if (T->isAnyComplexType())
6834 return AVK_Complex;
6835
6836 llvm_unreachable("Type not integer, floating, or complex");
6837}
6838
6839// Changes the absolute value function to a different type. Preserves whether
6840// the function is a builtin.
6841static unsigned changeAbsFunction(unsigned AbsKind,
6842 AbsoluteValueKind ValueKind) {
6843 switch (ValueKind) {
6844 case AVK_Integer:
6845 switch (AbsKind) {
6846 default:
6847 return 0;
6848 case Builtin::BI__builtin_fabsf:
6849 case Builtin::BI__builtin_fabs:
6850 case Builtin::BI__builtin_fabsl:
6851 case Builtin::BI__builtin_cabsf:
6852 case Builtin::BI__builtin_cabs:
6853 case Builtin::BI__builtin_cabsl:
6854 return Builtin::BI__builtin_abs;
6855 case Builtin::BIfabsf:
6856 case Builtin::BIfabs:
6857 case Builtin::BIfabsl:
6858 case Builtin::BIcabsf:
6859 case Builtin::BIcabs:
6860 case Builtin::BIcabsl:
6861 return Builtin::BIabs;
6862 }
6863 case AVK_Floating:
6864 switch (AbsKind) {
6865 default:
6866 return 0;
6867 case Builtin::BI__builtin_abs:
6868 case Builtin::BI__builtin_labs:
6869 case Builtin::BI__builtin_llabs:
6870 case Builtin::BI__builtin_cabsf:
6871 case Builtin::BI__builtin_cabs:
6872 case Builtin::BI__builtin_cabsl:
6873 return Builtin::BI__builtin_fabsf;
6874 case Builtin::BIabs:
6875 case Builtin::BIlabs:
6876 case Builtin::BIllabs:
6877 case Builtin::BIcabsf:
6878 case Builtin::BIcabs:
6879 case Builtin::BIcabsl:
6880 return Builtin::BIfabsf;
6881 }
6882 case AVK_Complex:
6883 switch (AbsKind) {
6884 default:
6885 return 0;
6886 case Builtin::BI__builtin_abs:
6887 case Builtin::BI__builtin_labs:
6888 case Builtin::BI__builtin_llabs:
6889 case Builtin::BI__builtin_fabsf:
6890 case Builtin::BI__builtin_fabs:
6891 case Builtin::BI__builtin_fabsl:
6892 return Builtin::BI__builtin_cabsf;
6893 case Builtin::BIabs:
6894 case Builtin::BIlabs:
6895 case Builtin::BIllabs:
6896 case Builtin::BIfabsf:
6897 case Builtin::BIfabs:
6898 case Builtin::BIfabsl:
6899 return Builtin::BIcabsf;
6900 }
6901 }
6902 llvm_unreachable("Unable to convert function");
6903}
6904
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00006905static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006906 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
6907 if (!FnInfo)
6908 return 0;
6909
6910 switch (FDecl->getBuiltinID()) {
6911 default:
6912 return 0;
6913 case Builtin::BI__builtin_abs:
6914 case Builtin::BI__builtin_fabs:
6915 case Builtin::BI__builtin_fabsf:
6916 case Builtin::BI__builtin_fabsl:
6917 case Builtin::BI__builtin_labs:
6918 case Builtin::BI__builtin_llabs:
6919 case Builtin::BI__builtin_cabs:
6920 case Builtin::BI__builtin_cabsf:
6921 case Builtin::BI__builtin_cabsl:
6922 case Builtin::BIabs:
6923 case Builtin::BIlabs:
6924 case Builtin::BIllabs:
6925 case Builtin::BIfabs:
6926 case Builtin::BIfabsf:
6927 case Builtin::BIfabsl:
6928 case Builtin::BIcabs:
6929 case Builtin::BIcabsf:
6930 case Builtin::BIcabsl:
6931 return FDecl->getBuiltinID();
6932 }
6933 llvm_unreachable("Unknown Builtin type");
6934}
6935
6936// If the replacement is valid, emit a note with replacement function.
6937// Additionally, suggest including the proper header if not already included.
6938static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00006939 unsigned AbsKind, QualType ArgType) {
6940 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00006941 const char *HeaderName = nullptr;
Mehdi Amini7186a432016-10-11 19:04:24 +00006942 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00006943 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
6944 FunctionName = "std::abs";
6945 if (ArgType->isIntegralOrEnumerationType()) {
6946 HeaderName = "cstdlib";
6947 } else if (ArgType->isRealFloatingType()) {
6948 HeaderName = "cmath";
6949 } else {
6950 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006951 }
Richard Trieubeffb832014-04-15 23:47:53 +00006952
6953 // Lookup all std::abs
6954 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00006955 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00006956 R.suppressDiagnostics();
6957 S.LookupQualifiedName(R, Std);
6958
6959 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006960 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00006961 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
6962 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
6963 } else {
6964 FDecl = dyn_cast<FunctionDecl>(I);
6965 }
6966 if (!FDecl)
6967 continue;
6968
6969 // Found std::abs(), check that they are the right ones.
6970 if (FDecl->getNumParams() != 1)
6971 continue;
6972
6973 // Check that the parameter type can handle the argument.
6974 QualType ParamType = FDecl->getParamDecl(0)->getType();
6975 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
6976 S.Context.getTypeSize(ArgType) <=
6977 S.Context.getTypeSize(ParamType)) {
6978 // Found a function, don't need the header hint.
6979 EmitHeaderHint = false;
6980 break;
6981 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006982 }
Richard Trieubeffb832014-04-15 23:47:53 +00006983 }
6984 } else {
Eric Christopher02d5d862015-08-06 01:01:12 +00006985 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
Richard Trieubeffb832014-04-15 23:47:53 +00006986 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
6987
6988 if (HeaderName) {
6989 DeclarationName DN(&S.Context.Idents.get(FunctionName));
6990 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
6991 R.suppressDiagnostics();
6992 S.LookupName(R, S.getCurScope());
6993
6994 if (R.isSingleResult()) {
6995 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
6996 if (FD && FD->getBuiltinID() == AbsKind) {
6997 EmitHeaderHint = false;
6998 } else {
6999 return;
7000 }
7001 } else if (!R.empty()) {
7002 return;
7003 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007004 }
7005 }
7006
7007 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00007008 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007009
Richard Trieubeffb832014-04-15 23:47:53 +00007010 if (!HeaderName)
7011 return;
7012
7013 if (!EmitHeaderHint)
7014 return;
7015
Alp Toker5d96e0a2014-07-11 20:53:51 +00007016 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
7017 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00007018}
7019
Richard Trieua7f30b12016-12-06 01:42:28 +00007020template <std::size_t StrLen>
7021static bool IsStdFunction(const FunctionDecl *FDecl,
7022 const char (&Str)[StrLen]) {
Richard Trieubeffb832014-04-15 23:47:53 +00007023 if (!FDecl)
7024 return false;
Richard Trieua7f30b12016-12-06 01:42:28 +00007025 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
Richard Trieubeffb832014-04-15 23:47:53 +00007026 return false;
Richard Trieua7f30b12016-12-06 01:42:28 +00007027 if (!FDecl->isInStdNamespace())
Richard Trieubeffb832014-04-15 23:47:53 +00007028 return false;
7029
7030 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007031}
7032
7033// Warn when using the wrong abs() function.
7034void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
Richard Trieua7f30b12016-12-06 01:42:28 +00007035 const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007036 if (Call->getNumArgs() != 1)
7037 return;
7038
7039 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieua7f30b12016-12-06 01:42:28 +00007040 bool IsStdAbs = IsStdFunction(FDecl, "abs");
Richard Trieubeffb832014-04-15 23:47:53 +00007041 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007042 return;
7043
7044 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7045 QualType ParamType = Call->getArg(0)->getType();
7046
Alp Toker5d96e0a2014-07-11 20:53:51 +00007047 // Unsigned types cannot be negative. Suggest removing the absolute value
7048 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007049 if (ArgType->isUnsignedIntegerType()) {
Mehdi Amini7186a432016-10-11 19:04:24 +00007050 const char *FunctionName =
Eric Christopher02d5d862015-08-06 01:01:12 +00007051 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007052 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
7053 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00007054 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007055 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
7056 return;
7057 }
7058
David Majnemer7f77eb92015-11-15 03:04:34 +00007059 // Taking the absolute value of a pointer is very suspicious, they probably
7060 // wanted to index into an array, dereference a pointer, call a function, etc.
7061 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
7062 unsigned DiagType = 0;
7063 if (ArgType->isFunctionType())
7064 DiagType = 1;
7065 else if (ArgType->isArrayType())
7066 DiagType = 2;
7067
7068 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
7069 return;
7070 }
7071
Richard Trieubeffb832014-04-15 23:47:53 +00007072 // std::abs has overloads which prevent most of the absolute value problems
7073 // from occurring.
7074 if (IsStdAbs)
7075 return;
7076
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007077 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
7078 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
7079
7080 // The argument and parameter are the same kind. Check if they are the right
7081 // size.
7082 if (ArgValueKind == ParamValueKind) {
7083 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
7084 return;
7085
7086 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
7087 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
7088 << FDecl << ArgType << ParamType;
7089
7090 if (NewAbsKind == 0)
7091 return;
7092
7093 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00007094 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007095 return;
7096 }
7097
7098 // ArgValueKind != ParamValueKind
7099 // The wrong type of absolute value function was used. Attempt to find the
7100 // proper one.
7101 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
7102 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
7103 if (NewAbsKind == 0)
7104 return;
7105
7106 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
7107 << FDecl << ParamValueKind << ArgValueKind;
7108
7109 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00007110 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007111}
7112
Richard Trieu67c00712016-12-05 23:41:46 +00007113//===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
Richard Trieua7f30b12016-12-06 01:42:28 +00007114void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
7115 const FunctionDecl *FDecl) {
Richard Trieu67c00712016-12-05 23:41:46 +00007116 if (!Call || !FDecl) return;
7117
7118 // Ignore template specializations and macros.
Richard Smith51ec0cf2017-02-21 01:17:38 +00007119 if (inTemplateInstantiation()) return;
Richard Trieu67c00712016-12-05 23:41:46 +00007120 if (Call->getExprLoc().isMacroID()) return;
7121
7122 // Only care about the one template argument, two function parameter std::max
7123 if (Call->getNumArgs() != 2) return;
Richard Trieua7f30b12016-12-06 01:42:28 +00007124 if (!IsStdFunction(FDecl, "max")) return;
Richard Trieu67c00712016-12-05 23:41:46 +00007125 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
7126 if (!ArgList) return;
7127 if (ArgList->size() != 1) return;
7128
7129 // Check that template type argument is unsigned integer.
7130 const auto& TA = ArgList->get(0);
7131 if (TA.getKind() != TemplateArgument::Type) return;
7132 QualType ArgType = TA.getAsType();
7133 if (!ArgType->isUnsignedIntegerType()) return;
7134
7135 // See if either argument is a literal zero.
7136 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
7137 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
7138 if (!MTE) return false;
7139 const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
7140 if (!Num) return false;
7141 if (Num->getValue() != 0) return false;
7142 return true;
7143 };
7144
7145 const Expr *FirstArg = Call->getArg(0);
7146 const Expr *SecondArg = Call->getArg(1);
7147 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
7148 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
7149
7150 // Only warn when exactly one argument is zero.
7151 if (IsFirstArgZero == IsSecondArgZero) return;
7152
7153 SourceRange FirstRange = FirstArg->getSourceRange();
7154 SourceRange SecondRange = SecondArg->getSourceRange();
7155
7156 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
7157
7158 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
7159 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
7160
7161 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
7162 SourceRange RemovalRange;
7163 if (IsFirstArgZero) {
7164 RemovalRange = SourceRange(FirstRange.getBegin(),
7165 SecondRange.getBegin().getLocWithOffset(-1));
7166 } else {
7167 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
7168 SecondRange.getEnd());
7169 }
7170
7171 Diag(Call->getExprLoc(), diag::note_remove_max_call)
7172 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
7173 << FixItHint::CreateRemoval(RemovalRange);
7174}
7175
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007176//===--- CHECK: Standard memory functions ---------------------------------===//
7177
Nico Weber0e6daef2013-12-26 23:38:39 +00007178/// \brief Takes the expression passed to the size_t parameter of functions
7179/// such as memcmp, strncat, etc and warns if it's a comparison.
7180///
7181/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
7182static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
7183 IdentifierInfo *FnName,
7184 SourceLocation FnLoc,
7185 SourceLocation RParenLoc) {
7186 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
7187 if (!Size)
7188 return false;
7189
7190 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
7191 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
7192 return false;
7193
Nico Weber0e6daef2013-12-26 23:38:39 +00007194 SourceRange SizeRange = Size->getSourceRange();
7195 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
7196 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00007197 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00007198 << FnName << FixItHint::CreateInsertion(
7199 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00007200 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00007201 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00007202 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00007203 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
7204 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00007205
7206 return true;
7207}
7208
Reid Kleckner5fb5b122014-06-27 23:58:21 +00007209/// \brief Determine whether the given type is or contains a dynamic class type
7210/// (e.g., whether it has a vtable).
7211static const CXXRecordDecl *getContainedDynamicClass(QualType T,
7212 bool &IsContained) {
7213 // Look through array types while ignoring qualifiers.
7214 const Type *Ty = T->getBaseElementTypeUnsafe();
7215 IsContained = false;
7216
7217 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
7218 RD = RD ? RD->getDefinition() : nullptr;
Richard Trieu1c7237a2016-03-31 04:18:07 +00007219 if (!RD || RD->isInvalidDecl())
Reid Kleckner5fb5b122014-06-27 23:58:21 +00007220 return nullptr;
7221
7222 if (RD->isDynamicClass())
7223 return RD;
7224
7225 // Check all the fields. If any bases were dynamic, the class is dynamic.
7226 // It's impossible for a class to transitively contain itself by value, so
7227 // infinite recursion is impossible.
7228 for (auto *FD : RD->fields()) {
7229 bool SubContained;
7230 if (const CXXRecordDecl *ContainedRD =
7231 getContainedDynamicClass(FD->getType(), SubContained)) {
7232 IsContained = true;
7233 return ContainedRD;
7234 }
7235 }
7236
7237 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00007238}
7239
Chandler Carruth889ed862011-06-21 23:04:20 +00007240/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007241/// otherwise returns NULL.
Nico Weberc44b35e2015-03-21 17:37:46 +00007242static const Expr *getSizeOfExprArg(const Expr *E) {
Nico Weberc5e73862011-06-14 16:14:58 +00007243 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007244 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
7245 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
7246 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00007247
Craig Topperc3ec1492014-05-26 06:22:03 +00007248 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007249}
7250
Chandler Carruth889ed862011-06-21 23:04:20 +00007251/// \brief If E is a sizeof expression, returns its argument type.
Nico Weberc44b35e2015-03-21 17:37:46 +00007252static QualType getSizeOfArgType(const Expr *E) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007253 if (const UnaryExprOrTypeTraitExpr *SizeOf =
7254 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
7255 if (SizeOf->getKind() == clang::UETT_SizeOf)
7256 return SizeOf->getTypeOfArgument();
7257
7258 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00007259}
7260
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007261/// \brief Check for dangerous or invalid arguments to memset().
7262///
Chandler Carruthac687262011-06-03 06:23:57 +00007263/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007264/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
7265/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007266///
7267/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007268void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00007269 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007270 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00007271 assert(BId != 0);
7272
Ted Kremenekb5fabb22011-04-28 01:38:02 +00007273 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00007274 // we have enough arguments, and if not, abort further checking.
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007275 unsigned ExpectedNumArgs =
7276 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00007277 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00007278 return;
7279
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007280 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
Anna Zaks22122702012-01-17 00:37:07 +00007281 BId == Builtin::BIstrndup ? 1 : 2);
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007282 unsigned LenArg =
7283 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00007284 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007285
Nico Weber0e6daef2013-12-26 23:38:39 +00007286 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
7287 Call->getLocStart(), Call->getRParenLoc()))
7288 return;
7289
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007290 // We have special checking when the length is a sizeof expression.
7291 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
7292 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
7293 llvm::FoldingSetNodeID SizeOfArgID;
7294
Bruno Cardoso Lopesc73e4c32016-08-11 18:33:15 +00007295 // Although widely used, 'bzero' is not a standard function. Be more strict
7296 // with the argument types before allowing diagnostics and only allow the
7297 // form bzero(ptr, sizeof(...)).
7298 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7299 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
7300 return;
7301
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007302 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
7303 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00007304 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007305
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007306 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00007307 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007308 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00007309 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00007310
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007311 // Never warn about void type pointers. This can be used to suppress
7312 // false positives.
7313 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007314 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007315
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007316 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
7317 // actually comparing the expressions for equality. Because computing the
7318 // expression IDs can be expensive, we only do this if the diagnostic is
7319 // enabled.
7320 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007321 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
7322 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007323 // We only compute IDs for expressions if the warning is enabled, and
7324 // cache the sizeof arg's ID.
7325 if (SizeOfArgID == llvm::FoldingSetNodeID())
7326 SizeOfArg->Profile(SizeOfArgID, Context, true);
7327 llvm::FoldingSetNodeID DestID;
7328 Dest->Profile(DestID, Context, true);
7329 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00007330 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
7331 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007332 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00007333 StringRef ReadableName = FnName->getName();
7334
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007335 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00007336 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007337 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00007338 if (!PointeeTy->isIncompleteType() &&
7339 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007340 ActionIdx = 2; // If the pointee's size is sizeof(char),
7341 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00007342
7343 // If the function is defined as a builtin macro, do not show macro
7344 // expansion.
7345 SourceLocation SL = SizeOfArg->getExprLoc();
7346 SourceRange DSR = Dest->getSourceRange();
7347 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00007348 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00007349
7350 if (SM.isMacroArgExpansion(SL)) {
7351 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
7352 SL = SM.getSpellingLoc(SL);
7353 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
7354 SM.getSpellingLoc(DSR.getEnd()));
7355 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
7356 SM.getSpellingLoc(SSR.getEnd()));
7357 }
7358
Anna Zaksd08d9152012-05-30 23:14:52 +00007359 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007360 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00007361 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00007362 << PointeeTy
7363 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00007364 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00007365 << SSR);
7366 DiagRuntimeBehavior(SL, SizeOfArg,
7367 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
7368 << ActionIdx
7369 << SSR);
7370
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007371 break;
7372 }
7373 }
7374
7375 // Also check for cases where the sizeof argument is the exact same
7376 // type as the memory argument, and where it points to a user-defined
7377 // record type.
7378 if (SizeOfArgTy != QualType()) {
7379 if (PointeeTy->isRecordType() &&
7380 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
7381 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
7382 PDiag(diag::warn_sizeof_pointer_type_memaccess)
7383 << FnName << SizeOfArgTy << ArgIdx
7384 << PointeeTy << Dest->getSourceRange()
7385 << LenExpr->getSourceRange());
7386 break;
7387 }
Nico Weberc5e73862011-06-14 16:14:58 +00007388 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00007389 } else if (DestTy->isArrayType()) {
7390 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00007391 }
Nico Weberc5e73862011-06-14 16:14:58 +00007392
Nico Weberc44b35e2015-03-21 17:37:46 +00007393 if (PointeeTy == QualType())
7394 continue;
Anna Zaks22122702012-01-17 00:37:07 +00007395
Nico Weberc44b35e2015-03-21 17:37:46 +00007396 // Always complain about dynamic classes.
7397 bool IsContained;
7398 if (const CXXRecordDecl *ContainedRD =
7399 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00007400
Nico Weberc44b35e2015-03-21 17:37:46 +00007401 unsigned OperationType = 0;
7402 // "overwritten" if we're warning about the destination for any call
7403 // but memcmp; otherwise a verb appropriate to the call.
7404 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
7405 if (BId == Builtin::BImemcpy)
7406 OperationType = 1;
7407 else if(BId == Builtin::BImemmove)
7408 OperationType = 2;
7409 else if (BId == Builtin::BImemcmp)
7410 OperationType = 3;
7411 }
7412
John McCall31168b02011-06-15 23:02:42 +00007413 DiagRuntimeBehavior(
7414 Dest->getExprLoc(), Dest,
Nico Weberc44b35e2015-03-21 17:37:46 +00007415 PDiag(diag::warn_dyn_class_memaccess)
7416 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
7417 << FnName << IsContained << ContainedRD << OperationType
7418 << Call->getCallee()->getSourceRange());
7419 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
7420 BId != Builtin::BImemset)
7421 DiagRuntimeBehavior(
7422 Dest->getExprLoc(), Dest,
7423 PDiag(diag::warn_arc_object_memaccess)
7424 << ArgIdx << FnName << PointeeTy
7425 << Call->getCallee()->getSourceRange());
7426 else
7427 continue;
7428
7429 DiagRuntimeBehavior(
7430 Dest->getExprLoc(), Dest,
7431 PDiag(diag::note_bad_memaccess_silence)
7432 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
7433 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007434 }
7435}
7436
Ted Kremenek6865f772011-08-18 20:55:45 +00007437// A little helper routine: ignore addition and subtraction of integer literals.
7438// This intentionally does not ignore all integer constant expressions because
7439// we don't want to remove sizeof().
7440static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
7441 Ex = Ex->IgnoreParenCasts();
7442
7443 for (;;) {
7444 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
7445 if (!BO || !BO->isAdditiveOp())
7446 break;
7447
7448 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
7449 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
7450
7451 if (isa<IntegerLiteral>(RHS))
7452 Ex = LHS;
7453 else if (isa<IntegerLiteral>(LHS))
7454 Ex = RHS;
7455 else
7456 break;
7457 }
7458
7459 return Ex;
7460}
7461
Anna Zaks13b08572012-08-08 21:42:23 +00007462static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
7463 ASTContext &Context) {
7464 // Only handle constant-sized or VLAs, but not flexible members.
7465 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
7466 // Only issue the FIXIT for arrays of size > 1.
7467 if (CAT->getSize().getSExtValue() <= 1)
7468 return false;
7469 } else if (!Ty->isVariableArrayType()) {
7470 return false;
7471 }
7472 return true;
7473}
7474
Ted Kremenek6865f772011-08-18 20:55:45 +00007475// Warn if the user has made the 'size' argument to strlcpy or strlcat
7476// be the size of the source, instead of the destination.
7477void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
7478 IdentifierInfo *FnName) {
7479
7480 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00007481 unsigned NumArgs = Call->getNumArgs();
7482 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00007483 return;
7484
7485 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
7486 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00007487 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00007488
7489 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
7490 Call->getLocStart(), Call->getRParenLoc()))
7491 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00007492
7493 // Look for 'strlcpy(dst, x, sizeof(x))'
7494 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
7495 CompareWithSrc = Ex;
7496 else {
7497 // Look for 'strlcpy(dst, x, strlen(x))'
7498 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00007499 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
7500 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00007501 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
7502 }
7503 }
7504
7505 if (!CompareWithSrc)
7506 return;
7507
7508 // Determine if the argument to sizeof/strlen is equal to the source
7509 // argument. In principle there's all kinds of things you could do
7510 // here, for instance creating an == expression and evaluating it with
7511 // EvaluateAsBooleanCondition, but this uses a more direct technique:
7512 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
7513 if (!SrcArgDRE)
7514 return;
7515
7516 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
7517 if (!CompareWithSrcDRE ||
7518 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
7519 return;
7520
7521 const Expr *OriginalSizeArg = Call->getArg(2);
7522 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
7523 << OriginalSizeArg->getSourceRange() << FnName;
7524
7525 // Output a FIXIT hint if the destination is an array (rather than a
7526 // pointer to an array). This could be enhanced to handle some
7527 // pointers if we know the actual size, like if DstArg is 'array+2'
7528 // we could say 'sizeof(array)-2'.
7529 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00007530 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00007531 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00007532
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00007533 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00007534 llvm::raw_svector_ostream OS(sizeString);
7535 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007536 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00007537 OS << ")";
7538
7539 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
7540 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
7541 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00007542}
7543
Anna Zaks314cd092012-02-01 19:08:57 +00007544/// Check if two expressions refer to the same declaration.
7545static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
7546 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
7547 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
7548 return D1->getDecl() == D2->getDecl();
7549 return false;
7550}
7551
7552static const Expr *getStrlenExprArg(const Expr *E) {
7553 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
7554 const FunctionDecl *FD = CE->getDirectCallee();
7555 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00007556 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00007557 return CE->getArg(0)->IgnoreParenCasts();
7558 }
Craig Topperc3ec1492014-05-26 06:22:03 +00007559 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00007560}
7561
7562// Warn on anti-patterns as the 'size' argument to strncat.
7563// The correct size argument should look like following:
7564// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
7565void Sema::CheckStrncatArguments(const CallExpr *CE,
7566 IdentifierInfo *FnName) {
7567 // Don't crash if the user has the wrong number of arguments.
7568 if (CE->getNumArgs() < 3)
7569 return;
7570 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
7571 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
7572 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
7573
Nico Weber0e6daef2013-12-26 23:38:39 +00007574 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
7575 CE->getRParenLoc()))
7576 return;
7577
Anna Zaks314cd092012-02-01 19:08:57 +00007578 // Identify common expressions, which are wrongly used as the size argument
7579 // to strncat and may lead to buffer overflows.
7580 unsigned PatternType = 0;
7581 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
7582 // - sizeof(dst)
7583 if (referToTheSameDecl(SizeOfArg, DstArg))
7584 PatternType = 1;
7585 // - sizeof(src)
7586 else if (referToTheSameDecl(SizeOfArg, SrcArg))
7587 PatternType = 2;
7588 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
7589 if (BE->getOpcode() == BO_Sub) {
7590 const Expr *L = BE->getLHS()->IgnoreParenCasts();
7591 const Expr *R = BE->getRHS()->IgnoreParenCasts();
7592 // - sizeof(dst) - strlen(dst)
7593 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
7594 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
7595 PatternType = 1;
7596 // - sizeof(src) - (anything)
7597 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
7598 PatternType = 2;
7599 }
7600 }
7601
7602 if (PatternType == 0)
7603 return;
7604
Anna Zaks5069aa32012-02-03 01:27:37 +00007605 // Generate the diagnostic.
7606 SourceLocation SL = LenArg->getLocStart();
7607 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00007608 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00007609
7610 // If the function is defined as a builtin macro, do not show macro expansion.
7611 if (SM.isMacroArgExpansion(SL)) {
7612 SL = SM.getSpellingLoc(SL);
7613 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
7614 SM.getSpellingLoc(SR.getEnd()));
7615 }
7616
Anna Zaks13b08572012-08-08 21:42:23 +00007617 // Check if the destination is an array (rather than a pointer to an array).
7618 QualType DstTy = DstArg->getType();
7619 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
7620 Context);
7621 if (!isKnownSizeArray) {
7622 if (PatternType == 1)
7623 Diag(SL, diag::warn_strncat_wrong_size) << SR;
7624 else
7625 Diag(SL, diag::warn_strncat_src_size) << SR;
7626 return;
7627 }
7628
Anna Zaks314cd092012-02-01 19:08:57 +00007629 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00007630 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00007631 else
Anna Zaks5069aa32012-02-03 01:27:37 +00007632 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00007633
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00007634 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00007635 llvm::raw_svector_ostream OS(sizeString);
7636 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007637 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00007638 OS << ") - ";
7639 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007640 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00007641 OS << ") - 1";
7642
Anna Zaks5069aa32012-02-03 01:27:37 +00007643 Diag(SL, diag::note_strncat_wrong_size)
7644 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00007645}
7646
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007647//===--- CHECK: Return Address of Stack Variable --------------------------===//
7648
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007649static const Expr *EvalVal(const Expr *E,
7650 SmallVectorImpl<const DeclRefExpr *> &refVars,
7651 const Decl *ParentDecl);
7652static const Expr *EvalAddr(const Expr *E,
7653 SmallVectorImpl<const DeclRefExpr *> &refVars,
7654 const Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007655
7656/// CheckReturnStackAddr - Check if a return statement returns the address
7657/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007658static void
7659CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
7660 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00007661
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007662 const Expr *stackE = nullptr;
7663 SmallVector<const DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007664
7665 // Perform checking for returned stack addresses, local blocks,
7666 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00007667 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007668 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007669 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00007670 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007671 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007672 }
7673
Craig Topperc3ec1492014-05-26 06:22:03 +00007674 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007675 return; // Nothing suspicious was found.
7676
Simon Pilgrim750bde62017-03-31 11:00:53 +00007677 // Parameters are initialized in the calling scope, so taking the address
Richard Trieu81b6c562016-08-05 23:24:47 +00007678 // of a parameter reference doesn't need a warning.
7679 for (auto *DRE : refVars)
7680 if (isa<ParmVarDecl>(DRE->getDecl()))
7681 return;
7682
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007683 SourceLocation diagLoc;
7684 SourceRange diagRange;
7685 if (refVars.empty()) {
7686 diagLoc = stackE->getLocStart();
7687 diagRange = stackE->getSourceRange();
7688 } else {
7689 // We followed through a reference variable. 'stackE' contains the
7690 // problematic expression but we will warn at the return statement pointing
7691 // at the reference variable. We will later display the "trail" of
7692 // reference variables using notes.
7693 diagLoc = refVars[0]->getLocStart();
7694 diagRange = refVars[0]->getSourceRange();
7695 }
7696
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007697 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
7698 // address of local var
Craig Topperda7b27f2015-11-17 05:40:09 +00007699 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007700 << DR->getDecl()->getDeclName() << diagRange;
7701 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007702 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007703 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007704 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007705 } else { // local temporary.
Richard Trieu81b6c562016-08-05 23:24:47 +00007706 // If there is an LValue->RValue conversion, then the value of the
7707 // reference type is used, not the reference.
7708 if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
7709 if (ICE->getCastKind() == CK_LValueToRValue) {
7710 return;
7711 }
7712 }
Craig Topperda7b27f2015-11-17 05:40:09 +00007713 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
7714 << lhsType->isReferenceType() << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007715 }
7716
7717 // Display the "trail" of reference variables that we followed until we
7718 // found the problematic expression using notes.
7719 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007720 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007721 // If this var binds to another reference var, show the range of the next
7722 // var, otherwise the var binds to the problematic expression, in which case
7723 // show the range of the expression.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007724 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
7725 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007726 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
7727 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007728 }
7729}
7730
7731/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
7732/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007733/// to a location on the stack, a local block, an address of a label, or a
7734/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007735/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007736/// encounter a subexpression that (1) clearly does not lead to one of the
7737/// above problematic expressions (2) is something we cannot determine leads to
7738/// a problematic expression based on such local checking.
7739///
7740/// Both EvalAddr and EvalVal follow through reference variables to evaluate
7741/// the expression that they point to. Such variables are added to the
7742/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007743///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00007744/// EvalAddr processes expressions that are pointers that are used as
7745/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007746/// At the base case of the recursion is a check for the above problematic
7747/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007748///
7749/// This implementation handles:
7750///
7751/// * pointer-to-pointer casts
7752/// * implicit conversions from array references to pointers
7753/// * taking the address of fields
7754/// * arbitrary interplay between "&" and "*" operators
7755/// * pointer arithmetic from an address of a stack variable
7756/// * taking the address of an array element where the array is on the stack
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007757static const Expr *EvalAddr(const Expr *E,
7758 SmallVectorImpl<const DeclRefExpr *> &refVars,
7759 const Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007760 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00007761 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007762
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007763 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00007764 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00007765 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00007766 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00007767 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00007768
Peter Collingbourne91147592011-04-15 00:35:48 +00007769 E = E->IgnoreParens();
7770
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007771 // Our "symbolic interpreter" is just a dispatch off the currently
7772 // viewed AST node. We then recursively traverse the AST by calling
7773 // EvalAddr and EvalVal appropriately.
7774 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007775 case Stmt::DeclRefExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007776 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007777
Richard Smith40f08eb2014-01-30 22:05:38 +00007778 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00007779 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00007780 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00007781
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007782 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007783 // If this is a reference variable, follow through to the expression that
7784 // it points to.
7785 if (V->hasLocalStorage() &&
7786 V->getType()->isReferenceType() && V->hasInit()) {
7787 // Add the reference variable to the "trail".
7788 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007789 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007790 }
7791
Craig Topperc3ec1492014-05-26 06:22:03 +00007792 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007793 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007794
Chris Lattner934edb22007-12-28 05:31:15 +00007795 case Stmt::UnaryOperatorClass: {
7796 // The only unary operator that make sense to handle here
7797 // is AddrOf. All others don't make sense as pointers.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007798 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007799
John McCalle3027922010-08-25 11:45:40 +00007800 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007801 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007802 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007803 }
Mike Stump11289f42009-09-09 15:08:12 +00007804
Chris Lattner934edb22007-12-28 05:31:15 +00007805 case Stmt::BinaryOperatorClass: {
7806 // Handle pointer arithmetic. All other binary operators are not valid
7807 // in this context.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007808 const BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00007809 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00007810
John McCalle3027922010-08-25 11:45:40 +00007811 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00007812 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00007813
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007814 const Expr *Base = B->getLHS();
Chris Lattner934edb22007-12-28 05:31:15 +00007815
7816 // Determine which argument is the real pointer base. It could be
7817 // the RHS argument instead of the LHS.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007818 if (!Base->getType()->isPointerType())
7819 Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00007820
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007821 assert(Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007822 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00007823 }
Steve Naroff2752a172008-09-10 19:17:48 +00007824
Chris Lattner934edb22007-12-28 05:31:15 +00007825 // For conditional operators we need to see if either the LHS or RHS are
7826 // valid DeclRefExpr*s. If one of them is valid, we return it.
7827 case Stmt::ConditionalOperatorClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007828 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007829
Chris Lattner934edb22007-12-28 05:31:15 +00007830 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007831 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007832 if (const Expr *LHSExpr = C->getLHS()) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007833 // In C++, we can have a throw-expression, which has 'void' type.
7834 if (!LHSExpr->getType()->isVoidType())
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007835 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007836 return LHS;
7837 }
Chris Lattner934edb22007-12-28 05:31:15 +00007838
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007839 // In C++, we can have a throw-expression, which has 'void' type.
7840 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00007841 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007842
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007843 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00007844 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007845
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007846 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00007847 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007848 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00007849 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007850
7851 case Stmt::AddrLabelExprClass:
7852 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00007853
John McCall28fc7092011-11-10 05:35:25 +00007854 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007855 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7856 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00007857
Ted Kremenekc3b4c522008-08-07 00:49:01 +00007858 // For casts, we need to handle conversions from arrays to
7859 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00007860 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00007861 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00007862 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00007863 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00007864 case Stmt::CXXStaticCastExprClass:
7865 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00007866 case Stmt::CXXConstCastExprClass:
7867 case Stmt::CXXReinterpretCastExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007868 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Eli Friedman8195ad72012-02-23 23:04:32 +00007869 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00007870 case CK_LValueToRValue:
7871 case CK_NoOp:
7872 case CK_BaseToDerived:
7873 case CK_DerivedToBase:
7874 case CK_UncheckedDerivedToBase:
7875 case CK_Dynamic:
7876 case CK_CPointerToObjCPointerCast:
7877 case CK_BlockPointerToObjCPointerCast:
7878 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007879 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00007880
7881 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007882 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00007883
Richard Trieudadefde2014-07-02 04:39:38 +00007884 case CK_BitCast:
7885 if (SubExpr->getType()->isAnyPointerType() ||
7886 SubExpr->getType()->isBlockPointerType() ||
7887 SubExpr->getType()->isObjCQualifiedIdType())
7888 return EvalAddr(SubExpr, refVars, ParentDecl);
7889 else
7890 return nullptr;
7891
Eli Friedman8195ad72012-02-23 23:04:32 +00007892 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00007893 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00007894 }
Chris Lattner934edb22007-12-28 05:31:15 +00007895 }
Mike Stump11289f42009-09-09 15:08:12 +00007896
Douglas Gregorfe314812011-06-21 17:03:29 +00007897 case Stmt::MaterializeTemporaryExprClass:
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007898 if (const Expr *Result =
7899 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7900 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00007901 return Result;
Douglas Gregorfe314812011-06-21 17:03:29 +00007902 return E;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007903
Chris Lattner934edb22007-12-28 05:31:15 +00007904 // Everything else: we simply don't reason about them.
7905 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00007906 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00007907 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007908}
Mike Stump11289f42009-09-09 15:08:12 +00007909
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007910/// EvalVal - This function is complements EvalAddr in the mutual recursion.
7911/// See the comments for EvalAddr for more details.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007912static const Expr *EvalVal(const Expr *E,
7913 SmallVectorImpl<const DeclRefExpr *> &refVars,
7914 const Decl *ParentDecl) {
7915 do {
7916 // We should only be called for evaluating non-pointer expressions, or
7917 // expressions with a pointer type that are not used as references but
7918 // instead
7919 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00007920
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007921 // Our "symbolic interpreter" is just a dispatch off the currently
7922 // viewed AST node. We then recursively traverse the AST by calling
7923 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00007924
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007925 E = E->IgnoreParens();
7926 switch (E->getStmtClass()) {
7927 case Stmt::ImplicitCastExprClass: {
7928 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
7929 if (IE->getValueKind() == VK_LValue) {
7930 E = IE->getSubExpr();
7931 continue;
7932 }
Craig Topperc3ec1492014-05-26 06:22:03 +00007933 return nullptr;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007934 }
Richard Smith40f08eb2014-01-30 22:05:38 +00007935
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007936 case Stmt::ExprWithCleanupsClass:
7937 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7938 ParentDecl);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007939
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007940 case Stmt::DeclRefExprClass: {
7941 // When we hit a DeclRefExpr we are looking at code that refers to a
7942 // variable's name. If it's not a reference variable we check if it has
7943 // local storage within the function, and if so, return the expression.
7944 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7945
7946 // If we leave the immediate function, the lifetime isn't about to end.
7947 if (DR->refersToEnclosingVariableOrCapture())
7948 return nullptr;
7949
7950 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
7951 // Check if it refers to itself, e.g. "int& i = i;".
7952 if (V == ParentDecl)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007953 return DR;
7954
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007955 if (V->hasLocalStorage()) {
7956 if (!V->getType()->isReferenceType())
7957 return DR;
7958
7959 // Reference variable, follow through to the expression that
7960 // it points to.
7961 if (V->hasInit()) {
7962 // Add the reference variable to the "trail".
7963 refVars.push_back(DR);
7964 return EvalVal(V->getInit(), refVars, V);
7965 }
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007966 }
7967 }
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007968
7969 return nullptr;
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007970 }
Mike Stump11289f42009-09-09 15:08:12 +00007971
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007972 case Stmt::UnaryOperatorClass: {
7973 // The only unary operator that make sense to handle here
7974 // is Deref. All others don't resolve to a "name." This includes
7975 // handling all sorts of rvalues passed to a unary operator.
7976 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007977
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007978 if (U->getOpcode() == UO_Deref)
7979 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Mike Stump11289f42009-09-09 15:08:12 +00007980
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007981 return nullptr;
7982 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007983
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007984 case Stmt::ArraySubscriptExprClass: {
7985 // Array subscripts are potential references to data on the stack. We
7986 // retrieve the DeclRefExpr* for the array variable if it indeed
7987 // has local storage.
Saleem Abdulrasoolcfd45532016-02-15 01:51:24 +00007988 const auto *ASE = cast<ArraySubscriptExpr>(E);
7989 if (ASE->isTypeDependent())
7990 return nullptr;
7991 return EvalAddr(ASE->getBase(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007992 }
Mike Stump11289f42009-09-09 15:08:12 +00007993
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007994 case Stmt::OMPArraySectionExprClass: {
7995 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
7996 ParentDecl);
7997 }
Mike Stump11289f42009-09-09 15:08:12 +00007998
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007999 case Stmt::ConditionalOperatorClass: {
8000 // For conditional operators we need to see if either the LHS or RHS are
8001 // non-NULL Expr's. If one is non-NULL, we return it.
8002 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Alexey Bataev1a3320e2015-08-25 14:24:04 +00008003
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008004 // Handle the GNU extension for missing LHS.
8005 if (const Expr *LHSExpr = C->getLHS()) {
8006 // In C++, we can have a throw-expression, which has 'void' type.
8007 if (!LHSExpr->getType()->isVoidType())
8008 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
8009 return LHS;
8010 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008011
Richard Smith6a6a4bb2014-01-27 04:19:56 +00008012 // In C++, we can have a throw-expression, which has 'void' type.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008013 if (C->getRHS()->getType()->isVoidType())
8014 return nullptr;
8015
8016 return EvalVal(C->getRHS(), refVars, ParentDecl);
Richard Smith6a6a4bb2014-01-27 04:19:56 +00008017 }
8018
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008019 // Accesses to members are potential references to data on the stack.
8020 case Stmt::MemberExprClass: {
8021 const MemberExpr *M = cast<MemberExpr>(E);
Anders Carlsson801c5c72007-11-30 19:04:31 +00008022
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008023 // Check for indirect access. We only want direct field accesses.
8024 if (M->isArrow())
8025 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00008026
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008027 // Check whether the member type is itself a reference, in which case
8028 // we're not going to refer to the member, but to what the member refers
8029 // to.
8030 if (M->getMemberDecl()->getType()->isReferenceType())
8031 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00008032
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008033 return EvalVal(M->getBase(), refVars, ParentDecl);
8034 }
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00008035
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008036 case Stmt::MaterializeTemporaryExprClass:
8037 if (const Expr *Result =
8038 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
8039 refVars, ParentDecl))
8040 return Result;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008041 return E;
8042
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008043 default:
8044 // Check that we don't return or take the address of a reference to a
8045 // temporary. This is only useful in C++.
8046 if (!E->isTypeDependent() && E->isRValue())
8047 return E;
8048
8049 // Everything else: we simply don't reason about them.
8050 return nullptr;
8051 }
8052 } while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008053}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008054
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008055void
8056Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
8057 SourceLocation ReturnLoc,
8058 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00008059 const AttrVec *Attrs,
8060 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008061 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
8062
8063 // Check if the return value is null but should not be.
Douglas Gregorb4866e82015-06-19 18:13:19 +00008064 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
8065 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
Benjamin Kramerae852a62014-02-23 14:34:50 +00008066 CheckNonNullExpr(*this, RetValExp))
8067 Diag(ReturnLoc, diag::warn_null_ret)
8068 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00008069
8070 // C++11 [basic.stc.dynamic.allocation]p4:
8071 // If an allocation function declared with a non-throwing
8072 // exception-specification fails to allocate storage, it shall return
8073 // a null pointer. Any other allocation function that fails to allocate
8074 // storage shall indicate failure only by throwing an exception [...]
8075 if (FD) {
8076 OverloadedOperatorKind Op = FD->getOverloadedOperator();
8077 if (Op == OO_New || Op == OO_Array_New) {
8078 const FunctionProtoType *Proto
8079 = FD->getType()->castAs<FunctionProtoType>();
8080 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
8081 CheckNonNullExpr(*this, RetValExp))
8082 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
8083 << FD << getLangOpts().CPlusPlus11;
8084 }
8085 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008086}
8087
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008088//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
8089
8090/// Check for comparisons of floating point operands using != and ==.
8091/// Issue a warning if these are no self-comparisons, as they are not likely
8092/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00008093void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00008094 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
8095 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008096
8097 // Special case: check for x == x (which is OK).
8098 // Do not emit warnings for such cases.
8099 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
8100 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
8101 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00008102 return;
Mike Stump11289f42009-09-09 15:08:12 +00008103
Ted Kremenekeda40e22007-11-29 00:59:04 +00008104 // Special case: check for comparisons against literals that can be exactly
8105 // represented by APFloat. In such cases, do not emit a warning. This
8106 // is a heuristic: often comparison against such literals are used to
8107 // detect if a value in a variable has not changed. This clearly can
8108 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00008109 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
8110 if (FLL->isExact())
8111 return;
8112 } else
8113 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
8114 if (FLR->isExact())
8115 return;
Mike Stump11289f42009-09-09 15:08:12 +00008116
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008117 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00008118 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00008119 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00008120 return;
Mike Stump11289f42009-09-09 15:08:12 +00008121
David Blaikie1f4ff152012-07-16 20:47:22 +00008122 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00008123 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00008124 return;
Mike Stump11289f42009-09-09 15:08:12 +00008125
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008126 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00008127 Diag(Loc, diag::warn_floatingpoint_eq)
8128 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008129}
John McCallca01b222010-01-04 23:21:16 +00008130
John McCall70aa5392010-01-06 05:24:50 +00008131//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
8132//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00008133
John McCall70aa5392010-01-06 05:24:50 +00008134namespace {
John McCallca01b222010-01-04 23:21:16 +00008135
John McCall70aa5392010-01-06 05:24:50 +00008136/// Structure recording the 'active' range of an integer-valued
8137/// expression.
8138struct IntRange {
8139 /// The number of bits active in the int.
8140 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00008141
John McCall70aa5392010-01-06 05:24:50 +00008142 /// True if the int is known not to have negative values.
8143 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00008144
John McCall70aa5392010-01-06 05:24:50 +00008145 IntRange(unsigned Width, bool NonNegative)
8146 : Width(Width), NonNegative(NonNegative)
8147 {}
John McCallca01b222010-01-04 23:21:16 +00008148
John McCall817d4af2010-11-10 23:38:19 +00008149 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00008150 static IntRange forBoolType() {
8151 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00008152 }
8153
John McCall817d4af2010-11-10 23:38:19 +00008154 /// Returns the range of an opaque value of the given integral type.
8155 static IntRange forValueOfType(ASTContext &C, QualType T) {
8156 return forValueOfCanonicalType(C,
8157 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00008158 }
8159
John McCall817d4af2010-11-10 23:38:19 +00008160 /// Returns the range of an opaque value of a canonical integral type.
8161 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00008162 assert(T->isCanonicalUnqualified());
8163
8164 if (const VectorType *VT = dyn_cast<VectorType>(T))
8165 T = VT->getElementType().getTypePtr();
8166 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8167 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00008168 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8169 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00008170
David Majnemer6a426652013-06-07 22:07:20 +00008171 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00008172 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00008173 EnumDecl *Enum = ET->getDecl();
8174 if (!Enum->isCompleteDefinition())
8175 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00008176
David Majnemer6a426652013-06-07 22:07:20 +00008177 unsigned NumPositive = Enum->getNumPositiveBits();
8178 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00008179
David Majnemer6a426652013-06-07 22:07:20 +00008180 if (NumNegative == 0)
8181 return IntRange(NumPositive, true/*NonNegative*/);
8182 else
8183 return IntRange(std::max(NumPositive + 1, NumNegative),
8184 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00008185 }
John McCall70aa5392010-01-06 05:24:50 +00008186
8187 const BuiltinType *BT = cast<BuiltinType>(T);
8188 assert(BT->isInteger());
8189
8190 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8191 }
8192
John McCall817d4af2010-11-10 23:38:19 +00008193 /// Returns the "target" range of a canonical integral type, i.e.
8194 /// the range of values expressible in the type.
8195 ///
8196 /// This matches forValueOfCanonicalType except that enums have the
8197 /// full range of their type, not the range of their enumerators.
8198 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
8199 assert(T->isCanonicalUnqualified());
8200
8201 if (const VectorType *VT = dyn_cast<VectorType>(T))
8202 T = VT->getElementType().getTypePtr();
8203 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8204 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00008205 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8206 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00008207 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00008208 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00008209
8210 const BuiltinType *BT = cast<BuiltinType>(T);
8211 assert(BT->isInteger());
8212
8213 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8214 }
8215
8216 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00008217 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00008218 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00008219 L.NonNegative && R.NonNegative);
8220 }
8221
John McCall817d4af2010-11-10 23:38:19 +00008222 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00008223 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00008224 return IntRange(std::min(L.Width, R.Width),
8225 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00008226 }
8227};
8228
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008229IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008230 if (value.isSigned() && value.isNegative())
8231 return IntRange(value.getMinSignedBits(), false);
8232
8233 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00008234 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00008235
8236 // isNonNegative() just checks the sign bit without considering
8237 // signedness.
8238 return IntRange(value.getActiveBits(), true);
8239}
8240
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008241IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
8242 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008243 if (result.isInt())
8244 return GetValueRange(C, result.getInt(), MaxWidth);
8245
8246 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00008247 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
8248 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
8249 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
8250 R = IntRange::join(R, El);
8251 }
John McCall70aa5392010-01-06 05:24:50 +00008252 return R;
8253 }
8254
8255 if (result.isComplexInt()) {
8256 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
8257 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
8258 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00008259 }
8260
8261 // This can happen with lossless casts to intptr_t of "based" lvalues.
8262 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00008263 // FIXME: The only reason we need to pass the type in here is to get
8264 // the sign right on this one case. It would be nice if APValue
8265 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008266 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00008267 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00008268}
John McCall70aa5392010-01-06 05:24:50 +00008269
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008270QualType GetExprType(const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008271 QualType Ty = E->getType();
8272 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
8273 Ty = AtomicRHS->getValueType();
8274 return Ty;
8275}
8276
John McCall70aa5392010-01-06 05:24:50 +00008277/// Pseudo-evaluate the given integer expression, estimating the
8278/// range of values it might take.
8279///
8280/// \param MaxWidth - the width to which the value will be truncated
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008281IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008282 E = E->IgnoreParens();
8283
8284 // Try a full evaluation first.
8285 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00008286 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00008287 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00008288
8289 // I think we only want to look through implicit casts here; if the
8290 // user has an explicit widening cast, we should treat the value as
8291 // being of the new, wider type.
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008292 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00008293 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00008294 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
8295
Eli Friedmane6d33952013-07-08 20:20:06 +00008296 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00008297
George Burgess IVdf1ed002016-01-13 01:52:39 +00008298 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
8299 CE->getCastKind() == CK_BooleanToSignedIntegral;
John McCall2ce81ad2010-01-06 22:07:33 +00008300
John McCall70aa5392010-01-06 05:24:50 +00008301 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00008302 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00008303 return OutputTypeRange;
8304
8305 IntRange SubRange
8306 = GetExprRange(C, CE->getSubExpr(),
8307 std::min(MaxWidth, OutputTypeRange.Width));
8308
8309 // Bail out if the subexpr's range is as wide as the cast type.
8310 if (SubRange.Width >= OutputTypeRange.Width)
8311 return OutputTypeRange;
8312
8313 // Otherwise, we take the smaller width, and we're non-negative if
8314 // either the output type or the subexpr is.
8315 return IntRange(SubRange.Width,
8316 SubRange.NonNegative || OutputTypeRange.NonNegative);
8317 }
8318
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008319 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008320 // If we can fold the condition, just take that operand.
8321 bool CondResult;
8322 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
8323 return GetExprRange(C, CondResult ? CO->getTrueExpr()
8324 : CO->getFalseExpr(),
8325 MaxWidth);
8326
8327 // Otherwise, conservatively merge.
8328 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
8329 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
8330 return IntRange::join(L, R);
8331 }
8332
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008333 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008334 switch (BO->getOpcode()) {
8335
8336 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00008337 case BO_LAnd:
8338 case BO_LOr:
8339 case BO_LT:
8340 case BO_GT:
8341 case BO_LE:
8342 case BO_GE:
8343 case BO_EQ:
8344 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00008345 return IntRange::forBoolType();
8346
John McCallc3688382011-07-13 06:35:24 +00008347 // The type of the assignments is the type of the LHS, so the RHS
8348 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00008349 case BO_MulAssign:
8350 case BO_DivAssign:
8351 case BO_RemAssign:
8352 case BO_AddAssign:
8353 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00008354 case BO_XorAssign:
8355 case BO_OrAssign:
8356 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00008357 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00008358
John McCallc3688382011-07-13 06:35:24 +00008359 // Simple assignments just pass through the RHS, which will have
8360 // been coerced to the LHS type.
8361 case BO_Assign:
8362 // TODO: bitfields?
8363 return GetExprRange(C, BO->getRHS(), MaxWidth);
8364
John McCall70aa5392010-01-06 05:24:50 +00008365 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00008366 case BO_PtrMemD:
8367 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00008368 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008369
John McCall2ce81ad2010-01-06 22:07:33 +00008370 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00008371 case BO_And:
8372 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00008373 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
8374 GetExprRange(C, BO->getRHS(), MaxWidth));
8375
John McCall70aa5392010-01-06 05:24:50 +00008376 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00008377 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00008378 // ...except that we want to treat '1 << (blah)' as logically
8379 // positive. It's an important idiom.
8380 if (IntegerLiteral *I
8381 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
8382 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008383 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00008384 return IntRange(R.Width, /*NonNegative*/ true);
8385 }
8386 }
8387 // fallthrough
8388
John McCalle3027922010-08-25 11:45:40 +00008389 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00008390 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008391
John McCall2ce81ad2010-01-06 22:07:33 +00008392 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00008393 case BO_Shr:
8394 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00008395 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8396
8397 // If the shift amount is a positive constant, drop the width by
8398 // that much.
8399 llvm::APSInt shift;
8400 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
8401 shift.isNonNegative()) {
8402 unsigned zext = shift.getZExtValue();
8403 if (zext >= L.Width)
8404 L.Width = (L.NonNegative ? 0 : 1);
8405 else
8406 L.Width -= zext;
8407 }
8408
8409 return L;
8410 }
8411
8412 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00008413 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00008414 return GetExprRange(C, BO->getRHS(), MaxWidth);
8415
John McCall2ce81ad2010-01-06 22:07:33 +00008416 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00008417 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00008418 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00008419 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008420 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00008421
John McCall51431812011-07-14 22:39:48 +00008422 // The width of a division result is mostly determined by the size
8423 // of the LHS.
8424 case BO_Div: {
8425 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00008426 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008427 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8428
8429 // If the divisor is constant, use that.
8430 llvm::APSInt divisor;
8431 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
8432 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
8433 if (log2 >= L.Width)
8434 L.Width = (L.NonNegative ? 0 : 1);
8435 else
8436 L.Width = std::min(L.Width - log2, MaxWidth);
8437 return L;
8438 }
8439
8440 // Otherwise, just use the LHS's width.
8441 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8442 return IntRange(L.Width, L.NonNegative && R.NonNegative);
8443 }
8444
8445 // The result of a remainder can't be larger than the result of
8446 // either side.
8447 case BO_Rem: {
8448 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00008449 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008450 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8451 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8452
8453 IntRange meet = IntRange::meet(L, R);
8454 meet.Width = std::min(meet.Width, MaxWidth);
8455 return meet;
8456 }
8457
8458 // The default behavior is okay for these.
8459 case BO_Mul:
8460 case BO_Add:
8461 case BO_Xor:
8462 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00008463 break;
8464 }
8465
John McCall51431812011-07-14 22:39:48 +00008466 // The default case is to treat the operation as if it were closed
8467 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00008468 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8469 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
8470 return IntRange::join(L, R);
8471 }
8472
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008473 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008474 switch (UO->getOpcode()) {
8475 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00008476 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00008477 return IntRange::forBoolType();
8478
8479 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00008480 case UO_Deref:
8481 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00008482 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008483
8484 default:
8485 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
8486 }
8487 }
8488
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008489 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
Ted Kremeneka553fbf2013-10-14 18:55:27 +00008490 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
8491
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008492 if (const auto *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00008493 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00008494 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00008495
Eli Friedmane6d33952013-07-08 20:20:06 +00008496 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008497}
John McCall263a48b2010-01-04 23:31:57 +00008498
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008499IntRange GetExprRange(ASTContext &C, const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008500 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00008501}
8502
John McCall263a48b2010-01-04 23:31:57 +00008503/// Checks whether the given value, which currently has the given
8504/// source semantics, has the same value when coerced through the
8505/// target semantics.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008506bool IsSameFloatAfterCast(const llvm::APFloat &value,
8507 const llvm::fltSemantics &Src,
8508 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00008509 llvm::APFloat truncated = value;
8510
8511 bool ignored;
8512 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
8513 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
8514
8515 return truncated.bitwiseIsEqual(value);
8516}
8517
8518/// Checks whether the given value, which currently has the given
8519/// source semantics, has the same value when coerced through the
8520/// target semantics.
8521///
8522/// The value might be a vector of floats (or a complex number).
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008523bool IsSameFloatAfterCast(const APValue &value,
8524 const llvm::fltSemantics &Src,
8525 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00008526 if (value.isFloat())
8527 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
8528
8529 if (value.isVector()) {
8530 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
8531 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
8532 return false;
8533 return true;
8534 }
8535
8536 assert(value.isComplexFloat());
8537 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
8538 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
8539}
8540
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008541void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008542
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008543bool IsZero(Sema &S, Expr *E) {
Ted Kremenek6274be42010-09-23 21:43:44 +00008544 // Suppress cases where we are comparing against an enum constant.
8545 if (const DeclRefExpr *DR =
8546 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
8547 if (isa<EnumConstantDecl>(DR->getDecl()))
8548 return false;
8549
8550 // Suppress cases where the '0' value is expanded from a macro.
8551 if (E->getLocStart().isMacroID())
8552 return false;
8553
John McCallcc7e5bf2010-05-06 08:58:33 +00008554 llvm::APSInt Value;
8555 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
8556}
8557
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008558bool HasEnumType(Expr *E) {
John McCall2551c1b2010-10-06 00:25:24 +00008559 // Strip off implicit integral promotions.
8560 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00008561 if (ICE->getCastKind() != CK_IntegralCast &&
8562 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00008563 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00008564 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00008565 }
8566
8567 return E->getType()->isEnumeralType();
8568}
8569
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00008570bool isNonBooleanUnsignedValue(Expr *E) {
8571 // We are checking that the expression is not known to have boolean value,
8572 // is an integer type; and is either unsigned after implicit casts,
8573 // or was unsigned before implicit casts.
8574 return !E->isKnownToHaveBooleanValue() && E->getType()->isIntegerType() &&
8575 (!E->getType()->isSignedIntegerType() ||
8576 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
8577}
8578
8579bool CheckTautologicalComparisonWithZero(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00008580 // Disable warning in template instantiations.
Richard Smith51ec0cf2017-02-21 01:17:38 +00008581 if (S.inTemplateInstantiation())
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00008582 return false;
8583
8584 // bool values are handled by DiagnoseOutOfRangeComparison().
Richard Trieu36594562013-11-01 21:47:19 +00008585
Roman Lebedevb0f0a1e2017-09-20 09:54:47 +00008586 BinaryOperatorKind Op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00008587 if (E->isValueDependent())
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00008588 return false;
Douglas Gregorb14dbd72010-12-21 07:22:56 +00008589
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00008590 Expr *LHS = E->getLHS();
8591 Expr *RHS = E->getRHS();
8592
8593 bool Match = true;
8594
Roman Lebedev30d26082017-09-20 13:50:01 +00008595 if (Op == BO_LT && isNonBooleanUnsignedValue(LHS) && IsZero(S, RHS)) {
Roman Lebedevb0f0a1e2017-09-20 09:54:47 +00008596 S.Diag(E->getOperatorLoc(),
8597 HasEnumType(LHS) ? diag::warn_lunsigned_enum_always_true_comparison
8598 : diag::warn_lunsigned_always_true_comparison)
8599 << "< 0" << false << LHS->getSourceRange() << RHS->getSourceRange();
Roman Lebedev30d26082017-09-20 13:50:01 +00008600 } else if (Op == BO_GE && isNonBooleanUnsignedValue(LHS) && IsZero(S, RHS)) {
Roman Lebedevb0f0a1e2017-09-20 09:54:47 +00008601 S.Diag(E->getOperatorLoc(),
8602 HasEnumType(LHS) ? diag::warn_lunsigned_enum_always_true_comparison
8603 : diag::warn_lunsigned_always_true_comparison)
8604 << ">= 0" << true << LHS->getSourceRange() << RHS->getSourceRange();
Roman Lebedev30d26082017-09-20 13:50:01 +00008605 } else if (Op == BO_GT && isNonBooleanUnsignedValue(RHS) && IsZero(S, LHS)) {
Roman Lebedevb0f0a1e2017-09-20 09:54:47 +00008606 S.Diag(E->getOperatorLoc(),
8607 HasEnumType(RHS) ? diag::warn_runsigned_enum_always_true_comparison
8608 : diag::warn_runsigned_always_true_comparison)
8609 << "0 >" << false << LHS->getSourceRange() << RHS->getSourceRange();
Roman Lebedev30d26082017-09-20 13:50:01 +00008610 } else if (Op == BO_LE && isNonBooleanUnsignedValue(RHS) && IsZero(S, LHS)) {
Roman Lebedevb0f0a1e2017-09-20 09:54:47 +00008611 S.Diag(E->getOperatorLoc(),
8612 HasEnumType(RHS) ? diag::warn_runsigned_enum_always_true_comparison
8613 : diag::warn_runsigned_always_true_comparison)
8614 << "0 <=" << true << LHS->getSourceRange() << RHS->getSourceRange();
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00008615 } else
8616 Match = false;
8617
8618 return Match;
John McCallcc7e5bf2010-05-06 08:58:33 +00008619}
8620
Benjamin Kramer7320b992016-06-15 14:20:56 +00008621void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E, Expr *Constant,
8622 Expr *Other, const llvm::APSInt &Value,
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008623 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00008624 // Disable warning in template instantiations.
Richard Smith51ec0cf2017-02-21 01:17:38 +00008625 if (S.inTemplateInstantiation())
Richard Trieudd51d742013-11-01 21:19:43 +00008626 return;
8627
Richard Trieu0f097742014-04-04 04:13:47 +00008628 // TODO: Investigate using GetExprRange() to get tighter bounds
8629 // on the bit ranges.
8630 QualType OtherT = Other->getType();
David Majnemer7800f1f2015-05-23 01:32:17 +00008631 if (const auto *AT = OtherT->getAs<AtomicType>())
Justin Bogner4f42fc42014-07-21 18:01:53 +00008632 OtherT = AT->getValueType();
Richard Trieu0f097742014-04-04 04:13:47 +00008633 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
8634 unsigned OtherWidth = OtherRange.Width;
8635
8636 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
8637
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00008638 // 0 values are handled later by CheckTautologicalComparisonWithZero().
Richard Trieu0f097742014-04-04 04:13:47 +00008639 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00008640 return;
8641
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008642 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00008643 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00008644
Richard Trieu0f097742014-04-04 04:13:47 +00008645 // Used for diagnostic printout.
8646 enum {
8647 LiteralConstant = 0,
8648 CXXBoolLiteralTrue,
8649 CXXBoolLiteralFalse
8650 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00008651
Richard Trieu0f097742014-04-04 04:13:47 +00008652 if (!OtherIsBooleanType) {
8653 QualType ConstantT = Constant->getType();
8654 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00008655
Richard Trieu0f097742014-04-04 04:13:47 +00008656 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
8657 return;
8658 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
8659 "comparison with non-integer type");
8660
8661 bool ConstantSigned = ConstantT->isSignedIntegerType();
8662 bool CommonSigned = CommonT->isSignedIntegerType();
8663
8664 bool EqualityOnly = false;
8665
8666 if (CommonSigned) {
8667 // The common type is signed, therefore no signed to unsigned conversion.
8668 if (!OtherRange.NonNegative) {
8669 // Check that the constant is representable in type OtherT.
8670 if (ConstantSigned) {
8671 if (OtherWidth >= Value.getMinSignedBits())
8672 return;
8673 } else { // !ConstantSigned
8674 if (OtherWidth >= Value.getActiveBits() + 1)
8675 return;
8676 }
8677 } else { // !OtherSigned
8678 // Check that the constant is representable in type OtherT.
8679 // Negative values are out of range.
8680 if (ConstantSigned) {
8681 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
8682 return;
8683 } else { // !ConstantSigned
8684 if (OtherWidth >= Value.getActiveBits())
8685 return;
8686 }
Richard Trieu560910c2012-11-14 22:50:24 +00008687 }
Richard Trieu0f097742014-04-04 04:13:47 +00008688 } else { // !CommonSigned
8689 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00008690 if (OtherWidth >= Value.getActiveBits())
8691 return;
Craig Toppercf360162014-06-18 05:13:11 +00008692 } else { // OtherSigned
8693 assert(!ConstantSigned &&
8694 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00008695 // Check to see if the constant is representable in OtherT.
8696 if (OtherWidth > Value.getActiveBits())
8697 return;
8698 // Check to see if the constant is equivalent to a negative value
8699 // cast to CommonT.
8700 if (S.Context.getIntWidth(ConstantT) ==
8701 S.Context.getIntWidth(CommonT) &&
8702 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
8703 return;
8704 // The constant value rests between values that OtherT can represent
8705 // after conversion. Relational comparison still works, but equality
8706 // comparisons will be tautological.
8707 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00008708 }
8709 }
Richard Trieu0f097742014-04-04 04:13:47 +00008710
8711 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
8712
8713 if (op == BO_EQ || op == BO_NE) {
8714 IsTrue = op == BO_NE;
8715 } else if (EqualityOnly) {
8716 return;
8717 } else if (RhsConstant) {
8718 if (op == BO_GT || op == BO_GE)
8719 IsTrue = !PositiveConstant;
8720 else // op == BO_LT || op == BO_LE
8721 IsTrue = PositiveConstant;
8722 } else {
8723 if (op == BO_LT || op == BO_LE)
8724 IsTrue = !PositiveConstant;
8725 else // op == BO_GT || op == BO_GE
8726 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00008727 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00008728 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00008729 // Other isKnownToHaveBooleanValue
8730 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
8731 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
8732 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
8733
8734 static const struct LinkedConditions {
8735 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
8736 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
8737 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
8738 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
8739 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
8740 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
8741
8742 } TruthTable = {
8743 // Constant on LHS. | Constant on RHS. |
8744 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
8745 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
8746 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
8747 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
8748 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
8749 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
8750 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
8751 };
8752
8753 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
8754
8755 enum ConstantValue ConstVal = Zero;
8756 if (Value.isUnsigned() || Value.isNonNegative()) {
8757 if (Value == 0) {
8758 LiteralOrBoolConstant =
8759 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
8760 ConstVal = Zero;
8761 } else if (Value == 1) {
8762 LiteralOrBoolConstant =
8763 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
8764 ConstVal = One;
8765 } else {
8766 LiteralOrBoolConstant = LiteralConstant;
8767 ConstVal = GT_One;
8768 }
8769 } else {
8770 ConstVal = LT_Zero;
8771 }
8772
8773 CompareBoolWithConstantResult CmpRes;
8774
8775 switch (op) {
8776 case BO_LT:
8777 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
8778 break;
8779 case BO_GT:
8780 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
8781 break;
8782 case BO_LE:
8783 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
8784 break;
8785 case BO_GE:
8786 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
8787 break;
8788 case BO_EQ:
8789 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
8790 break;
8791 case BO_NE:
8792 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
8793 break;
8794 default:
8795 CmpRes = Unkwn;
8796 break;
8797 }
8798
8799 if (CmpRes == AFals) {
8800 IsTrue = false;
8801 } else if (CmpRes == ATrue) {
8802 IsTrue = true;
8803 } else {
8804 return;
8805 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008806 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008807
8808 // If this is a comparison to an enum constant, include that
8809 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00008810 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008811 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
8812 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
8813
8814 SmallString<64> PrettySourceValue;
8815 llvm::raw_svector_ostream OS(PrettySourceValue);
8816 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00008817 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008818 else
8819 OS << Value;
8820
Richard Trieu0f097742014-04-04 04:13:47 +00008821 S.DiagRuntimeBehavior(
8822 E->getOperatorLoc(), E,
8823 S.PDiag(diag::warn_out_of_range_compare)
8824 << OS.str() << LiteralOrBoolConstant
8825 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
8826 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008827}
8828
John McCallcc7e5bf2010-05-06 08:58:33 +00008829/// Analyze the operands of the given comparison. Implements the
8830/// fallback case from AnalyzeComparison.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008831void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00008832 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8833 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00008834}
John McCall263a48b2010-01-04 23:31:57 +00008835
John McCallca01b222010-01-04 23:21:16 +00008836/// \brief Implements -Wsign-compare.
8837///
Richard Trieu82402a02011-09-15 21:56:47 +00008838/// \param E the binary operator to check for warnings
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008839void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008840 // The type the comparison is being performed in.
8841 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00008842
8843 // Only analyze comparison operators where both sides have been converted to
8844 // the same type.
8845 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
8846 return AnalyzeImpConvsInComparison(S, E);
8847
8848 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00008849 if (E->isValueDependent())
8850 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00008851
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008852 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
8853 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008854
8855 bool IsComparisonConstant = false;
8856
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00008857 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008858 // of 'true' or 'false'.
8859 if (T->isIntegralType(S.Context)) {
8860 llvm::APSInt RHSValue;
8861 bool IsRHSIntegralLiteral =
8862 RHS->isIntegerConstantExpr(RHSValue, S.Context);
8863 llvm::APSInt LHSValue;
8864 bool IsLHSIntegralLiteral =
8865 LHS->isIntegerConstantExpr(LHSValue, S.Context);
8866 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
8867 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
8868 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
8869 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
8870 else
8871 IsComparisonConstant =
8872 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00008873 } else if (!T->hasUnsignedIntegerRepresentation())
8874 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00008875
8876 // We don't care about value-dependent expressions or expressions
8877 // whose result is a constant.
8878 if (IsComparisonConstant)
8879 return AnalyzeImpConvsInComparison(S, E);
8880
8881 // If this is a tautological comparison, suppress -Wsign-compare.
8882 if (CheckTautologicalComparisonWithZero(S, E))
8883 return AnalyzeImpConvsInComparison(S, E);
8884
John McCallcc7e5bf2010-05-06 08:58:33 +00008885 // We don't do anything special if this isn't an unsigned integral
8886 // comparison: we're only interested in integral comparisons, and
8887 // signed comparisons only happen in cases we don't care to warn about.
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00008888 if (!T->hasUnsignedIntegerRepresentation())
John McCallcc7e5bf2010-05-06 08:58:33 +00008889 return AnalyzeImpConvsInComparison(S, E);
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00008890
John McCallcc7e5bf2010-05-06 08:58:33 +00008891 // Check to see if one of the (unmodified) operands is of different
8892 // signedness.
8893 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00008894 if (LHS->getType()->hasSignedIntegerRepresentation()) {
8895 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00008896 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00008897 signedOperand = LHS;
8898 unsignedOperand = RHS;
8899 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
8900 signedOperand = RHS;
8901 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00008902 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00008903 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00008904 }
8905
John McCallcc7e5bf2010-05-06 08:58:33 +00008906 // Otherwise, calculate the effective range of the signed operand.
8907 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00008908
John McCallcc7e5bf2010-05-06 08:58:33 +00008909 // Go ahead and analyze implicit conversions in the operands. Note
8910 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00008911 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
8912 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00008913
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00008914 // If the signed range is non-negative, -Wsign-compare won't fire.
John McCallcc7e5bf2010-05-06 08:58:33 +00008915 if (signedRange.NonNegative)
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00008916 return;
John McCallca01b222010-01-04 23:21:16 +00008917
8918 // For (in)equality comparisons, if the unsigned operand is a
8919 // constant which cannot collide with a overflowed signed operand,
8920 // then reinterpreting the signed operand as unsigned will not
8921 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00008922 if (E->isEqualityOp()) {
8923 unsigned comparisonWidth = S.Context.getIntWidth(T);
8924 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00008925
John McCallcc7e5bf2010-05-06 08:58:33 +00008926 // We should never be unable to prove that the unsigned operand is
8927 // non-negative.
8928 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
8929
8930 if (unsignedRange.Width < comparisonWidth)
8931 return;
8932 }
8933
Douglas Gregorbfb4a212012-05-01 01:53:49 +00008934 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
8935 S.PDiag(diag::warn_mixed_sign_comparison)
8936 << LHS->getType() << RHS->getType()
8937 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00008938}
8939
John McCall1f425642010-11-11 03:21:53 +00008940/// Analyzes an attempt to assign the given value to a bitfield.
8941///
8942/// Returns true if there was something fishy about the attempt.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008943bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
8944 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00008945 assert(Bitfield->isBitField());
8946 if (Bitfield->isInvalidDecl())
8947 return false;
8948
John McCalldeebbcf2010-11-11 05:33:51 +00008949 // White-list bool bitfields.
Reid Klecknerad425622016-11-16 23:40:00 +00008950 QualType BitfieldType = Bitfield->getType();
8951 if (BitfieldType->isBooleanType())
8952 return false;
8953
8954 if (BitfieldType->isEnumeralType()) {
8955 EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
8956 // If the underlying enum type was not explicitly specified as an unsigned
8957 // type and the enum contain only positive values, MSVC++ will cause an
8958 // inconsistency by storing this as a signed type.
8959 if (S.getLangOpts().CPlusPlus11 &&
8960 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
8961 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
8962 BitfieldEnumDecl->getNumNegativeBits() == 0) {
8963 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
8964 << BitfieldEnumDecl->getNameAsString();
8965 }
8966 }
8967
John McCalldeebbcf2010-11-11 05:33:51 +00008968 if (Bitfield->getType()->isBooleanType())
8969 return false;
8970
Douglas Gregor789adec2011-02-04 13:09:01 +00008971 // Ignore value- or type-dependent expressions.
8972 if (Bitfield->getBitWidth()->isValueDependent() ||
8973 Bitfield->getBitWidth()->isTypeDependent() ||
8974 Init->isValueDependent() ||
8975 Init->isTypeDependent())
8976 return false;
8977
John McCall1f425642010-11-11 03:21:53 +00008978 Expr *OriginalInit = Init->IgnoreParenImpCasts();
Reid Kleckner329f24d2017-03-14 18:01:02 +00008979 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00008980
Richard Smith5fab0c92011-12-28 19:48:30 +00008981 llvm::APSInt Value;
Reid Kleckner329f24d2017-03-14 18:01:02 +00008982 if (!OriginalInit->EvaluateAsInt(Value, S.Context,
8983 Expr::SE_AllowSideEffects)) {
8984 // The RHS is not constant. If the RHS has an enum type, make sure the
8985 // bitfield is wide enough to hold all the values of the enum without
8986 // truncation.
8987 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
8988 EnumDecl *ED = EnumTy->getDecl();
8989 bool SignedBitfield = BitfieldType->isSignedIntegerType();
8990
8991 // Enum types are implicitly signed on Windows, so check if there are any
8992 // negative enumerators to see if the enum was intended to be signed or
8993 // not.
8994 bool SignedEnum = ED->getNumNegativeBits() > 0;
8995
8996 // Check for surprising sign changes when assigning enum values to a
8997 // bitfield of different signedness. If the bitfield is signed and we
8998 // have exactly the right number of bits to store this unsigned enum,
8999 // suggest changing the enum to an unsigned type. This typically happens
9000 // on Windows where unfixed enums always use an underlying type of 'int'.
9001 unsigned DiagID = 0;
9002 if (SignedEnum && !SignedBitfield) {
9003 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
9004 } else if (SignedBitfield && !SignedEnum &&
9005 ED->getNumPositiveBits() == FieldWidth) {
9006 DiagID = diag::warn_signed_bitfield_enum_conversion;
9007 }
9008
9009 if (DiagID) {
9010 S.Diag(InitLoc, DiagID) << Bitfield << ED;
9011 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
9012 SourceRange TypeRange =
9013 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
9014 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
9015 << SignedEnum << TypeRange;
9016 }
9017
9018 // Compute the required bitwidth. If the enum has negative values, we need
9019 // one more bit than the normal number of positive bits to represent the
9020 // sign bit.
9021 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
9022 ED->getNumNegativeBits())
9023 : ED->getNumPositiveBits();
9024
9025 // Check the bitwidth.
9026 if (BitsNeeded > FieldWidth) {
9027 Expr *WidthExpr = Bitfield->getBitWidth();
9028 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
9029 << Bitfield << ED;
9030 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
9031 << BitsNeeded << ED << WidthExpr->getSourceRange();
9032 }
9033 }
9034
John McCall1f425642010-11-11 03:21:53 +00009035 return false;
Reid Kleckner329f24d2017-03-14 18:01:02 +00009036 }
John McCall1f425642010-11-11 03:21:53 +00009037
John McCall1f425642010-11-11 03:21:53 +00009038 unsigned OriginalWidth = Value.getBitWidth();
John McCall1f425642010-11-11 03:21:53 +00009039
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +00009040 if (!Value.isSigned() || Value.isNegative())
Richard Trieu7561ed02016-08-05 02:39:30 +00009041 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +00009042 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
9043 OriginalWidth = Value.getMinSignedBits();
Richard Trieu7561ed02016-08-05 02:39:30 +00009044
John McCall1f425642010-11-11 03:21:53 +00009045 if (OriginalWidth <= FieldWidth)
9046 return false;
9047
Eli Friedmanc267a322012-01-26 23:11:39 +00009048 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00009049 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Reid Klecknerad425622016-11-16 23:40:00 +00009050 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00009051
Eli Friedmanc267a322012-01-26 23:11:39 +00009052 // Check whether the stored value is equal to the original value.
9053 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00009054 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00009055 return false;
9056
Eli Friedmanc267a322012-01-26 23:11:39 +00009057 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00009058 // therefore don't strictly fit into a signed bitfield of width 1.
9059 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00009060 return false;
9061
John McCall1f425642010-11-11 03:21:53 +00009062 std::string PrettyValue = Value.toString(10);
9063 std::string PrettyTrunc = TruncatedValue.toString(10);
9064
9065 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
9066 << PrettyValue << PrettyTrunc << OriginalInit->getType()
9067 << Init->getSourceRange();
9068
9069 return true;
9070}
9071
John McCalld2a53122010-11-09 23:24:47 +00009072/// Analyze the given simple or compound assignment for warning-worthy
9073/// operations.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009074void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00009075 // Just recurse on the LHS.
9076 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
9077
9078 // We want to recurse on the RHS as normal unless we're assigning to
9079 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00009080 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009081 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00009082 E->getOperatorLoc())) {
9083 // Recurse, ignoring any implicit conversions on the RHS.
9084 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
9085 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00009086 }
9087 }
9088
9089 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
9090}
9091
John McCall263a48b2010-01-04 23:31:57 +00009092/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009093void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
9094 SourceLocation CContext, unsigned diag,
9095 bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00009096 if (pruneControlFlow) {
9097 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9098 S.PDiag(diag)
9099 << SourceType << T << E->getSourceRange()
9100 << SourceRange(CContext));
9101 return;
9102 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00009103 S.Diag(E->getExprLoc(), diag)
9104 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
9105}
9106
Chandler Carruth7f3654f2011-04-05 06:47:57 +00009107/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009108void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
9109 unsigned diag, bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00009110 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00009111}
9112
Richard Trieube234c32016-04-21 21:04:55 +00009113
9114/// Diagnose an implicit cast from a floating point value to an integer value.
9115void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
9116
9117 SourceLocation CContext) {
9118 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
Richard Smith51ec0cf2017-02-21 01:17:38 +00009119 const bool PruneWarnings = S.inTemplateInstantiation();
Richard Trieube234c32016-04-21 21:04:55 +00009120
9121 Expr *InnerE = E->IgnoreParenImpCasts();
9122 // We also want to warn on, e.g., "int i = -1.234"
9123 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
9124 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
9125 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
9126
9127 const bool IsLiteral =
9128 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
9129
9130 llvm::APFloat Value(0.0);
9131 bool IsConstant =
9132 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
9133 if (!IsConstant) {
Richard Trieu891f0f12016-04-22 22:14:32 +00009134 return DiagnoseImpCast(S, E, T, CContext,
9135 diag::warn_impcast_float_integer, PruneWarnings);
Richard Trieube234c32016-04-21 21:04:55 +00009136 }
9137
Chandler Carruth016ef402011-04-10 08:36:24 +00009138 bool isExact = false;
Richard Trieube234c32016-04-21 21:04:55 +00009139
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00009140 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
9141 T->hasUnsignedIntegerRepresentation());
Richard Trieube234c32016-04-21 21:04:55 +00009142 if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero,
9143 &isExact) == llvm::APFloat::opOK &&
Richard Trieu891f0f12016-04-22 22:14:32 +00009144 isExact) {
Richard Trieube234c32016-04-21 21:04:55 +00009145 if (IsLiteral) return;
9146 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
9147 PruneWarnings);
9148 }
9149
9150 unsigned DiagID = 0;
Richard Trieu891f0f12016-04-22 22:14:32 +00009151 if (IsLiteral) {
Richard Trieube234c32016-04-21 21:04:55 +00009152 // Warn on floating point literal to integer.
9153 DiagID = diag::warn_impcast_literal_float_to_integer;
9154 } else if (IntegerValue == 0) {
9155 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
9156 return DiagnoseImpCast(S, E, T, CContext,
9157 diag::warn_impcast_float_integer, PruneWarnings);
9158 }
9159 // Warn on non-zero to zero conversion.
9160 DiagID = diag::warn_impcast_float_to_integer_zero;
9161 } else {
9162 if (IntegerValue.isUnsigned()) {
9163 if (!IntegerValue.isMaxValue()) {
9164 return DiagnoseImpCast(S, E, T, CContext,
9165 diag::warn_impcast_float_integer, PruneWarnings);
9166 }
9167 } else { // IntegerValue.isSigned()
9168 if (!IntegerValue.isMaxSignedValue() &&
9169 !IntegerValue.isMinSignedValue()) {
9170 return DiagnoseImpCast(S, E, T, CContext,
9171 diag::warn_impcast_float_integer, PruneWarnings);
9172 }
9173 }
9174 // Warn on evaluatable floating point expression to integer conversion.
9175 DiagID = diag::warn_impcast_float_to_integer;
9176 }
Chandler Carruth016ef402011-04-10 08:36:24 +00009177
Eli Friedman07185912013-08-29 23:44:43 +00009178 // FIXME: Force the precision of the source value down so we don't print
9179 // digits which are usually useless (we don't really care here if we
9180 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
9181 // would automatically print the shortest representation, but it's a bit
9182 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00009183 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00009184 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
9185 precision = (precision * 59 + 195) / 196;
9186 Value.toString(PrettySourceValue, precision);
9187
David Blaikie9b88cc02012-05-15 17:18:27 +00009188 SmallString<16> PrettyTargetValue;
Richard Trieube234c32016-04-21 21:04:55 +00009189 if (IsBool)
Aaron Ballmandbc441e2015-12-30 14:26:07 +00009190 PrettyTargetValue = Value.isZero() ? "false" : "true";
David Blaikie7555b6a2012-05-15 16:56:36 +00009191 else
David Blaikie9b88cc02012-05-15 17:18:27 +00009192 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00009193
Richard Trieube234c32016-04-21 21:04:55 +00009194 if (PruneWarnings) {
9195 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9196 S.PDiag(DiagID)
9197 << E->getType() << T.getUnqualifiedType()
9198 << PrettySourceValue << PrettyTargetValue
9199 << E->getSourceRange() << SourceRange(CContext));
9200 } else {
9201 S.Diag(E->getExprLoc(), DiagID)
9202 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
9203 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
9204 }
Chandler Carruth016ef402011-04-10 08:36:24 +00009205}
9206
John McCall18a2c2c2010-11-09 22:22:12 +00009207std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
9208 if (!Range.Width) return "0";
9209
9210 llvm::APSInt ValueInRange = Value;
9211 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00009212 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00009213 return ValueInRange.toString(10);
9214}
9215
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009216bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009217 if (!isa<ImplicitCastExpr>(Ex))
9218 return false;
9219
9220 Expr *InnerE = Ex->IgnoreParenImpCasts();
9221 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
9222 const Type *Source =
9223 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
9224 if (Target->isDependentType())
9225 return false;
9226
9227 const BuiltinType *FloatCandidateBT =
9228 dyn_cast<BuiltinType>(ToBool ? Source : Target);
9229 const Type *BoolCandidateType = ToBool ? Target : Source;
9230
9231 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
9232 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
9233}
9234
9235void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
9236 SourceLocation CC) {
9237 unsigned NumArgs = TheCall->getNumArgs();
9238 for (unsigned i = 0; i < NumArgs; ++i) {
9239 Expr *CurrA = TheCall->getArg(i);
9240 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
9241 continue;
9242
9243 bool IsSwapped = ((i > 0) &&
9244 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
9245 IsSwapped |= ((i < (NumArgs - 1)) &&
9246 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
9247 if (IsSwapped) {
9248 // Warn on this floating-point to bool conversion.
9249 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
9250 CurrA->getType(), CC,
9251 diag::warn_impcast_floating_point_to_bool);
9252 }
9253 }
9254}
9255
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009256void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) {
Richard Trieu5b993502014-10-15 03:42:06 +00009257 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
9258 E->getExprLoc()))
9259 return;
9260
Richard Trieu09d6b802016-01-08 23:35:06 +00009261 // Don't warn on functions which have return type nullptr_t.
9262 if (isa<CallExpr>(E))
9263 return;
9264
Richard Trieu5b993502014-10-15 03:42:06 +00009265 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
9266 const Expr::NullPointerConstantKind NullKind =
9267 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
9268 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
9269 return;
9270
9271 // Return if target type is a safe conversion.
9272 if (T->isAnyPointerType() || T->isBlockPointerType() ||
9273 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
9274 return;
9275
9276 SourceLocation Loc = E->getSourceRange().getBegin();
9277
Richard Trieu0a5e1662016-02-13 00:58:53 +00009278 // Venture through the macro stacks to get to the source of macro arguments.
9279 // The new location is a better location than the complete location that was
9280 // passed in.
9281 while (S.SourceMgr.isMacroArgExpansion(Loc))
9282 Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc);
9283
9284 while (S.SourceMgr.isMacroArgExpansion(CC))
9285 CC = S.SourceMgr.getImmediateMacroCallerLoc(CC);
9286
Richard Trieu5b993502014-10-15 03:42:06 +00009287 // __null is usually wrapped in a macro. Go up a macro if that is the case.
Richard Trieu0a5e1662016-02-13 00:58:53 +00009288 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
9289 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
9290 Loc, S.SourceMgr, S.getLangOpts());
9291 if (MacroName == "NULL")
9292 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
Richard Trieu5b993502014-10-15 03:42:06 +00009293 }
9294
9295 // Only warn if the null and context location are in the same macro expansion.
9296 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
9297 return;
9298
9299 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
9300 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
9301 << FixItHint::CreateReplacement(Loc,
9302 S.getFixItZeroLiteralForType(T, Loc));
9303}
9304
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009305void checkObjCArrayLiteral(Sema &S, QualType TargetType,
9306 ObjCArrayLiteral *ArrayLiteral);
9307void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
9308 ObjCDictionaryLiteral *DictionaryLiteral);
Douglas Gregor5054cb02015-07-07 03:58:22 +00009309
9310/// Check a single element within a collection literal against the
9311/// target element type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009312void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType,
9313 Expr *Element, unsigned ElementKind) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00009314 // Skip a bitcast to 'id' or qualified 'id'.
9315 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
9316 if (ICE->getCastKind() == CK_BitCast &&
9317 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
9318 Element = ICE->getSubExpr();
9319 }
9320
9321 QualType ElementType = Element->getType();
9322 ExprResult ElementResult(Element);
9323 if (ElementType->getAs<ObjCObjectPointerType>() &&
9324 S.CheckSingleAssignmentConstraints(TargetElementType,
9325 ElementResult,
9326 false, false)
9327 != Sema::Compatible) {
9328 S.Diag(Element->getLocStart(),
9329 diag::warn_objc_collection_literal_element)
9330 << ElementType << ElementKind << TargetElementType
9331 << Element->getSourceRange();
9332 }
9333
9334 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
9335 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
9336 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
9337 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
9338}
9339
9340/// Check an Objective-C array literal being converted to the given
9341/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009342void checkObjCArrayLiteral(Sema &S, QualType TargetType,
9343 ObjCArrayLiteral *ArrayLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00009344 if (!S.NSArrayDecl)
9345 return;
9346
9347 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
9348 if (!TargetObjCPtr)
9349 return;
9350
9351 if (TargetObjCPtr->isUnspecialized() ||
9352 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
9353 != S.NSArrayDecl->getCanonicalDecl())
9354 return;
9355
9356 auto TypeArgs = TargetObjCPtr->getTypeArgs();
9357 if (TypeArgs.size() != 1)
9358 return;
9359
9360 QualType TargetElementType = TypeArgs[0];
9361 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
9362 checkObjCCollectionLiteralElement(S, TargetElementType,
9363 ArrayLiteral->getElement(I),
9364 0);
9365 }
9366}
9367
9368/// Check an Objective-C dictionary literal being converted to the given
9369/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009370void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
9371 ObjCDictionaryLiteral *DictionaryLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00009372 if (!S.NSDictionaryDecl)
9373 return;
9374
9375 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
9376 if (!TargetObjCPtr)
9377 return;
9378
9379 if (TargetObjCPtr->isUnspecialized() ||
9380 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
9381 != S.NSDictionaryDecl->getCanonicalDecl())
9382 return;
9383
9384 auto TypeArgs = TargetObjCPtr->getTypeArgs();
9385 if (TypeArgs.size() != 2)
9386 return;
9387
9388 QualType TargetKeyType = TypeArgs[0];
9389 QualType TargetObjectType = TypeArgs[1];
9390 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
9391 auto Element = DictionaryLiteral->getKeyValueElement(I);
9392 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
9393 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
9394 }
9395}
9396
Richard Trieufc404c72016-02-05 23:02:38 +00009397// Helper function to filter out cases for constant width constant conversion.
9398// Don't warn on char array initialization or for non-decimal values.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009399bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
9400 SourceLocation CC) {
Richard Trieufc404c72016-02-05 23:02:38 +00009401 // If initializing from a constant, and the constant starts with '0',
9402 // then it is a binary, octal, or hexadecimal. Allow these constants
9403 // to fill all the bits, even if there is a sign change.
9404 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
9405 const char FirstLiteralCharacter =
9406 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
9407 if (FirstLiteralCharacter == '0')
9408 return false;
9409 }
9410
9411 // If the CC location points to a '{', and the type is char, then assume
9412 // assume it is an array initialization.
9413 if (CC.isValid() && T->isCharType()) {
9414 const char FirstContextCharacter =
9415 S.getSourceManager().getCharacterData(CC)[0];
9416 if (FirstContextCharacter == '{')
9417 return false;
9418 }
9419
9420 return true;
9421}
9422
John McCallcc7e5bf2010-05-06 08:58:33 +00009423void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00009424 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009425 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00009426
John McCallcc7e5bf2010-05-06 08:58:33 +00009427 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
9428 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
9429 if (Source == Target) return;
9430 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00009431
Chandler Carruthc22845a2011-07-26 05:40:03 +00009432 // If the conversion context location is invalid don't complain. We also
9433 // don't want to emit a warning if the issue occurs from the expansion of
9434 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
9435 // delay this check as long as possible. Once we detect we are in that
9436 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009437 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00009438 return;
9439
Richard Trieu021baa32011-09-23 20:10:00 +00009440 // Diagnose implicit casts to bool.
9441 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
9442 if (isa<StringLiteral>(E))
9443 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00009444 // and expressions, for instance, assert(0 && "error here"), are
9445 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00009446 return DiagnoseImpCast(S, E, T, CC,
9447 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00009448 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
9449 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
9450 // This covers the literal expressions that evaluate to Objective-C
9451 // objects.
9452 return DiagnoseImpCast(S, E, T, CC,
9453 diag::warn_impcast_objective_c_literal_to_bool);
9454 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00009455 if (Source->isPointerType() || Source->canDecayToPointerType()) {
9456 // Warn on pointer to bool conversion that is always true.
9457 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
9458 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00009459 }
Richard Trieu021baa32011-09-23 20:10:00 +00009460 }
John McCall263a48b2010-01-04 23:31:57 +00009461
Douglas Gregor5054cb02015-07-07 03:58:22 +00009462 // Check implicit casts from Objective-C collection literals to specialized
9463 // collection types, e.g., NSArray<NSString *> *.
9464 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
9465 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
9466 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
9467 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
9468
John McCall263a48b2010-01-04 23:31:57 +00009469 // Strip vector types.
9470 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009471 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009472 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009473 return;
John McCallacf0ee52010-10-08 02:01:28 +00009474 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009475 }
Chris Lattneree7286f2011-06-14 04:51:15 +00009476
9477 // If the vector cast is cast between two vectors of the same size, it is
9478 // a bitcast, not a conversion.
9479 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
9480 return;
John McCall263a48b2010-01-04 23:31:57 +00009481
9482 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
9483 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
9484 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00009485 if (auto VecTy = dyn_cast<VectorType>(Target))
9486 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00009487
9488 // Strip complex types.
9489 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009490 if (!isa<ComplexType>(Target)) {
Tim Northover02416372017-08-08 23:18:05 +00009491 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009492 return;
9493
Tim Northover02416372017-08-08 23:18:05 +00009494 return DiagnoseImpCast(S, E, T, CC,
9495 S.getLangOpts().CPlusPlus
9496 ? diag::err_impcast_complex_scalar
9497 : diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009498 }
John McCall263a48b2010-01-04 23:31:57 +00009499
9500 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
9501 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
9502 }
9503
9504 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
9505 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
9506
9507 // If the source is floating point...
9508 if (SourceBT && SourceBT->isFloatingPoint()) {
9509 // ...and the target is floating point...
9510 if (TargetBT && TargetBT->isFloatingPoint()) {
9511 // ...then warn if we're dropping FP rank.
9512
9513 // Builtin FP kinds are ordered by increasing FP rank.
9514 if (SourceBT->getKind() > TargetBT->getKind()) {
9515 // Don't warn about float constants that are precisely
9516 // representable in the target type.
9517 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00009518 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00009519 // Value might be a float, a float vector, or a float complex.
9520 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00009521 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
9522 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00009523 return;
9524 }
9525
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009526 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009527 return;
9528
John McCallacf0ee52010-10-08 02:01:28 +00009529 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
George Burgess IV148e0d32015-10-29 00:28:52 +00009530 }
9531 // ... or possibly if we're increasing rank, too
9532 else if (TargetBT->getKind() > SourceBT->getKind()) {
9533 if (S.SourceMgr.isInSystemMacro(CC))
9534 return;
9535
9536 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
John McCall263a48b2010-01-04 23:31:57 +00009537 }
9538 return;
9539 }
9540
Richard Trieube234c32016-04-21 21:04:55 +00009541 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00009542 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009543 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009544 return;
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00009545
Richard Trieube234c32016-04-21 21:04:55 +00009546 DiagnoseFloatingImpCast(S, E, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00009547 }
John McCall263a48b2010-01-04 23:31:57 +00009548
Richard Smith54894fd2015-12-30 01:06:52 +00009549 // Detect the case where a call result is converted from floating-point to
9550 // to bool, and the final argument to the call is converted from bool, to
9551 // discover this typo:
9552 //
9553 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
9554 //
9555 // FIXME: This is an incredibly special case; is there some more general
9556 // way to detect this class of misplaced-parentheses bug?
9557 if (Target->isBooleanType() && isa<CallExpr>(E)) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009558 // Check last argument of function call to see if it is an
9559 // implicit cast from a type matching the type the result
9560 // is being cast to.
9561 CallExpr *CEx = cast<CallExpr>(E);
Richard Smith54894fd2015-12-30 01:06:52 +00009562 if (unsigned NumArgs = CEx->getNumArgs()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009563 Expr *LastA = CEx->getArg(NumArgs - 1);
9564 Expr *InnerE = LastA->IgnoreParenImpCasts();
Richard Smith54894fd2015-12-30 01:06:52 +00009565 if (isa<ImplicitCastExpr>(LastA) &&
9566 InnerE->getType()->isBooleanType()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009567 // Warn on this floating-point to bool conversion
9568 DiagnoseImpCast(S, E, T, CC,
9569 diag::warn_impcast_floating_point_to_bool);
9570 }
9571 }
9572 }
John McCall263a48b2010-01-04 23:31:57 +00009573 return;
9574 }
9575
Richard Trieu5b993502014-10-15 03:42:06 +00009576 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +00009577
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +00009578 S.DiscardMisalignedMemberAddress(Target, E);
9579
David Blaikie9366d2b2012-06-19 21:19:06 +00009580 if (!Source->isIntegerType() || !Target->isIntegerType())
9581 return;
9582
David Blaikie7555b6a2012-05-15 16:56:36 +00009583 // TODO: remove this early return once the false positives for constant->bool
9584 // in templates, macros, etc, are reduced or removed.
9585 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
9586 return;
9587
John McCallcc7e5bf2010-05-06 08:58:33 +00009588 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00009589 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00009590
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009591 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00009592 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009593 // TODO: this should happen for bitfield stores, too.
9594 llvm::APSInt Value(32);
Richard Trieudcb55572016-01-29 23:51:16 +00009595 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009596 if (S.SourceMgr.isInSystemMacro(CC))
9597 return;
9598
John McCall18a2c2c2010-11-09 22:22:12 +00009599 std::string PrettySourceValue = Value.toString(10);
9600 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009601
Ted Kremenek33ba9952011-10-22 02:37:33 +00009602 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9603 S.PDiag(diag::warn_impcast_integer_precision_constant)
9604 << PrettySourceValue << PrettyTargetValue
9605 << E->getType() << T << E->getSourceRange()
9606 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00009607 return;
9608 }
9609
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009610 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
9611 if (S.SourceMgr.isInSystemMacro(CC))
9612 return;
9613
David Blaikie9455da02012-04-12 22:40:54 +00009614 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00009615 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
9616 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00009617 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00009618 }
9619
Richard Trieudcb55572016-01-29 23:51:16 +00009620 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
9621 SourceRange.NonNegative && Source->isSignedIntegerType()) {
9622 // Warn when doing a signed to signed conversion, warn if the positive
9623 // source value is exactly the width of the target type, which will
9624 // cause a negative value to be stored.
9625
9626 llvm::APSInt Value;
Richard Trieufc404c72016-02-05 23:02:38 +00009627 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
9628 !S.SourceMgr.isInSystemMacro(CC)) {
9629 if (isSameWidthConstantConversion(S, E, T, CC)) {
9630 std::string PrettySourceValue = Value.toString(10);
9631 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Richard Trieudcb55572016-01-29 23:51:16 +00009632
Richard Trieufc404c72016-02-05 23:02:38 +00009633 S.DiagRuntimeBehavior(
9634 E->getExprLoc(), E,
9635 S.PDiag(diag::warn_impcast_integer_precision_constant)
9636 << PrettySourceValue << PrettyTargetValue << E->getType() << T
9637 << E->getSourceRange() << clang::SourceRange(CC));
9638 return;
Richard Trieudcb55572016-01-29 23:51:16 +00009639 }
9640 }
Richard Trieufc404c72016-02-05 23:02:38 +00009641
Richard Trieudcb55572016-01-29 23:51:16 +00009642 // Fall through for non-constants to give a sign conversion warning.
9643 }
9644
John McCallcc7e5bf2010-05-06 08:58:33 +00009645 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
9646 (!TargetRange.NonNegative && SourceRange.NonNegative &&
9647 SourceRange.Width == TargetRange.Width)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009648 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009649 return;
9650
John McCallcc7e5bf2010-05-06 08:58:33 +00009651 unsigned DiagID = diag::warn_impcast_integer_sign;
9652
9653 // Traditionally, gcc has warned about this under -Wsign-compare.
9654 // We also want to warn about it in -Wconversion.
9655 // So if -Wconversion is off, use a completely identical diagnostic
9656 // in the sign-compare group.
9657 // The conditional-checking code will
9658 if (ICContext) {
9659 DiagID = diag::warn_impcast_integer_sign_conditional;
9660 *ICContext = true;
9661 }
9662
John McCallacf0ee52010-10-08 02:01:28 +00009663 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00009664 }
9665
Douglas Gregora78f1932011-02-22 02:45:07 +00009666 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00009667 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
9668 // type, to give us better diagnostics.
9669 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00009670 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00009671 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9672 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
9673 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
9674 SourceType = S.Context.getTypeDeclType(Enum);
9675 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
9676 }
9677 }
9678
Douglas Gregora78f1932011-02-22 02:45:07 +00009679 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
9680 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00009681 if (SourceEnum->getDecl()->hasNameForLinkage() &&
9682 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009683 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009684 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009685 return;
9686
Douglas Gregor364f7db2011-03-12 00:14:31 +00009687 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00009688 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009689 }
John McCall263a48b2010-01-04 23:31:57 +00009690}
9691
David Blaikie18e9ac72012-05-15 21:57:38 +00009692void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9693 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009694
9695void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00009696 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009697 E = E->IgnoreParenImpCasts();
9698
9699 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00009700 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009701
John McCallacf0ee52010-10-08 02:01:28 +00009702 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009703 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00009704 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00009705}
9706
David Blaikie18e9ac72012-05-15 21:57:38 +00009707void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9708 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00009709 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00009710
9711 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00009712 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
9713 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00009714
9715 // If -Wconversion would have warned about either of the candidates
9716 // for a signedness conversion to the context type...
9717 if (!Suspicious) return;
9718
9719 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009720 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00009721 return;
9722
John McCallcc7e5bf2010-05-06 08:58:33 +00009723 // ...then check whether it would have warned about either of the
9724 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00009725 if (E->getType() == T) return;
9726
9727 Suspicious = false;
9728 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
9729 E->getType(), CC, &Suspicious);
9730 if (!Suspicious)
9731 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00009732 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00009733}
9734
Richard Trieu65724892014-11-15 06:37:39 +00009735/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9736/// Input argument E is a logical expression.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009737void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
Richard Trieu65724892014-11-15 06:37:39 +00009738 if (S.getLangOpts().Bool)
9739 return;
9740 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
9741}
9742
John McCallcc7e5bf2010-05-06 08:58:33 +00009743/// AnalyzeImplicitConversions - Find and report any interesting
9744/// implicit conversions in the given expression. There are a couple
9745/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00009746void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00009747 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00009748 Expr *E = OrigE->IgnoreParenImpCasts();
9749
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00009750 if (E->isTypeDependent() || E->isValueDependent())
9751 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00009752
John McCallcc7e5bf2010-05-06 08:58:33 +00009753 // For conditional operators, we analyze the arguments as if they
9754 // were being fed directly into the output.
9755 if (isa<ConditionalOperator>(E)) {
9756 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00009757 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009758 return;
9759 }
9760
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009761 // Check implicit argument conversions for function calls.
9762 if (CallExpr *Call = dyn_cast<CallExpr>(E))
9763 CheckImplicitArgumentConversions(S, Call, CC);
9764
John McCallcc7e5bf2010-05-06 08:58:33 +00009765 // Go ahead and check any implicit conversions we might have skipped.
9766 // The non-canonical typecheck is just an optimization;
9767 // CheckImplicitConversion will filter out dead implicit conversions.
9768 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00009769 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009770
9771 // Now continue drilling into this expression.
Richard Smithd7bed4d2015-11-22 02:57:17 +00009772
9773 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
9774 // The bound subexpressions in a PseudoObjectExpr are not reachable
9775 // as transitive children.
9776 // FIXME: Use a more uniform representation for this.
9777 for (auto *SE : POE->semantics())
9778 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
9779 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00009780 }
Richard Smithd7bed4d2015-11-22 02:57:17 +00009781
John McCallcc7e5bf2010-05-06 08:58:33 +00009782 // Skip past explicit casts.
9783 if (isa<ExplicitCastExpr>(E)) {
9784 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00009785 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009786 }
9787
John McCalld2a53122010-11-09 23:24:47 +00009788 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9789 // Do a somewhat different check with comparison operators.
9790 if (BO->isComparisonOp())
9791 return AnalyzeComparison(S, BO);
9792
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009793 // And with simple assignments.
9794 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00009795 return AnalyzeAssignment(S, BO);
9796 }
John McCallcc7e5bf2010-05-06 08:58:33 +00009797
9798 // These break the otherwise-useful invariant below. Fortunately,
9799 // we don't really need to recurse into them, because any internal
9800 // expressions should have been analyzed already when they were
9801 // built into statements.
9802 if (isa<StmtExpr>(E)) return;
9803
9804 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00009805 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00009806
9807 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00009808 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00009809 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00009810 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Benjamin Kramer642f1732015-07-02 21:03:14 +00009811 for (Stmt *SubStmt : E->children()) {
9812 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00009813 if (!ChildExpr)
9814 continue;
9815
Richard Trieu955231d2014-01-25 01:10:35 +00009816 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00009817 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00009818 // Ignore checking string literals that are in logical and operators.
9819 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00009820 continue;
9821 AnalyzeImplicitConversions(S, ChildExpr, CC);
9822 }
Richard Trieu791b86e2014-11-19 06:08:18 +00009823
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009824 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +00009825 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
9826 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00009827 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +00009828
9829 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
9830 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00009831 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009832 }
Richard Trieu791b86e2014-11-19 06:08:18 +00009833
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009834 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
9835 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +00009836 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009837}
9838
9839} // end anonymous namespace
9840
Anastasia Stulova0df4ac32016-11-14 17:39:58 +00009841/// Diagnose integer type and any valid implicit convertion to it.
9842static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
9843 // Taking into account implicit conversions,
9844 // allow any integer.
9845 if (!E->getType()->isIntegerType()) {
9846 S.Diag(E->getLocStart(),
9847 diag::err_opencl_enqueue_kernel_invalid_local_size_type);
9848 return true;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00009849 }
Anastasia Stulova0df4ac32016-11-14 17:39:58 +00009850 // Potentially emit standard warnings for implicit conversions if enabled
9851 // using -Wconversion.
9852 CheckImplicitConversion(S, E, IntT, E->getLocStart());
9853 return false;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00009854}
9855
Richard Trieuc1888e02014-06-28 23:25:37 +00009856// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
9857// Returns true when emitting a warning about taking the address of a reference.
9858static bool CheckForReference(Sema &SemaRef, const Expr *E,
Benjamin Kramer7320b992016-06-15 14:20:56 +00009859 const PartialDiagnostic &PD) {
Richard Trieuc1888e02014-06-28 23:25:37 +00009860 E = E->IgnoreParenImpCasts();
9861
9862 const FunctionDecl *FD = nullptr;
9863
9864 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9865 if (!DRE->getDecl()->getType()->isReferenceType())
9866 return false;
9867 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9868 if (!M->getMemberDecl()->getType()->isReferenceType())
9869 return false;
9870 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +00009871 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +00009872 return false;
9873 FD = Call->getDirectCallee();
9874 } else {
9875 return false;
9876 }
9877
9878 SemaRef.Diag(E->getExprLoc(), PD);
9879
9880 // If possible, point to location of function.
9881 if (FD) {
9882 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
9883 }
9884
9885 return true;
9886}
9887
Richard Trieu4cbff5c2014-08-08 22:41:43 +00009888// Returns true if the SourceLocation is expanded from any macro body.
9889// Returns false if the SourceLocation is invalid, is from not in a macro
9890// expansion, or is from expanded from a top-level macro argument.
9891static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
9892 if (Loc.isInvalid())
9893 return false;
9894
9895 while (Loc.isMacroID()) {
9896 if (SM.isMacroBodyExpansion(Loc))
9897 return true;
9898 Loc = SM.getImmediateMacroCallerLoc(Loc);
9899 }
9900
9901 return false;
9902}
9903
Richard Trieu3bb8b562014-02-26 02:36:06 +00009904/// \brief Diagnose pointers that are always non-null.
9905/// \param E the expression containing the pointer
9906/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
9907/// compared to a null pointer
9908/// \param IsEqual True when the comparison is equal to a null pointer
9909/// \param Range Extra SourceRange to highlight in the diagnostic
9910void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
9911 Expr::NullPointerConstantKind NullKind,
9912 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00009913 if (!E)
9914 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009915
9916 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +00009917 if (E->getExprLoc().isMacroID()) {
9918 const SourceManager &SM = getSourceManager();
9919 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
9920 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +00009921 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +00009922 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00009923 E = E->IgnoreImpCasts();
9924
9925 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
9926
Richard Trieuf7432752014-06-06 21:39:26 +00009927 if (isa<CXXThisExpr>(E)) {
9928 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
9929 : diag::warn_this_bool_conversion;
9930 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
9931 return;
9932 }
9933
Richard Trieu3bb8b562014-02-26 02:36:06 +00009934 bool IsAddressOf = false;
9935
9936 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
9937 if (UO->getOpcode() != UO_AddrOf)
9938 return;
9939 IsAddressOf = true;
9940 E = UO->getSubExpr();
9941 }
9942
Richard Trieuc1888e02014-06-28 23:25:37 +00009943 if (IsAddressOf) {
9944 unsigned DiagID = IsCompare
9945 ? diag::warn_address_of_reference_null_compare
9946 : diag::warn_address_of_reference_bool_conversion;
9947 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
9948 << IsEqual;
9949 if (CheckForReference(*this, E, PD)) {
9950 return;
9951 }
9952 }
9953
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009954 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
9955 bool IsParam = isa<NonNullAttr>(NonnullAttr);
George Burgess IV850269a2015-12-08 22:02:00 +00009956 std::string Str;
9957 llvm::raw_string_ostream S(Str);
9958 E->printPretty(S, nullptr, getPrintingPolicy());
9959 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
9960 : diag::warn_cast_nonnull_to_bool;
9961 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
9962 << E->getSourceRange() << Range << IsEqual;
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009963 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
George Burgess IV850269a2015-12-08 22:02:00 +00009964 };
9965
9966 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
9967 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
9968 if (auto *Callee = Call->getDirectCallee()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009969 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
9970 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +00009971 return;
9972 }
9973 }
9974 }
9975
Richard Trieu3bb8b562014-02-26 02:36:06 +00009976 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +00009977 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009978 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
9979 D = R->getDecl();
9980 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9981 D = M->getMemberDecl();
9982 }
9983
9984 // Weak Decls can be null.
9985 if (!D || D->isWeak())
9986 return;
George Burgess IV850269a2015-12-08 22:02:00 +00009987
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009988 // Check for parameter decl with nonnull attribute
George Burgess IV850269a2015-12-08 22:02:00 +00009989 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
9990 if (getCurFunction() &&
9991 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009992 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
9993 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +00009994 return;
9995 }
9996
9997 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
David Majnemera3debed2016-06-24 05:33:44 +00009998 auto ParamIter = llvm::find(FD->parameters(), PV);
George Burgess IV850269a2015-12-08 22:02:00 +00009999 assert(ParamIter != FD->param_end());
10000 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
10001
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010002 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
10003 if (!NonNull->args_size()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010004 ComplainAboutNonnullParamOrCall(NonNull);
George Burgess IV850269a2015-12-08 22:02:00 +000010005 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010006 }
George Burgess IV850269a2015-12-08 22:02:00 +000010007
10008 for (unsigned ArgNo : NonNull->args()) {
10009 if (ArgNo == ParamNo) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010010 ComplainAboutNonnullParamOrCall(NonNull);
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010011 return;
10012 }
George Burgess IV850269a2015-12-08 22:02:00 +000010013 }
10014 }
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010015 }
10016 }
George Burgess IV850269a2015-12-08 22:02:00 +000010017 }
10018
Richard Trieu3bb8b562014-02-26 02:36:06 +000010019 QualType T = D->getType();
10020 const bool IsArray = T->isArrayType();
10021 const bool IsFunction = T->isFunctionType();
10022
Richard Trieuc1888e02014-06-28 23:25:37 +000010023 // Address of function is used to silence the function warning.
10024 if (IsAddressOf && IsFunction) {
10025 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +000010026 }
10027
10028 // Found nothing.
10029 if (!IsAddressOf && !IsFunction && !IsArray)
10030 return;
10031
10032 // Pretty print the expression for the diagnostic.
10033 std::string Str;
10034 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +000010035 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +000010036
10037 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
10038 : diag::warn_impcast_pointer_to_bool;
Craig Topperfa1340f2015-12-23 05:44:46 +000010039 enum {
10040 AddressOf,
10041 FunctionPointer,
10042 ArrayPointer
10043 } DiagType;
Richard Trieu3bb8b562014-02-26 02:36:06 +000010044 if (IsAddressOf)
10045 DiagType = AddressOf;
10046 else if (IsFunction)
10047 DiagType = FunctionPointer;
10048 else if (IsArray)
10049 DiagType = ArrayPointer;
10050 else
10051 llvm_unreachable("Could not determine diagnostic.");
10052 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
10053 << Range << IsEqual;
10054
10055 if (!IsFunction)
10056 return;
10057
10058 // Suggest '&' to silence the function warning.
10059 Diag(E->getExprLoc(), diag::note_function_warning_silence)
10060 << FixItHint::CreateInsertion(E->getLocStart(), "&");
10061
10062 // Check to see if '()' fixit should be emitted.
10063 QualType ReturnType;
10064 UnresolvedSet<4> NonTemplateOverloads;
10065 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
10066 if (ReturnType.isNull())
10067 return;
10068
10069 if (IsCompare) {
10070 // There are two cases here. If there is null constant, the only suggest
10071 // for a pointer return type. If the null is 0, then suggest if the return
10072 // type is a pointer or an integer type.
10073 if (!ReturnType->isPointerType()) {
10074 if (NullKind == Expr::NPCK_ZeroExpression ||
10075 NullKind == Expr::NPCK_ZeroLiteral) {
10076 if (!ReturnType->isIntegerType())
10077 return;
10078 } else {
10079 return;
10080 }
10081 }
10082 } else { // !IsCompare
10083 // For function to bool, only suggest if the function pointer has bool
10084 // return type.
10085 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
10086 return;
10087 }
10088 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +000010089 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +000010090}
10091
John McCallcc7e5bf2010-05-06 08:58:33 +000010092/// Diagnoses "dangerous" implicit conversions within the given
10093/// expression (which is a full expression). Implements -Wconversion
10094/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +000010095///
10096/// \param CC the "context" location of the implicit conversion, i.e.
10097/// the most location of the syntactic entity requiring the implicit
10098/// conversion
10099void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +000010100 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +000010101 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +000010102 return;
10103
10104 // Don't diagnose for value- or type-dependent expressions.
10105 if (E->isTypeDependent() || E->isValueDependent())
10106 return;
10107
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010108 // Check for array bounds violations in cases where the check isn't triggered
10109 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
10110 // ArraySubscriptExpr is on the RHS of a variable initialization.
10111 CheckArrayAccess(E);
10112
John McCallacf0ee52010-10-08 02:01:28 +000010113 // This is not the right CC for (e.g.) a variable initialization.
10114 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000010115}
10116
Richard Trieu65724892014-11-15 06:37:39 +000010117/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
10118/// Input argument E is a logical expression.
10119void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
10120 ::CheckBoolLikeConversion(*this, E, CC);
10121}
10122
Richard Smith9f7df0c2017-06-26 23:19:32 +000010123/// Diagnose when expression is an integer constant expression and its evaluation
10124/// results in integer overflow
10125void Sema::CheckForIntOverflow (Expr *E) {
10126 // Use a work list to deal with nested struct initializers.
10127 SmallVector<Expr *, 2> Exprs(1, E);
10128
10129 do {
10130 Expr *E = Exprs.pop_back_val();
10131
10132 if (isa<BinaryOperator>(E->IgnoreParenCasts())) {
10133 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
10134 continue;
10135 }
10136
10137 if (auto InitList = dyn_cast<InitListExpr>(E))
10138 Exprs.append(InitList->inits().begin(), InitList->inits().end());
10139
10140 if (isa<ObjCBoxedExpr>(E))
10141 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
10142 } while (!Exprs.empty());
10143}
10144
Richard Smithc406cb72013-01-17 01:17:56 +000010145namespace {
10146/// \brief Visitor for expressions which looks for unsequenced operations on the
10147/// same object.
10148class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +000010149 typedef EvaluatedExprVisitor<SequenceChecker> Base;
10150
Richard Smithc406cb72013-01-17 01:17:56 +000010151 /// \brief A tree of sequenced regions within an expression. Two regions are
10152 /// unsequenced if one is an ancestor or a descendent of the other. When we
10153 /// finish processing an expression with sequencing, such as a comma
10154 /// expression, we fold its tree nodes into its parent, since they are
10155 /// unsequenced with respect to nodes we will visit later.
10156 class SequenceTree {
10157 struct Value {
10158 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
10159 unsigned Parent : 31;
Aaron Ballmanaffa1c32016-07-06 18:33:01 +000010160 unsigned Merged : 1;
Richard Smithc406cb72013-01-17 01:17:56 +000010161 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010162 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +000010163
10164 public:
10165 /// \brief A region within an expression which may be sequenced with respect
10166 /// to some other region.
10167 class Seq {
10168 explicit Seq(unsigned N) : Index(N) {}
10169 unsigned Index;
10170 friend class SequenceTree;
10171 public:
10172 Seq() : Index(0) {}
10173 };
10174
10175 SequenceTree() { Values.push_back(Value(0)); }
10176 Seq root() const { return Seq(0); }
10177
10178 /// \brief Create a new sequence of operations, which is an unsequenced
10179 /// subset of \p Parent. This sequence of operations is sequenced with
10180 /// respect to other children of \p Parent.
10181 Seq allocate(Seq Parent) {
10182 Values.push_back(Value(Parent.Index));
10183 return Seq(Values.size() - 1);
10184 }
10185
10186 /// \brief Merge a sequence of operations into its parent.
10187 void merge(Seq S) {
10188 Values[S.Index].Merged = true;
10189 }
10190
10191 /// \brief Determine whether two operations are unsequenced. This operation
10192 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
10193 /// should have been merged into its parent as appropriate.
10194 bool isUnsequenced(Seq Cur, Seq Old) {
10195 unsigned C = representative(Cur.Index);
10196 unsigned Target = representative(Old.Index);
10197 while (C >= Target) {
10198 if (C == Target)
10199 return true;
10200 C = Values[C].Parent;
10201 }
10202 return false;
10203 }
10204
10205 private:
10206 /// \brief Pick a representative for a sequence.
10207 unsigned representative(unsigned K) {
10208 if (Values[K].Merged)
10209 // Perform path compression as we go.
10210 return Values[K].Parent = representative(Values[K].Parent);
10211 return K;
10212 }
10213 };
10214
10215 /// An object for which we can track unsequenced uses.
10216 typedef NamedDecl *Object;
10217
10218 /// Different flavors of object usage which we track. We only track the
10219 /// least-sequenced usage of each kind.
10220 enum UsageKind {
10221 /// A read of an object. Multiple unsequenced reads are OK.
10222 UK_Use,
10223 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +000010224 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +000010225 UK_ModAsValue,
10226 /// A modification of an object which is not sequenced before the value
10227 /// computation of the expression, such as n++.
10228 UK_ModAsSideEffect,
10229
10230 UK_Count = UK_ModAsSideEffect + 1
10231 };
10232
10233 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +000010234 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +000010235 Expr *Use;
10236 SequenceTree::Seq Seq;
10237 };
10238
10239 struct UsageInfo {
10240 UsageInfo() : Diagnosed(false) {}
10241 Usage Uses[UK_Count];
10242 /// Have we issued a diagnostic for this variable already?
10243 bool Diagnosed;
10244 };
10245 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
10246
10247 Sema &SemaRef;
10248 /// Sequenced regions within the expression.
10249 SequenceTree Tree;
10250 /// Declaration modifications and references which we have seen.
10251 UsageInfoMap UsageMap;
10252 /// The region we are currently within.
10253 SequenceTree::Seq Region;
10254 /// Filled in with declarations which were modified as a side-effect
10255 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010256 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +000010257 /// Expressions to check later. We defer checking these to reduce
10258 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010259 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +000010260
10261 /// RAII object wrapping the visitation of a sequenced subexpression of an
10262 /// expression. At the end of this process, the side-effects of the evaluation
10263 /// become sequenced with respect to the value computation of the result, so
10264 /// we downgrade any UK_ModAsSideEffect within the evaluation to
10265 /// UK_ModAsValue.
10266 struct SequencedSubexpression {
10267 SequencedSubexpression(SequenceChecker &Self)
10268 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
10269 Self.ModAsSideEffect = &ModAsSideEffect;
10270 }
10271 ~SequencedSubexpression() {
David Majnemerf7e36092016-06-23 00:15:04 +000010272 for (auto &M : llvm::reverse(ModAsSideEffect)) {
10273 UsageInfo &U = Self.UsageMap[M.first];
Richard Smithe8efd992014-12-03 01:05:50 +000010274 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
David Majnemerf7e36092016-06-23 00:15:04 +000010275 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
10276 SideEffectUsage = M.second;
Richard Smithc406cb72013-01-17 01:17:56 +000010277 }
10278 Self.ModAsSideEffect = OldModAsSideEffect;
10279 }
10280
10281 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010282 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
10283 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +000010284 };
10285
Richard Smith40238f02013-06-20 22:21:56 +000010286 /// RAII object wrapping the visitation of a subexpression which we might
10287 /// choose to evaluate as a constant. If any subexpression is evaluated and
10288 /// found to be non-constant, this allows us to suppress the evaluation of
10289 /// the outer expression.
10290 class EvaluationTracker {
10291 public:
10292 EvaluationTracker(SequenceChecker &Self)
10293 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
10294 Self.EvalTracker = this;
10295 }
10296 ~EvaluationTracker() {
10297 Self.EvalTracker = Prev;
10298 if (Prev)
10299 Prev->EvalOK &= EvalOK;
10300 }
10301
10302 bool evaluate(const Expr *E, bool &Result) {
10303 if (!EvalOK || E->isValueDependent())
10304 return false;
10305 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
10306 return EvalOK;
10307 }
10308
10309 private:
10310 SequenceChecker &Self;
10311 EvaluationTracker *Prev;
10312 bool EvalOK;
10313 } *EvalTracker;
10314
Richard Smithc406cb72013-01-17 01:17:56 +000010315 /// \brief Find the object which is produced by the specified expression,
10316 /// if any.
10317 Object getObject(Expr *E, bool Mod) const {
10318 E = E->IgnoreParenCasts();
10319 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
10320 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
10321 return getObject(UO->getSubExpr(), Mod);
10322 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10323 if (BO->getOpcode() == BO_Comma)
10324 return getObject(BO->getRHS(), Mod);
10325 if (Mod && BO->isAssignmentOp())
10326 return getObject(BO->getLHS(), Mod);
10327 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
10328 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
10329 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
10330 return ME->getMemberDecl();
10331 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10332 // FIXME: If this is a reference, map through to its value.
10333 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +000010334 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +000010335 }
10336
10337 /// \brief Note that an object was modified or used by an expression.
10338 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
10339 Usage &U = UI.Uses[UK];
10340 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
10341 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
10342 ModAsSideEffect->push_back(std::make_pair(O, U));
10343 U.Use = Ref;
10344 U.Seq = Region;
10345 }
10346 }
10347 /// \brief Check whether a modification or use conflicts with a prior usage.
10348 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
10349 bool IsModMod) {
10350 if (UI.Diagnosed)
10351 return;
10352
10353 const Usage &U = UI.Uses[OtherKind];
10354 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
10355 return;
10356
10357 Expr *Mod = U.Use;
10358 Expr *ModOrUse = Ref;
10359 if (OtherKind == UK_Use)
10360 std::swap(Mod, ModOrUse);
10361
10362 SemaRef.Diag(Mod->getExprLoc(),
10363 IsModMod ? diag::warn_unsequenced_mod_mod
10364 : diag::warn_unsequenced_mod_use)
10365 << O << SourceRange(ModOrUse->getExprLoc());
10366 UI.Diagnosed = true;
10367 }
10368
10369 void notePreUse(Object O, Expr *Use) {
10370 UsageInfo &U = UsageMap[O];
10371 // Uses conflict with other modifications.
10372 checkUsage(O, U, Use, UK_ModAsValue, false);
10373 }
10374 void notePostUse(Object O, Expr *Use) {
10375 UsageInfo &U = UsageMap[O];
10376 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
10377 addUsage(U, O, Use, UK_Use);
10378 }
10379
10380 void notePreMod(Object O, Expr *Mod) {
10381 UsageInfo &U = UsageMap[O];
10382 // Modifications conflict with other modifications and with uses.
10383 checkUsage(O, U, Mod, UK_ModAsValue, true);
10384 checkUsage(O, U, Mod, UK_Use, false);
10385 }
10386 void notePostMod(Object O, Expr *Use, UsageKind UK) {
10387 UsageInfo &U = UsageMap[O];
10388 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
10389 addUsage(U, O, Use, UK);
10390 }
10391
10392public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010393 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +000010394 : Base(S.Context), SemaRef(S), Region(Tree.root()),
10395 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +000010396 Visit(E);
10397 }
10398
10399 void VisitStmt(Stmt *S) {
10400 // Skip all statements which aren't expressions for now.
10401 }
10402
10403 void VisitExpr(Expr *E) {
10404 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +000010405 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +000010406 }
10407
10408 void VisitCastExpr(CastExpr *E) {
10409 Object O = Object();
10410 if (E->getCastKind() == CK_LValueToRValue)
10411 O = getObject(E->getSubExpr(), false);
10412
10413 if (O)
10414 notePreUse(O, E);
10415 VisitExpr(E);
10416 if (O)
10417 notePostUse(O, E);
10418 }
10419
10420 void VisitBinComma(BinaryOperator *BO) {
10421 // C++11 [expr.comma]p1:
10422 // Every value computation and side effect associated with the left
10423 // expression is sequenced before every value computation and side
10424 // effect associated with the right expression.
10425 SequenceTree::Seq LHS = Tree.allocate(Region);
10426 SequenceTree::Seq RHS = Tree.allocate(Region);
10427 SequenceTree::Seq OldRegion = Region;
10428
10429 {
10430 SequencedSubexpression SeqLHS(*this);
10431 Region = LHS;
10432 Visit(BO->getLHS());
10433 }
10434
10435 Region = RHS;
10436 Visit(BO->getRHS());
10437
10438 Region = OldRegion;
10439
10440 // Forget that LHS and RHS are sequenced. They are both unsequenced
10441 // with respect to other stuff.
10442 Tree.merge(LHS);
10443 Tree.merge(RHS);
10444 }
10445
10446 void VisitBinAssign(BinaryOperator *BO) {
10447 // The modification is sequenced after the value computation of the LHS
10448 // and RHS, so check it before inspecting the operands and update the
10449 // map afterwards.
10450 Object O = getObject(BO->getLHS(), true);
10451 if (!O)
10452 return VisitExpr(BO);
10453
10454 notePreMod(O, BO);
10455
10456 // C++11 [expr.ass]p7:
10457 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
10458 // only once.
10459 //
10460 // Therefore, for a compound assignment operator, O is considered used
10461 // everywhere except within the evaluation of E1 itself.
10462 if (isa<CompoundAssignOperator>(BO))
10463 notePreUse(O, BO);
10464
10465 Visit(BO->getLHS());
10466
10467 if (isa<CompoundAssignOperator>(BO))
10468 notePostUse(O, BO);
10469
10470 Visit(BO->getRHS());
10471
Richard Smith83e37bee2013-06-26 23:16:51 +000010472 // C++11 [expr.ass]p1:
10473 // the assignment is sequenced [...] before the value computation of the
10474 // assignment expression.
10475 // C11 6.5.16/3 has no such rule.
10476 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10477 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000010478 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010479
Richard Smithc406cb72013-01-17 01:17:56 +000010480 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
10481 VisitBinAssign(CAO);
10482 }
10483
10484 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10485 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10486 void VisitUnaryPreIncDec(UnaryOperator *UO) {
10487 Object O = getObject(UO->getSubExpr(), true);
10488 if (!O)
10489 return VisitExpr(UO);
10490
10491 notePreMod(O, UO);
10492 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +000010493 // C++11 [expr.pre.incr]p1:
10494 // the expression ++x is equivalent to x+=1
10495 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10496 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000010497 }
10498
10499 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10500 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10501 void VisitUnaryPostIncDec(UnaryOperator *UO) {
10502 Object O = getObject(UO->getSubExpr(), true);
10503 if (!O)
10504 return VisitExpr(UO);
10505
10506 notePreMod(O, UO);
10507 Visit(UO->getSubExpr());
10508 notePostMod(O, UO, UK_ModAsSideEffect);
10509 }
10510
10511 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
10512 void VisitBinLOr(BinaryOperator *BO) {
10513 // The side-effects of the LHS of an '&&' are sequenced before the
10514 // value computation of the RHS, and hence before the value computation
10515 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
10516 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +000010517 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000010518 {
10519 SequencedSubexpression Sequenced(*this);
10520 Visit(BO->getLHS());
10521 }
10522
10523 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010524 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000010525 if (!Result)
10526 Visit(BO->getRHS());
10527 } else {
10528 // Check for unsequenced operations in the RHS, treating it as an
10529 // entirely separate evaluation.
10530 //
10531 // FIXME: If there are operations in the RHS which are unsequenced
10532 // with respect to operations outside the RHS, and those operations
10533 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +000010534 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000010535 }
Richard Smithc406cb72013-01-17 01:17:56 +000010536 }
10537 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +000010538 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000010539 {
10540 SequencedSubexpression Sequenced(*this);
10541 Visit(BO->getLHS());
10542 }
10543
10544 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010545 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000010546 if (Result)
10547 Visit(BO->getRHS());
10548 } else {
Richard Smithd33f5202013-01-17 23:18:09 +000010549 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000010550 }
Richard Smithc406cb72013-01-17 01:17:56 +000010551 }
10552
10553 // Only visit the condition, unless we can be sure which subexpression will
10554 // be chosen.
10555 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +000010556 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +000010557 {
10558 SequencedSubexpression Sequenced(*this);
10559 Visit(CO->getCond());
10560 }
Richard Smithc406cb72013-01-17 01:17:56 +000010561
10562 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010563 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +000010564 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000010565 else {
Richard Smithd33f5202013-01-17 23:18:09 +000010566 WorkList.push_back(CO->getTrueExpr());
10567 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000010568 }
Richard Smithc406cb72013-01-17 01:17:56 +000010569 }
10570
Richard Smithe3dbfe02013-06-30 10:40:20 +000010571 void VisitCallExpr(CallExpr *CE) {
10572 // C++11 [intro.execution]p15:
10573 // When calling a function [...], every value computation and side effect
10574 // associated with any argument expression, or with the postfix expression
10575 // designating the called function, is sequenced before execution of every
10576 // expression or statement in the body of the function [and thus before
10577 // the value computation of its result].
10578 SequencedSubexpression Sequenced(*this);
10579 Base::VisitCallExpr(CE);
10580
10581 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
10582 }
10583
Richard Smithc406cb72013-01-17 01:17:56 +000010584 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +000010585 // This is a call, so all subexpressions are sequenced before the result.
10586 SequencedSubexpression Sequenced(*this);
10587
Richard Smithc406cb72013-01-17 01:17:56 +000010588 if (!CCE->isListInitialization())
10589 return VisitExpr(CCE);
10590
10591 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010592 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000010593 SequenceTree::Seq Parent = Region;
10594 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
10595 E = CCE->arg_end();
10596 I != E; ++I) {
10597 Region = Tree.allocate(Parent);
10598 Elts.push_back(Region);
10599 Visit(*I);
10600 }
10601
10602 // Forget that the initializers are sequenced.
10603 Region = Parent;
10604 for (unsigned I = 0; I < Elts.size(); ++I)
10605 Tree.merge(Elts[I]);
10606 }
10607
10608 void VisitInitListExpr(InitListExpr *ILE) {
10609 if (!SemaRef.getLangOpts().CPlusPlus11)
10610 return VisitExpr(ILE);
10611
10612 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010613 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000010614 SequenceTree::Seq Parent = Region;
10615 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
10616 Expr *E = ILE->getInit(I);
10617 if (!E) continue;
10618 Region = Tree.allocate(Parent);
10619 Elts.push_back(Region);
10620 Visit(E);
10621 }
10622
10623 // Forget that the initializers are sequenced.
10624 Region = Parent;
10625 for (unsigned I = 0; I < Elts.size(); ++I)
10626 Tree.merge(Elts[I]);
10627 }
10628};
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010629} // end anonymous namespace
Richard Smithc406cb72013-01-17 01:17:56 +000010630
10631void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010632 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +000010633 WorkList.push_back(E);
10634 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +000010635 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +000010636 SequenceChecker(*this, Item, WorkList);
10637 }
Richard Smithc406cb72013-01-17 01:17:56 +000010638}
10639
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010640void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
10641 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +000010642 CheckImplicitConversions(E, CheckLoc);
Richard Trieu71d74d42016-08-05 21:02:34 +000010643 if (!E->isInstantiationDependent())
10644 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010645 if (!IsConstexpr && !E->isValueDependent())
Richard Smith9f7df0c2017-06-26 23:19:32 +000010646 CheckForIntOverflow(E);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000010647 DiagnoseMisalignedMembers();
Richard Smithc406cb72013-01-17 01:17:56 +000010648}
10649
John McCall1f425642010-11-11 03:21:53 +000010650void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
10651 FieldDecl *BitField,
10652 Expr *Init) {
10653 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
10654}
10655
David Majnemer61a5bbf2015-04-07 22:08:51 +000010656static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
10657 SourceLocation Loc) {
10658 if (!PType->isVariablyModifiedType())
10659 return;
10660 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
10661 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
10662 return;
10663 }
David Majnemerdf8f73f2015-04-09 19:53:25 +000010664 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
10665 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
10666 return;
10667 }
David Majnemer61a5bbf2015-04-07 22:08:51 +000010668 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
10669 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
10670 return;
10671 }
10672
10673 const ArrayType *AT = S.Context.getAsArrayType(PType);
10674 if (!AT)
10675 return;
10676
10677 if (AT->getSizeModifier() != ArrayType::Star) {
10678 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
10679 return;
10680 }
10681
10682 S.Diag(Loc, diag::err_array_star_in_function_definition);
10683}
10684
Mike Stump0c2ec772010-01-21 03:59:47 +000010685/// CheckParmsForFunctionDef - Check that the parameters of the given
10686/// function are appropriate for the definition of a function. This
10687/// takes care of any checks that cannot be performed on the
10688/// declaration itself, e.g., that the types of each of the function
10689/// parameters are complete.
David Majnemer59f77922016-06-24 04:05:48 +000010690bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
Douglas Gregorb524d902010-11-01 18:37:59 +000010691 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010692 bool HasInvalidParm = false;
David Majnemer59f77922016-06-24 04:05:48 +000010693 for (ParmVarDecl *Param : Parameters) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010694 // C99 6.7.5.3p4: the parameters in a parameter type list in a
10695 // function declarator that is part of a function definition of
10696 // that function shall not have incomplete type.
10697 //
10698 // This is also C++ [dcl.fct]p6.
10699 if (!Param->isInvalidDecl() &&
10700 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000010701 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010702 Param->setInvalidDecl();
10703 HasInvalidParm = true;
10704 }
10705
10706 // C99 6.9.1p5: If the declarator includes a parameter type list, the
10707 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +000010708 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +000010709 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +000010710 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +000010711 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +000010712 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +000010713
10714 // C99 6.7.5.3p12:
10715 // If the function declarator is not part of a definition of that
10716 // function, parameters may have incomplete type and may use the [*]
10717 // notation in their sequences of declarator specifiers to specify
10718 // variable length array types.
10719 QualType PType = Param->getOriginalType();
David Majnemer61a5bbf2015-04-07 22:08:51 +000010720 // FIXME: This diagnostic should point the '[*]' if source-location
10721 // information is added for it.
10722 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000010723
10724 // MSVC destroys objects passed by value in the callee. Therefore a
10725 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +000010726 // object's destructor. However, we don't perform any direct access check
10727 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +000010728 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
10729 .getCXXABI()
10730 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +000010731 if (!Param->isInvalidDecl()) {
10732 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
10733 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
10734 if (!ClassDecl->isInvalidDecl() &&
10735 !ClassDecl->hasIrrelevantDestructor() &&
10736 !ClassDecl->isDependentContext()) {
10737 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
10738 MarkFunctionReferenced(Param->getLocation(), Destructor);
10739 DiagnoseUseOfDecl(Destructor, Param->getLocation());
10740 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +000010741 }
10742 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000010743 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010744
10745 // Parameters with the pass_object_size attribute only need to be marked
10746 // constant at function definitions. Because we lack information about
10747 // whether we're on a declaration or definition when we're instantiating the
10748 // attribute, we need to check for constness here.
10749 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
10750 if (!Param->getType().isConstQualified())
10751 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
10752 << Attr->getSpelling() << 1;
Mike Stump0c2ec772010-01-21 03:59:47 +000010753 }
10754
10755 return HasInvalidParm;
10756}
John McCall2b5c1b22010-08-12 21:44:57 +000010757
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000010758/// A helper function to get the alignment of a Decl referred to by DeclRefExpr
10759/// or MemberExpr.
10760static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
10761 ASTContext &Context) {
10762 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
10763 return Context.getDeclAlign(DRE->getDecl());
10764
10765 if (const auto *ME = dyn_cast<MemberExpr>(E))
10766 return Context.getDeclAlign(ME->getMemberDecl());
10767
10768 return TypeAlign;
10769}
10770
John McCall2b5c1b22010-08-12 21:44:57 +000010771/// CheckCastAlign - Implements -Wcast-align, which warns when a
10772/// pointer cast increases the alignment requirements.
10773void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
10774 // This is actually a lot of work to potentially be doing on every
10775 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000010776 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +000010777 return;
10778
10779 // Ignore dependent types.
10780 if (T->isDependentType() || Op->getType()->isDependentType())
10781 return;
10782
10783 // Require that the destination be a pointer type.
10784 const PointerType *DestPtr = T->getAs<PointerType>();
10785 if (!DestPtr) return;
10786
10787 // If the destination has alignment 1, we're done.
10788 QualType DestPointee = DestPtr->getPointeeType();
10789 if (DestPointee->isIncompleteType()) return;
10790 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
10791 if (DestAlign.isOne()) return;
10792
10793 // Require that the source be a pointer type.
10794 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
10795 if (!SrcPtr) return;
10796 QualType SrcPointee = SrcPtr->getPointeeType();
10797
10798 // Whitelist casts from cv void*. We already implicitly
10799 // whitelisted casts to cv void*, since they have alignment 1.
10800 // Also whitelist casts involving incomplete types, which implicitly
10801 // includes 'void'.
10802 if (SrcPointee->isIncompleteType()) return;
10803
10804 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000010805
10806 if (auto *CE = dyn_cast<CastExpr>(Op)) {
10807 if (CE->getCastKind() == CK_ArrayToPointerDecay)
10808 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
10809 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
10810 if (UO->getOpcode() == UO_AddrOf)
10811 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
10812 }
10813
John McCall2b5c1b22010-08-12 21:44:57 +000010814 if (SrcAlign >= DestAlign) return;
10815
10816 Diag(TRange.getBegin(), diag::warn_cast_align)
10817 << Op->getType() << T
10818 << static_cast<unsigned>(SrcAlign.getQuantity())
10819 << static_cast<unsigned>(DestAlign.getQuantity())
10820 << TRange << Op->getSourceRange();
10821}
10822
Chandler Carruth28389f02011-08-05 09:10:50 +000010823/// \brief Check whether this array fits the idiom of a size-one tail padded
10824/// array member of a struct.
10825///
10826/// We avoid emitting out-of-bounds access warnings for such arrays as they are
10827/// commonly used to emulate flexible arrays in C89 code.
Benjamin Kramer7320b992016-06-15 14:20:56 +000010828static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
Chandler Carruth28389f02011-08-05 09:10:50 +000010829 const NamedDecl *ND) {
10830 if (Size != 1 || !ND) return false;
10831
10832 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
10833 if (!FD) return false;
10834
10835 // Don't consider sizes resulting from macro expansions or template argument
10836 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +000010837
10838 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000010839 while (TInfo) {
10840 TypeLoc TL = TInfo->getTypeLoc();
10841 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +000010842 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
10843 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000010844 TInfo = TDL->getTypeSourceInfo();
10845 continue;
10846 }
David Blaikie6adc78e2013-02-18 22:06:02 +000010847 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
10848 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +000010849 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
10850 return false;
10851 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +000010852 break;
Sean Callanan06a48a62012-05-04 18:22:53 +000010853 }
Chandler Carruth28389f02011-08-05 09:10:50 +000010854
10855 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +000010856 if (!RD) return false;
10857 if (RD->isUnion()) return false;
10858 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
10859 if (!CRD->isStandardLayout()) return false;
10860 }
Chandler Carruth28389f02011-08-05 09:10:50 +000010861
Benjamin Kramer8c543672011-08-06 03:04:42 +000010862 // See if this is the last field decl in the record.
10863 const Decl *D = FD;
10864 while ((D = D->getNextDeclInContext()))
10865 if (isa<FieldDecl>(D))
10866 return false;
10867 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +000010868}
10869
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010870void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010871 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +000010872 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010873 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010874 if (IndexExpr->isValueDependent())
10875 return;
10876
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000010877 const Type *EffectiveType =
10878 BaseExpr->getType()->getPointeeOrArrayElementType();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010879 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010880 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010881 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010882 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +000010883 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +000010884
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010885 llvm::APSInt index;
Richard Smith0c6124b2015-12-03 01:36:22 +000010886 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
Ted Kremenek64699be2011-02-16 01:57:07 +000010887 return;
Richard Smith13f67182011-12-16 19:31:14 +000010888 if (IndexNegated)
10889 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +000010890
Craig Topperc3ec1492014-05-26 06:22:03 +000010891 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +000010892 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
10893 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +000010894 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +000010895 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +000010896
Ted Kremeneke4b316c2011-02-23 23:06:04 +000010897 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000010898 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +000010899 if (!size.isStrictlyPositive())
10900 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010901
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000010902 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
Nico Weber7c299802011-09-17 22:59:41 +000010903 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010904 // Make sure we're comparing apples to apples when comparing index to size
10905 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
10906 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +000010907 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +000010908 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010909 if (ptrarith_typesize != array_typesize) {
10910 // There's a cast to a different size type involved
10911 uint64_t ratio = array_typesize / ptrarith_typesize;
10912 // TODO: Be smarter about handling cases where array_typesize is not a
10913 // multiple of ptrarith_typesize
10914 if (ptrarith_typesize * ratio == array_typesize)
10915 size *= llvm::APInt(size.getBitWidth(), ratio);
10916 }
10917 }
10918
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010919 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010920 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000010921 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010922 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000010923
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010924 // For array subscripting the index must be less than size, but for pointer
10925 // arithmetic also allow the index (offset) to be equal to size since
10926 // computing the next address after the end of the array is legal and
10927 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010928 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +000010929 return;
10930
10931 // Also don't warn for arrays of size 1 which are members of some
10932 // structure. These are often used to approximate flexible arrays in C89
10933 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010934 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +000010935 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010936
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010937 // Suppress the warning if the subscript expression (as identified by the
10938 // ']' location) and the index expression are both from macro expansions
10939 // within a system header.
10940 if (ASE) {
10941 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
10942 ASE->getRBracketLoc());
10943 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
10944 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
10945 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +000010946 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010947 return;
10948 }
10949 }
10950
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010951 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010952 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010953 DiagID = diag::warn_array_index_exceeds_bounds;
10954
10955 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
10956 PDiag(DiagID) << index.toString(10, true)
10957 << size.toString(10, true)
10958 << (unsigned)size.getLimitedValue(~0U)
10959 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010960 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010961 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010962 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010963 DiagID = diag::warn_ptr_arith_precedes_bounds;
10964 if (index.isNegative()) index = -index;
10965 }
10966
10967 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
10968 PDiag(DiagID) << index.toString(10, true)
10969 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +000010970 }
Chandler Carruth1af88f12011-02-17 21:10:52 +000010971
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000010972 if (!ND) {
10973 // Try harder to find a NamedDecl to point at in the note.
10974 while (const ArraySubscriptExpr *ASE =
10975 dyn_cast<ArraySubscriptExpr>(BaseExpr))
10976 BaseExpr = ASE->getBase()->IgnoreParenCasts();
10977 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
10978 ND = dyn_cast<NamedDecl>(DRE->getDecl());
10979 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
10980 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
10981 }
10982
Chandler Carruth1af88f12011-02-17 21:10:52 +000010983 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010984 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
10985 PDiag(diag::note_array_index_out_of_bounds)
10986 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +000010987}
10988
Ted Kremenekdf26df72011-03-01 18:41:00 +000010989void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010990 int AllowOnePastEnd = 0;
10991 while (expr) {
10992 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +000010993 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010994 case Stmt::ArraySubscriptExprClass: {
10995 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010996 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010997 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +000010998 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010999 }
Alexey Bataev1a3320e2015-08-25 14:24:04 +000011000 case Stmt::OMPArraySectionExprClass: {
11001 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
11002 if (ASE->getLowerBound())
11003 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
11004 /*ASE=*/nullptr, AllowOnePastEnd > 0);
11005 return;
11006 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011007 case Stmt::UnaryOperatorClass: {
11008 // Only unwrap the * and & unary operators
11009 const UnaryOperator *UO = cast<UnaryOperator>(expr);
11010 expr = UO->getSubExpr();
11011 switch (UO->getOpcode()) {
11012 case UO_AddrOf:
11013 AllowOnePastEnd++;
11014 break;
11015 case UO_Deref:
11016 AllowOnePastEnd--;
11017 break;
11018 default:
11019 return;
11020 }
11021 break;
11022 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000011023 case Stmt::ConditionalOperatorClass: {
11024 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
11025 if (const Expr *lhs = cond->getLHS())
11026 CheckArrayAccess(lhs);
11027 if (const Expr *rhs = cond->getRHS())
11028 CheckArrayAccess(rhs);
11029 return;
11030 }
Daniel Marjamaki20a209e2017-02-28 14:53:50 +000011031 case Stmt::CXXOperatorCallExprClass: {
11032 const auto *OCE = cast<CXXOperatorCallExpr>(expr);
11033 for (const auto *Arg : OCE->arguments())
11034 CheckArrayAccess(Arg);
11035 return;
11036 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000011037 default:
11038 return;
11039 }
Peter Collingbourne91147592011-04-15 00:35:48 +000011040 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000011041}
John McCall31168b02011-06-15 23:02:42 +000011042
11043//===--- CHECK: Objective-C retain cycles ----------------------------------//
11044
11045namespace {
11046 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +000011047 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +000011048 VarDecl *Variable;
11049 SourceRange Range;
11050 SourceLocation Loc;
11051 bool Indirect;
11052
11053 void setLocsFrom(Expr *e) {
11054 Loc = e->getExprLoc();
11055 Range = e->getSourceRange();
11056 }
11057 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011058} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +000011059
11060/// Consider whether capturing the given variable can possibly lead to
11061/// a retain cycle.
11062static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +000011063 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +000011064 // lifetime. In MRR, it's captured strongly if the variable is
11065 // __block and has an appropriate type.
11066 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
11067 return false;
11068
11069 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000011070 if (ref)
11071 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +000011072 return true;
11073}
11074
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011075static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +000011076 while (true) {
11077 e = e->IgnoreParens();
11078 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
11079 switch (cast->getCastKind()) {
11080 case CK_BitCast:
11081 case CK_LValueBitCast:
11082 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +000011083 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +000011084 e = cast->getSubExpr();
11085 continue;
11086
John McCall31168b02011-06-15 23:02:42 +000011087 default:
11088 return false;
11089 }
11090 }
11091
11092 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
11093 ObjCIvarDecl *ivar = ref->getDecl();
11094 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
11095 return false;
11096
11097 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011098 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +000011099 return false;
11100
11101 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
11102 owner.Indirect = true;
11103 return true;
11104 }
11105
11106 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
11107 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
11108 if (!var) return false;
11109 return considerVariable(var, ref, owner);
11110 }
11111
John McCall31168b02011-06-15 23:02:42 +000011112 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
11113 if (member->isArrow()) return false;
11114
11115 // Don't count this as an indirect ownership.
11116 e = member->getBase();
11117 continue;
11118 }
11119
John McCallfe96e0b2011-11-06 09:01:30 +000011120 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
11121 // Only pay attention to pseudo-objects on property references.
11122 ObjCPropertyRefExpr *pre
11123 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
11124 ->IgnoreParens());
11125 if (!pre) return false;
11126 if (pre->isImplicitProperty()) return false;
11127 ObjCPropertyDecl *property = pre->getExplicitProperty();
11128 if (!property->isRetaining() &&
11129 !(property->getPropertyIvarDecl() &&
11130 property->getPropertyIvarDecl()->getType()
11131 .getObjCLifetime() == Qualifiers::OCL_Strong))
11132 return false;
11133
11134 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011135 if (pre->isSuperReceiver()) {
11136 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
11137 if (!owner.Variable)
11138 return false;
11139 owner.Loc = pre->getLocation();
11140 owner.Range = pre->getSourceRange();
11141 return true;
11142 }
John McCallfe96e0b2011-11-06 09:01:30 +000011143 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
11144 ->getSourceExpr());
11145 continue;
11146 }
11147
John McCall31168b02011-06-15 23:02:42 +000011148 // Array ivars?
11149
11150 return false;
11151 }
11152}
11153
11154namespace {
11155 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
11156 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
11157 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000011158 Context(Context), Variable(variable), Capturer(nullptr),
11159 VarWillBeReased(false) {}
11160 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +000011161 VarDecl *Variable;
11162 Expr *Capturer;
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000011163 bool VarWillBeReased;
John McCall31168b02011-06-15 23:02:42 +000011164
11165 void VisitDeclRefExpr(DeclRefExpr *ref) {
11166 if (ref->getDecl() == Variable && !Capturer)
11167 Capturer = ref;
11168 }
11169
John McCall31168b02011-06-15 23:02:42 +000011170 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
11171 if (Capturer) return;
11172 Visit(ref->getBase());
11173 if (Capturer && ref->isFreeIvar())
11174 Capturer = ref;
11175 }
11176
11177 void VisitBlockExpr(BlockExpr *block) {
11178 // Look inside nested blocks
11179 if (block->getBlockDecl()->capturesVariable(Variable))
11180 Visit(block->getBlockDecl()->getBody());
11181 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +000011182
11183 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
11184 if (Capturer) return;
11185 if (OVE->getSourceExpr())
11186 Visit(OVE->getSourceExpr());
11187 }
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000011188 void VisitBinaryOperator(BinaryOperator *BinOp) {
11189 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
11190 return;
11191 Expr *LHS = BinOp->getLHS();
11192 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
11193 if (DRE->getDecl() != Variable)
11194 return;
11195 if (Expr *RHS = BinOp->getRHS()) {
11196 RHS = RHS->IgnoreParenCasts();
11197 llvm::APSInt Value;
11198 VarWillBeReased =
11199 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
11200 }
11201 }
11202 }
John McCall31168b02011-06-15 23:02:42 +000011203 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011204} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +000011205
11206/// Check whether the given argument is a block which captures a
11207/// variable.
11208static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
11209 assert(owner.Variable && owner.Loc.isValid());
11210
11211 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +000011212
11213 // Look through [^{...} copy] and Block_copy(^{...}).
11214 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
11215 Selector Cmd = ME->getSelector();
11216 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
11217 e = ME->getInstanceReceiver();
11218 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +000011219 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +000011220 e = e->IgnoreParenCasts();
11221 }
11222 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
11223 if (CE->getNumArgs() == 1) {
11224 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +000011225 if (Fn) {
11226 const IdentifierInfo *FnI = Fn->getIdentifier();
11227 if (FnI && FnI->isStr("_Block_copy")) {
11228 e = CE->getArg(0)->IgnoreParenCasts();
11229 }
11230 }
Jordan Rose67e887c2012-09-17 17:54:30 +000011231 }
11232 }
11233
John McCall31168b02011-06-15 23:02:42 +000011234 BlockExpr *block = dyn_cast<BlockExpr>(e);
11235 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +000011236 return nullptr;
John McCall31168b02011-06-15 23:02:42 +000011237
11238 FindCaptureVisitor visitor(S.Context, owner.Variable);
11239 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000011240 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +000011241}
11242
11243static void diagnoseRetainCycle(Sema &S, Expr *capturer,
11244 RetainCycleOwner &owner) {
11245 assert(capturer);
11246 assert(owner.Variable && owner.Loc.isValid());
11247
11248 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
11249 << owner.Variable << capturer->getSourceRange();
11250 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
11251 << owner.Indirect << owner.Range;
11252}
11253
11254/// Check for a keyword selector that starts with the word 'add' or
11255/// 'set'.
11256static bool isSetterLikeSelector(Selector sel) {
11257 if (sel.isUnarySelector()) return false;
11258
Chris Lattner0e62c1c2011-07-23 10:55:15 +000011259 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +000011260 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +000011261 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +000011262 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +000011263 else if (str.startswith("add")) {
11264 // Specially whitelist 'addOperationWithBlock:'.
11265 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
11266 return false;
11267 str = str.substr(3);
11268 }
John McCall31168b02011-06-15 23:02:42 +000011269 else
11270 return false;
11271
11272 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +000011273 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +000011274}
11275
Benjamin Kramer3a743452015-03-09 15:03:32 +000011276static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
11277 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011278 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
11279 Message->getReceiverInterface(),
11280 NSAPI::ClassId_NSMutableArray);
11281 if (!IsMutableArray) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011282 return None;
11283 }
11284
11285 Selector Sel = Message->getSelector();
11286
11287 Optional<NSAPI::NSArrayMethodKind> MKOpt =
11288 S.NSAPIObj->getNSArrayMethodKind(Sel);
11289 if (!MKOpt) {
11290 return None;
11291 }
11292
11293 NSAPI::NSArrayMethodKind MK = *MKOpt;
11294
11295 switch (MK) {
11296 case NSAPI::NSMutableArr_addObject:
11297 case NSAPI::NSMutableArr_insertObjectAtIndex:
11298 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
11299 return 0;
11300 case NSAPI::NSMutableArr_replaceObjectAtIndex:
11301 return 1;
11302
11303 default:
11304 return None;
11305 }
11306
11307 return None;
11308}
11309
11310static
11311Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
11312 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011313 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
11314 Message->getReceiverInterface(),
11315 NSAPI::ClassId_NSMutableDictionary);
11316 if (!IsMutableDictionary) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011317 return None;
11318 }
11319
11320 Selector Sel = Message->getSelector();
11321
11322 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
11323 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
11324 if (!MKOpt) {
11325 return None;
11326 }
11327
11328 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
11329
11330 switch (MK) {
11331 case NSAPI::NSMutableDict_setObjectForKey:
11332 case NSAPI::NSMutableDict_setValueForKey:
11333 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
11334 return 0;
11335
11336 default:
11337 return None;
11338 }
11339
11340 return None;
11341}
11342
11343static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011344 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
11345 Message->getReceiverInterface(),
11346 NSAPI::ClassId_NSMutableSet);
Alex Denisove1d882c2015-03-04 17:55:52 +000011347
Alex Denisov5dfac812015-08-06 04:51:14 +000011348 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
11349 Message->getReceiverInterface(),
11350 NSAPI::ClassId_NSMutableOrderedSet);
11351 if (!IsMutableSet && !IsMutableOrderedSet) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011352 return None;
11353 }
11354
11355 Selector Sel = Message->getSelector();
11356
11357 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
11358 if (!MKOpt) {
11359 return None;
11360 }
11361
11362 NSAPI::NSSetMethodKind MK = *MKOpt;
11363
11364 switch (MK) {
11365 case NSAPI::NSMutableSet_addObject:
11366 case NSAPI::NSOrderedSet_setObjectAtIndex:
11367 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
11368 case NSAPI::NSOrderedSet_insertObjectAtIndex:
11369 return 0;
11370 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
11371 return 1;
11372 }
11373
11374 return None;
11375}
11376
11377void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
11378 if (!Message->isInstanceMessage()) {
11379 return;
11380 }
11381
11382 Optional<int> ArgOpt;
11383
11384 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
11385 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
11386 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
11387 return;
11388 }
11389
11390 int ArgIndex = *ArgOpt;
11391
Alex Denisove1d882c2015-03-04 17:55:52 +000011392 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
11393 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
11394 Arg = OE->getSourceExpr()->IgnoreImpCasts();
11395 }
11396
Alex Denisov5dfac812015-08-06 04:51:14 +000011397 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011398 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011399 if (ArgRE->isObjCSelfExpr()) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011400 Diag(Message->getSourceRange().getBegin(),
11401 diag::warn_objc_circular_container)
Alex Denisov5dfac812015-08-06 04:51:14 +000011402 << ArgRE->getDecl()->getName() << StringRef("super");
Alex Denisove1d882c2015-03-04 17:55:52 +000011403 }
11404 }
Alex Denisov5dfac812015-08-06 04:51:14 +000011405 } else {
11406 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
11407
11408 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
11409 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
11410 }
11411
11412 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
11413 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
11414 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
11415 ValueDecl *Decl = ReceiverRE->getDecl();
11416 Diag(Message->getSourceRange().getBegin(),
11417 diag::warn_objc_circular_container)
11418 << Decl->getName() << Decl->getName();
11419 if (!ArgRE->isObjCSelfExpr()) {
11420 Diag(Decl->getLocation(),
11421 diag::note_objc_circular_container_declared_here)
11422 << Decl->getName();
11423 }
11424 }
11425 }
11426 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
11427 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
11428 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
11429 ObjCIvarDecl *Decl = IvarRE->getDecl();
11430 Diag(Message->getSourceRange().getBegin(),
11431 diag::warn_objc_circular_container)
11432 << Decl->getName() << Decl->getName();
11433 Diag(Decl->getLocation(),
11434 diag::note_objc_circular_container_declared_here)
11435 << Decl->getName();
11436 }
Alex Denisove1d882c2015-03-04 17:55:52 +000011437 }
11438 }
11439 }
Alex Denisove1d882c2015-03-04 17:55:52 +000011440}
11441
John McCall31168b02011-06-15 23:02:42 +000011442/// Check a message send to see if it's likely to cause a retain cycle.
11443void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
11444 // Only check instance methods whose selector looks like a setter.
11445 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
11446 return;
11447
11448 // Try to find a variable that the receiver is strongly owned by.
11449 RetainCycleOwner owner;
11450 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011451 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +000011452 return;
11453 } else {
11454 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
11455 owner.Variable = getCurMethodDecl()->getSelfDecl();
11456 owner.Loc = msg->getSuperLoc();
11457 owner.Range = msg->getSuperLoc();
11458 }
11459
11460 // Check whether the receiver is captured by any of the arguments.
11461 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
11462 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
11463 return diagnoseRetainCycle(*this, capturer, owner);
11464}
11465
11466/// Check a property assign to see if it's likely to cause a retain cycle.
11467void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
11468 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011469 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +000011470 return;
11471
11472 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
11473 diagnoseRetainCycle(*this, capturer, owner);
11474}
11475
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000011476void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
11477 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +000011478 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000011479 return;
11480
11481 // Because we don't have an expression for the variable, we have to set the
11482 // location explicitly here.
11483 Owner.Loc = Var->getLocation();
11484 Owner.Range = Var->getSourceRange();
11485
11486 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
11487 diagnoseRetainCycle(*this, Capturer, Owner);
11488}
11489
Ted Kremenek9304da92012-12-21 08:04:28 +000011490static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
11491 Expr *RHS, bool isProperty) {
11492 // Check if RHS is an Objective-C object literal, which also can get
11493 // immediately zapped in a weak reference. Note that we explicitly
11494 // allow ObjCStringLiterals, since those are designed to never really die.
11495 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000011496
Ted Kremenek64873352012-12-21 22:46:35 +000011497 // This enum needs to match with the 'select' in
11498 // warn_objc_arc_literal_assign (off-by-1).
11499 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
11500 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
11501 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000011502
11503 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +000011504 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +000011505 << (isProperty ? 0 : 1)
11506 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000011507
11508 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +000011509}
11510
Ted Kremenekc1f014a2012-12-21 19:45:30 +000011511static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
11512 Qualifiers::ObjCLifetime LT,
11513 Expr *RHS, bool isProperty) {
11514 // Strip off any implicit cast added to get to the one ARC-specific.
11515 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
11516 if (cast->getCastKind() == CK_ARCConsumeObject) {
11517 S.Diag(Loc, diag::warn_arc_retained_assign)
11518 << (LT == Qualifiers::OCL_ExplicitNone)
11519 << (isProperty ? 0 : 1)
11520 << RHS->getSourceRange();
11521 return true;
11522 }
11523 RHS = cast->getSubExpr();
11524 }
11525
11526 if (LT == Qualifiers::OCL_Weak &&
11527 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
11528 return true;
11529
11530 return false;
11531}
11532
Ted Kremenekb36234d2012-12-21 08:04:20 +000011533bool Sema::checkUnsafeAssigns(SourceLocation Loc,
11534 QualType LHS, Expr *RHS) {
11535 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
11536
11537 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
11538 return false;
11539
11540 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
11541 return true;
11542
11543 return false;
11544}
11545
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011546void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
11547 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011548 QualType LHSType;
11549 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +000011550 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011551 ObjCPropertyRefExpr *PRE
11552 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
11553 if (PRE && !PRE->isImplicitProperty()) {
11554 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11555 if (PD)
11556 LHSType = PD->getType();
11557 }
11558
11559 if (LHSType.isNull())
11560 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +000011561
11562 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
11563
11564 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000011565 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +000011566 getCurFunction()->markSafeWeakUse(LHS);
11567 }
11568
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011569 if (checkUnsafeAssigns(Loc, LHSType, RHS))
11570 return;
Jordan Rose657b5f42012-09-28 22:21:35 +000011571
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011572 // FIXME. Check for other life times.
11573 if (LT != Qualifiers::OCL_None)
11574 return;
11575
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011576 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011577 if (PRE->isImplicitProperty())
11578 return;
11579 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11580 if (!PD)
11581 return;
11582
Bill Wendling44426052012-12-20 19:22:21 +000011583 unsigned Attributes = PD->getPropertyAttributes();
11584 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011585 // when 'assign' attribute was not explicitly specified
11586 // by user, ignore it and rely on property type itself
11587 // for lifetime info.
11588 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
11589 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
11590 LHSType->isObjCRetainableType())
11591 return;
11592
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011593 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +000011594 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011595 Diag(Loc, diag::warn_arc_retained_property_assign)
11596 << RHS->getSourceRange();
11597 return;
11598 }
11599 RHS = cast->getSubExpr();
11600 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011601 }
Bill Wendling44426052012-12-20 19:22:21 +000011602 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +000011603 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
11604 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +000011605 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011606 }
11607}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011608
11609//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
11610
11611namespace {
11612bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
11613 SourceLocation StmtLoc,
11614 const NullStmt *Body) {
11615 // Do not warn if the body is a macro that expands to nothing, e.g:
11616 //
11617 // #define CALL(x)
11618 // if (condition)
11619 // CALL(0);
11620 //
11621 if (Body->hasLeadingEmptyMacro())
11622 return false;
11623
11624 // Get line numbers of statement and body.
11625 bool StmtLineInvalid;
Dmitri Gribenkoad80af82015-03-15 01:08:23 +000011626 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011627 &StmtLineInvalid);
11628 if (StmtLineInvalid)
11629 return false;
11630
11631 bool BodyLineInvalid;
11632 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
11633 &BodyLineInvalid);
11634 if (BodyLineInvalid)
11635 return false;
11636
11637 // Warn if null statement and body are on the same line.
11638 if (StmtLine != BodyLine)
11639 return false;
11640
11641 return true;
11642}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011643} // end anonymous namespace
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011644
11645void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
11646 const Stmt *Body,
11647 unsigned DiagID) {
11648 // Since this is a syntactic check, don't emit diagnostic for template
11649 // instantiations, this just adds noise.
11650 if (CurrentInstantiationScope)
11651 return;
11652
11653 // The body should be a null statement.
11654 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11655 if (!NBody)
11656 return;
11657
11658 // Do the usual checks.
11659 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11660 return;
11661
11662 Diag(NBody->getSemiLoc(), DiagID);
11663 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11664}
11665
11666void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
11667 const Stmt *PossibleBody) {
11668 assert(!CurrentInstantiationScope); // Ensured by caller
11669
11670 SourceLocation StmtLoc;
11671 const Stmt *Body;
11672 unsigned DiagID;
11673 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
11674 StmtLoc = FS->getRParenLoc();
11675 Body = FS->getBody();
11676 DiagID = diag::warn_empty_for_body;
11677 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
11678 StmtLoc = WS->getCond()->getSourceRange().getEnd();
11679 Body = WS->getBody();
11680 DiagID = diag::warn_empty_while_body;
11681 } else
11682 return; // Neither `for' nor `while'.
11683
11684 // The body should be a null statement.
11685 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11686 if (!NBody)
11687 return;
11688
11689 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000011690 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011691 return;
11692
11693 // Do the usual checks.
11694 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11695 return;
11696
11697 // `for(...);' and `while(...);' are popular idioms, so in order to keep
11698 // noise level low, emit diagnostics only if for/while is followed by a
11699 // CompoundStmt, e.g.:
11700 // for (int i = 0; i < n; i++);
11701 // {
11702 // a(i);
11703 // }
11704 // or if for/while is followed by a statement with more indentation
11705 // than for/while itself:
11706 // for (int i = 0; i < n; i++);
11707 // a(i);
11708 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
11709 if (!ProbableTypo) {
11710 bool BodyColInvalid;
11711 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
11712 PossibleBody->getLocStart(),
11713 &BodyColInvalid);
11714 if (BodyColInvalid)
11715 return;
11716
11717 bool StmtColInvalid;
11718 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
11719 S->getLocStart(),
11720 &StmtColInvalid);
11721 if (StmtColInvalid)
11722 return;
11723
11724 if (BodyCol > StmtCol)
11725 ProbableTypo = true;
11726 }
11727
11728 if (ProbableTypo) {
11729 Diag(NBody->getSemiLoc(), DiagID);
11730 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11731 }
11732}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011733
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011734//===--- CHECK: Warn on self move with std::move. -------------------------===//
11735
11736/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
11737void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
11738 SourceLocation OpLoc) {
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011739 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
11740 return;
11741
Richard Smith51ec0cf2017-02-21 01:17:38 +000011742 if (inTemplateInstantiation())
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011743 return;
11744
11745 // Strip parens and casts away.
11746 LHSExpr = LHSExpr->IgnoreParenImpCasts();
11747 RHSExpr = RHSExpr->IgnoreParenImpCasts();
11748
11749 // Check for a call expression
11750 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
11751 if (!CE || CE->getNumArgs() != 1)
11752 return;
11753
11754 // Check for a call to std::move
11755 const FunctionDecl *FD = CE->getDirectCallee();
11756 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
11757 !FD->getIdentifier()->isStr("move"))
11758 return;
11759
11760 // Get argument from std::move
11761 RHSExpr = CE->getArg(0);
11762
11763 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
11764 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
11765
11766 // Two DeclRefExpr's, check that the decls are the same.
11767 if (LHSDeclRef && RHSDeclRef) {
11768 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11769 return;
11770 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11771 RHSDeclRef->getDecl()->getCanonicalDecl())
11772 return;
11773
11774 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11775 << LHSExpr->getSourceRange()
11776 << RHSExpr->getSourceRange();
11777 return;
11778 }
11779
11780 // Member variables require a different approach to check for self moves.
11781 // MemberExpr's are the same if every nested MemberExpr refers to the same
11782 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
11783 // the base Expr's are CXXThisExpr's.
11784 const Expr *LHSBase = LHSExpr;
11785 const Expr *RHSBase = RHSExpr;
11786 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
11787 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
11788 if (!LHSME || !RHSME)
11789 return;
11790
11791 while (LHSME && RHSME) {
11792 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
11793 RHSME->getMemberDecl()->getCanonicalDecl())
11794 return;
11795
11796 LHSBase = LHSME->getBase();
11797 RHSBase = RHSME->getBase();
11798 LHSME = dyn_cast<MemberExpr>(LHSBase);
11799 RHSME = dyn_cast<MemberExpr>(RHSBase);
11800 }
11801
11802 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
11803 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
11804 if (LHSDeclRef && RHSDeclRef) {
11805 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11806 return;
11807 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11808 RHSDeclRef->getDecl()->getCanonicalDecl())
11809 return;
11810
11811 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11812 << LHSExpr->getSourceRange()
11813 << RHSExpr->getSourceRange();
11814 return;
11815 }
11816
11817 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
11818 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11819 << LHSExpr->getSourceRange()
11820 << RHSExpr->getSourceRange();
11821}
11822
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011823//===--- Layout compatibility ----------------------------------------------//
11824
11825namespace {
11826
11827bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
11828
11829/// \brief Check if two enumeration types are layout-compatible.
11830bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
11831 // C++11 [dcl.enum] p8:
11832 // Two enumeration types are layout-compatible if they have the same
11833 // underlying type.
11834 return ED1->isComplete() && ED2->isComplete() &&
11835 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
11836}
11837
11838/// \brief Check if two fields are layout-compatible.
11839bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
11840 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
11841 return false;
11842
11843 if (Field1->isBitField() != Field2->isBitField())
11844 return false;
11845
11846 if (Field1->isBitField()) {
11847 // Make sure that the bit-fields are the same length.
11848 unsigned Bits1 = Field1->getBitWidthValue(C);
11849 unsigned Bits2 = Field2->getBitWidthValue(C);
11850
11851 if (Bits1 != Bits2)
11852 return false;
11853 }
11854
11855 return true;
11856}
11857
11858/// \brief Check if two standard-layout structs are layout-compatible.
11859/// (C++11 [class.mem] p17)
11860bool isLayoutCompatibleStruct(ASTContext &C,
11861 RecordDecl *RD1,
11862 RecordDecl *RD2) {
11863 // If both records are C++ classes, check that base classes match.
11864 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
11865 // If one of records is a CXXRecordDecl we are in C++ mode,
11866 // thus the other one is a CXXRecordDecl, too.
11867 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
11868 // Check number of base classes.
11869 if (D1CXX->getNumBases() != D2CXX->getNumBases())
11870 return false;
11871
11872 // Check the base classes.
11873 for (CXXRecordDecl::base_class_const_iterator
11874 Base1 = D1CXX->bases_begin(),
11875 BaseEnd1 = D1CXX->bases_end(),
11876 Base2 = D2CXX->bases_begin();
11877 Base1 != BaseEnd1;
11878 ++Base1, ++Base2) {
11879 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
11880 return false;
11881 }
11882 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
11883 // If only RD2 is a C++ class, it should have zero base classes.
11884 if (D2CXX->getNumBases() > 0)
11885 return false;
11886 }
11887
11888 // Check the fields.
11889 RecordDecl::field_iterator Field2 = RD2->field_begin(),
11890 Field2End = RD2->field_end(),
11891 Field1 = RD1->field_begin(),
11892 Field1End = RD1->field_end();
11893 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
11894 if (!isLayoutCompatible(C, *Field1, *Field2))
11895 return false;
11896 }
11897 if (Field1 != Field1End || Field2 != Field2End)
11898 return false;
11899
11900 return true;
11901}
11902
11903/// \brief Check if two standard-layout unions are layout-compatible.
11904/// (C++11 [class.mem] p18)
11905bool isLayoutCompatibleUnion(ASTContext &C,
11906 RecordDecl *RD1,
11907 RecordDecl *RD2) {
11908 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011909 for (auto *Field2 : RD2->fields())
11910 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011911
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011912 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011913 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
11914 I = UnmatchedFields.begin(),
11915 E = UnmatchedFields.end();
11916
11917 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011918 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011919 bool Result = UnmatchedFields.erase(*I);
11920 (void) Result;
11921 assert(Result);
11922 break;
11923 }
11924 }
11925 if (I == E)
11926 return false;
11927 }
11928
11929 return UnmatchedFields.empty();
11930}
11931
11932bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
11933 if (RD1->isUnion() != RD2->isUnion())
11934 return false;
11935
11936 if (RD1->isUnion())
11937 return isLayoutCompatibleUnion(C, RD1, RD2);
11938 else
11939 return isLayoutCompatibleStruct(C, RD1, RD2);
11940}
11941
11942/// \brief Check if two types are layout-compatible in C++11 sense.
11943bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
11944 if (T1.isNull() || T2.isNull())
11945 return false;
11946
11947 // C++11 [basic.types] p11:
11948 // If two types T1 and T2 are the same type, then T1 and T2 are
11949 // layout-compatible types.
11950 if (C.hasSameType(T1, T2))
11951 return true;
11952
11953 T1 = T1.getCanonicalType().getUnqualifiedType();
11954 T2 = T2.getCanonicalType().getUnqualifiedType();
11955
11956 const Type::TypeClass TC1 = T1->getTypeClass();
11957 const Type::TypeClass TC2 = T2->getTypeClass();
11958
11959 if (TC1 != TC2)
11960 return false;
11961
11962 if (TC1 == Type::Enum) {
11963 return isLayoutCompatible(C,
11964 cast<EnumType>(T1)->getDecl(),
11965 cast<EnumType>(T2)->getDecl());
11966 } else if (TC1 == Type::Record) {
11967 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
11968 return false;
11969
11970 return isLayoutCompatible(C,
11971 cast<RecordType>(T1)->getDecl(),
11972 cast<RecordType>(T2)->getDecl());
11973 }
11974
11975 return false;
11976}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011977} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011978
11979//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
11980
11981namespace {
11982/// \brief Given a type tag expression find the type tag itself.
11983///
11984/// \param TypeExpr Type tag expression, as it appears in user's code.
11985///
11986/// \param VD Declaration of an identifier that appears in a type tag.
11987///
11988/// \param MagicValue Type tag magic value.
11989bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
11990 const ValueDecl **VD, uint64_t *MagicValue) {
11991 while(true) {
11992 if (!TypeExpr)
11993 return false;
11994
11995 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
11996
11997 switch (TypeExpr->getStmtClass()) {
11998 case Stmt::UnaryOperatorClass: {
11999 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
12000 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
12001 TypeExpr = UO->getSubExpr();
12002 continue;
12003 }
12004 return false;
12005 }
12006
12007 case Stmt::DeclRefExprClass: {
12008 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
12009 *VD = DRE->getDecl();
12010 return true;
12011 }
12012
12013 case Stmt::IntegerLiteralClass: {
12014 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
12015 llvm::APInt MagicValueAPInt = IL->getValue();
12016 if (MagicValueAPInt.getActiveBits() <= 64) {
12017 *MagicValue = MagicValueAPInt.getZExtValue();
12018 return true;
12019 } else
12020 return false;
12021 }
12022
12023 case Stmt::BinaryConditionalOperatorClass:
12024 case Stmt::ConditionalOperatorClass: {
12025 const AbstractConditionalOperator *ACO =
12026 cast<AbstractConditionalOperator>(TypeExpr);
12027 bool Result;
12028 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
12029 if (Result)
12030 TypeExpr = ACO->getTrueExpr();
12031 else
12032 TypeExpr = ACO->getFalseExpr();
12033 continue;
12034 }
12035 return false;
12036 }
12037
12038 case Stmt::BinaryOperatorClass: {
12039 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
12040 if (BO->getOpcode() == BO_Comma) {
12041 TypeExpr = BO->getRHS();
12042 continue;
12043 }
12044 return false;
12045 }
12046
12047 default:
12048 return false;
12049 }
12050 }
12051}
12052
12053/// \brief Retrieve the C type corresponding to type tag TypeExpr.
12054///
12055/// \param TypeExpr Expression that specifies a type tag.
12056///
12057/// \param MagicValues Registered magic values.
12058///
12059/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
12060/// kind.
12061///
12062/// \param TypeInfo Information about the corresponding C type.
12063///
12064/// \returns true if the corresponding C type was found.
12065bool GetMatchingCType(
12066 const IdentifierInfo *ArgumentKind,
12067 const Expr *TypeExpr, const ASTContext &Ctx,
12068 const llvm::DenseMap<Sema::TypeTagMagicValue,
12069 Sema::TypeTagData> *MagicValues,
12070 bool &FoundWrongKind,
12071 Sema::TypeTagData &TypeInfo) {
12072 FoundWrongKind = false;
12073
12074 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +000012075 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012076
12077 uint64_t MagicValue;
12078
12079 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
12080 return false;
12081
12082 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +000012083 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012084 if (I->getArgumentKind() != ArgumentKind) {
12085 FoundWrongKind = true;
12086 return false;
12087 }
12088 TypeInfo.Type = I->getMatchingCType();
12089 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
12090 TypeInfo.MustBeNull = I->getMustBeNull();
12091 return true;
12092 }
12093 return false;
12094 }
12095
12096 if (!MagicValues)
12097 return false;
12098
12099 llvm::DenseMap<Sema::TypeTagMagicValue,
12100 Sema::TypeTagData>::const_iterator I =
12101 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
12102 if (I == MagicValues->end())
12103 return false;
12104
12105 TypeInfo = I->second;
12106 return true;
12107}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000012108} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012109
12110void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
12111 uint64_t MagicValue, QualType Type,
12112 bool LayoutCompatible,
12113 bool MustBeNull) {
12114 if (!TypeTagForDatatypeMagicValues)
12115 TypeTagForDatatypeMagicValues.reset(
12116 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
12117
12118 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
12119 (*TypeTagForDatatypeMagicValues)[Magic] =
12120 TypeTagData(Type, LayoutCompatible, MustBeNull);
12121}
12122
12123namespace {
12124bool IsSameCharType(QualType T1, QualType T2) {
12125 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
12126 if (!BT1)
12127 return false;
12128
12129 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
12130 if (!BT2)
12131 return false;
12132
12133 BuiltinType::Kind T1Kind = BT1->getKind();
12134 BuiltinType::Kind T2Kind = BT2->getKind();
12135
12136 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
12137 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
12138 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
12139 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
12140}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000012141} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012142
12143void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
12144 const Expr * const *ExprArgs) {
12145 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
12146 bool IsPointerAttr = Attr->getIsPointer();
12147
12148 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
12149 bool FoundWrongKind;
12150 TypeTagData TypeInfo;
12151 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
12152 TypeTagForDatatypeMagicValues.get(),
12153 FoundWrongKind, TypeInfo)) {
12154 if (FoundWrongKind)
12155 Diag(TypeTagExpr->getExprLoc(),
12156 diag::warn_type_tag_for_datatype_wrong_kind)
12157 << TypeTagExpr->getSourceRange();
12158 return;
12159 }
12160
12161 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
12162 if (IsPointerAttr) {
12163 // Skip implicit cast of pointer to `void *' (as a function argument).
12164 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +000012165 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +000012166 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012167 ArgumentExpr = ICE->getSubExpr();
12168 }
12169 QualType ArgumentType = ArgumentExpr->getType();
12170
12171 // Passing a `void*' pointer shouldn't trigger a warning.
12172 if (IsPointerAttr && ArgumentType->isVoidPointerType())
12173 return;
12174
12175 if (TypeInfo.MustBeNull) {
12176 // Type tag with matching void type requires a null pointer.
12177 if (!ArgumentExpr->isNullPointerConstant(Context,
12178 Expr::NPC_ValueDependentIsNotNull)) {
12179 Diag(ArgumentExpr->getExprLoc(),
12180 diag::warn_type_safety_null_pointer_required)
12181 << ArgumentKind->getName()
12182 << ArgumentExpr->getSourceRange()
12183 << TypeTagExpr->getSourceRange();
12184 }
12185 return;
12186 }
12187
12188 QualType RequiredType = TypeInfo.Type;
12189 if (IsPointerAttr)
12190 RequiredType = Context.getPointerType(RequiredType);
12191
12192 bool mismatch = false;
12193 if (!TypeInfo.LayoutCompatible) {
12194 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
12195
12196 // C++11 [basic.fundamental] p1:
12197 // Plain char, signed char, and unsigned char are three distinct types.
12198 //
12199 // But we treat plain `char' as equivalent to `signed char' or `unsigned
12200 // char' depending on the current char signedness mode.
12201 if (mismatch)
12202 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
12203 RequiredType->getPointeeType())) ||
12204 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
12205 mismatch = false;
12206 } else
12207 if (IsPointerAttr)
12208 mismatch = !isLayoutCompatible(Context,
12209 ArgumentType->getPointeeType(),
12210 RequiredType->getPointeeType());
12211 else
12212 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
12213
12214 if (mismatch)
12215 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +000012216 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012217 << TypeInfo.LayoutCompatible << RequiredType
12218 << ArgumentExpr->getSourceRange()
12219 << TypeTagExpr->getSourceRange();
12220}
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012221
12222void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
12223 CharUnits Alignment) {
12224 MisalignedMembers.emplace_back(E, RD, MD, Alignment);
12225}
12226
12227void Sema::DiagnoseMisalignedMembers() {
12228 for (MisalignedMember &m : MisalignedMembers) {
Alex Lorenz014181e2016-10-05 09:27:48 +000012229 const NamedDecl *ND = m.RD;
12230 if (ND->getName().empty()) {
12231 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
12232 ND = TD;
12233 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012234 Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member)
Alex Lorenz014181e2016-10-05 09:27:48 +000012235 << m.MD << ND << m.E->getSourceRange();
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012236 }
12237 MisalignedMembers.clear();
12238}
12239
12240void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012241 E = E->IgnoreParens();
12242 if (!T->isPointerType() && !T->isIntegerType())
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012243 return;
12244 if (isa<UnaryOperator>(E) &&
12245 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
12246 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
12247 if (isa<MemberExpr>(Op)) {
12248 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
12249 MisalignedMember(Op));
12250 if (MA != MisalignedMembers.end() &&
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012251 (T->isIntegerType() ||
12252 (T->isPointerType() &&
12253 Context.getTypeAlignInChars(T->getPointeeType()) <= MA->Alignment)))
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012254 MisalignedMembers.erase(MA);
12255 }
12256 }
12257}
12258
12259void Sema::RefersToMemberWithReducedAlignment(
12260 Expr *E,
Benjamin Kramera8c3e672016-12-12 14:41:19 +000012261 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
12262 Action) {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012263 const auto *ME = dyn_cast<MemberExpr>(E);
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012264 if (!ME)
12265 return;
12266
Roger Ferrer Ibanez9f963472017-03-13 13:18:21 +000012267 // No need to check expressions with an __unaligned-qualified type.
12268 if (E->getType().getQualifiers().hasUnaligned())
12269 return;
12270
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012271 // For a chain of MemberExpr like "a.b.c.d" this list
12272 // will keep FieldDecl's like [d, c, b].
12273 SmallVector<FieldDecl *, 4> ReverseMemberChain;
12274 const MemberExpr *TopME = nullptr;
12275 bool AnyIsPacked = false;
12276 do {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012277 QualType BaseType = ME->getBase()->getType();
12278 if (ME->isArrow())
12279 BaseType = BaseType->getPointeeType();
12280 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
Olivier Goffart67049f02017-07-07 09:38:59 +000012281 if (RD->isInvalidDecl())
12282 return;
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012283
12284 ValueDecl *MD = ME->getMemberDecl();
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012285 auto *FD = dyn_cast<FieldDecl>(MD);
12286 // We do not care about non-data members.
12287 if (!FD || FD->isInvalidDecl())
12288 return;
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012289
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012290 AnyIsPacked =
12291 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
12292 ReverseMemberChain.push_back(FD);
12293
12294 TopME = ME;
12295 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
12296 } while (ME);
12297 assert(TopME && "We did not compute a topmost MemberExpr!");
12298
12299 // Not the scope of this diagnostic.
12300 if (!AnyIsPacked)
12301 return;
12302
12303 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
12304 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
12305 // TODO: The innermost base of the member expression may be too complicated.
12306 // For now, just disregard these cases. This is left for future
12307 // improvement.
12308 if (!DRE && !isa<CXXThisExpr>(TopBase))
12309 return;
12310
12311 // Alignment expected by the whole expression.
12312 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
12313
12314 // No need to do anything else with this case.
12315 if (ExpectedAlignment.isOne())
12316 return;
12317
12318 // Synthesize offset of the whole access.
12319 CharUnits Offset;
12320 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
12321 I++) {
12322 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
12323 }
12324
12325 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
12326 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
12327 ReverseMemberChain.back()->getParent()->getTypeForDecl());
12328
12329 // The base expression of the innermost MemberExpr may give
12330 // stronger guarantees than the class containing the member.
12331 if (DRE && !TopME->isArrow()) {
12332 const ValueDecl *VD = DRE->getDecl();
12333 if (!VD->getType()->isReferenceType())
12334 CompleteObjectAlignment =
12335 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
12336 }
12337
12338 // Check if the synthesized offset fulfills the alignment.
12339 if (Offset % ExpectedAlignment != 0 ||
12340 // It may fulfill the offset it but the effective alignment may still be
12341 // lower than the expected expression alignment.
12342 CompleteObjectAlignment < ExpectedAlignment) {
12343 // If this happens, we want to determine a sensible culprit of this.
12344 // Intuitively, watching the chain of member expressions from right to
12345 // left, we start with the required alignment (as required by the field
12346 // type) but some packed attribute in that chain has reduced the alignment.
12347 // It may happen that another packed structure increases it again. But if
12348 // we are here such increase has not been enough. So pointing the first
12349 // FieldDecl that either is packed or else its RecordDecl is,
12350 // seems reasonable.
12351 FieldDecl *FD = nullptr;
12352 CharUnits Alignment;
12353 for (FieldDecl *FDI : ReverseMemberChain) {
12354 if (FDI->hasAttr<PackedAttr>() ||
12355 FDI->getParent()->hasAttr<PackedAttr>()) {
12356 FD = FDI;
12357 Alignment = std::min(
12358 Context.getTypeAlignInChars(FD->getType()),
12359 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
12360 break;
12361 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012362 }
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012363 assert(FD && "We did not find a packed FieldDecl!");
12364 Action(E, FD->getParent(), FD, Alignment);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012365 }
12366}
12367
12368void Sema::CheckAddressOfPackedMember(Expr *rhs) {
12369 using namespace std::placeholders;
12370 RefersToMemberWithReducedAlignment(
12371 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
12372 _2, _3, _4));
12373}
12374