clang  3.9.0
SemaChecking.cpp
Go to the documentation of this file.
1 //===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements extra semantic analysis beyond what is enforced
11 // by the C type system.
12 //
13 //===----------------------------------------------------------------------===//
14 
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/CharUnits.h"
18 #include "clang/AST/DeclCXX.h"
19 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/Expr.h"
22 #include "clang/AST/ExprCXX.h"
23 #include "clang/AST/ExprObjC.h"
24 #include "clang/AST/ExprOpenMP.h"
25 #include "clang/AST/StmtCXX.h"
26 #include "clang/AST/StmtObjC.h"
28 #include "clang/Basic/CharInfo.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
33 #include "clang/Sema/Lookup.h"
34 #include "clang/Sema/ScopeInfo.h"
35 #include "clang/Sema/Sema.h"
36 #include "llvm/ADT/STLExtras.h"
37 #include "llvm/ADT/SmallBitVector.h"
38 #include "llvm/ADT/SmallString.h"
39 #include "llvm/Support/Format.h"
40 #include "llvm/Support/Locale.h"
41 #include "llvm/Support/ConvertUTF.h"
42 #include "llvm/Support/raw_ostream.h"
43 #include <limits>
44 
45 using namespace clang;
46 using namespace sema;
47 
49  unsigned ByteNo) const {
50  return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
52 }
53 
54 /// 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.
56 static 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 
74 /// Check that the first argument to __builtin_annotation is an integer
75 /// and the second argument is a non-wide string literal.
76 static 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();
86  return true;
87  }
88 
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);
99  return false;
100 }
101 
102 /// Check that the argument to __builtin_addressof is a glvalue, and set the
103 /// result type to the corresponding pointer type.
104 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
105  if (checkArgCount(S, TheCall, 1))
106  return true;
107 
108  ExprResult Arg(TheCall->getArg(0));
109  QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
110  if (ResultType.isNull())
111  return true;
112 
113  TheCall->setArg(0, Arg.get());
114  TheCall->setType(ResultType);
115  return false;
116 }
117 
118 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
119  if (checkArgCount(S, TheCall, 3))
120  return true;
121 
122  // First two arguments should be integers.
123  for (unsigned I = 0; I < 2; ++I) {
124  Expr *Arg = TheCall->getArg(I);
125  QualType Ty = Arg->getType();
126  if (!Ty->isIntegerType()) {
127  S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_int)
128  << Ty << Arg->getSourceRange();
129  return true;
130  }
131  }
132 
133  // Third argument should be a pointer to a non-const integer.
134  // IRGen correctly handles volatile, restrict, and address spaces, and
135  // the other qualifiers aren't possible.
136  {
137  Expr *Arg = TheCall->getArg(2);
138  QualType Ty = Arg->getType();
139  const auto *PtrTy = Ty->getAs<PointerType>();
140  if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
141  !PtrTy->getPointeeType().isConstQualified())) {
142  S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_ptr_int)
143  << Ty << Arg->getSourceRange();
144  return true;
145  }
146  }
147 
148  return false;
149 }
150 
152  CallExpr *TheCall, unsigned SizeIdx,
153  unsigned DstSizeIdx) {
154  if (TheCall->getNumArgs() <= SizeIdx ||
155  TheCall->getNumArgs() <= DstSizeIdx)
156  return;
157 
158  const Expr *SizeArg = TheCall->getArg(SizeIdx);
159  const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
160 
161  llvm::APSInt Size, DstSize;
162 
163  // find out if both sizes are known at compile time
164  if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
165  !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
166  return;
167 
168  if (Size.ule(DstSize))
169  return;
170 
171  // confirmed overflow so generate the diagnostic.
172  IdentifierInfo *FnName = FDecl->getIdentifier();
173  SourceLocation SL = TheCall->getLocStart();
174  SourceRange SR = TheCall->getSourceRange();
175 
176  S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
177 }
178 
179 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
180  if (checkArgCount(S, BuiltinCall, 2))
181  return true;
182 
183  SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
184  Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
185  Expr *Call = BuiltinCall->getArg(0);
186  Expr *Chain = BuiltinCall->getArg(1);
187 
188  if (Call->getStmtClass() != Stmt::CallExprClass) {
189  S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
190  << Call->getSourceRange();
191  return true;
192  }
193 
194  auto CE = cast<CallExpr>(Call);
195  if (CE->getCallee()->getType()->isBlockPointerType()) {
196  S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
197  << Call->getSourceRange();
198  return true;
199  }
200 
201  const Decl *TargetDecl = CE->getCalleeDecl();
202  if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
203  if (FD->getBuiltinID()) {
204  S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
205  << Call->getSourceRange();
206  return true;
207  }
208 
209  if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
210  S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
211  << Call->getSourceRange();
212  return true;
213  }
214 
215  ExprResult ChainResult = S.UsualUnaryConversions(Chain);
216  if (ChainResult.isInvalid())
217  return true;
218  if (!ChainResult.get()->getType()->isPointerType()) {
219  S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
220  << Chain->getSourceRange();
221  return true;
222  }
223 
224  QualType ReturnTy = CE->getCallReturnType(S.Context);
225  QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
226  QualType BuiltinTy = S.Context.getFunctionType(
227  ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
228  QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
229 
230  Builtin =
231  S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
232 
233  BuiltinCall->setType(CE->getType());
234  BuiltinCall->setValueKind(CE->getValueKind());
235  BuiltinCall->setObjectKind(CE->getObjectKind());
236  BuiltinCall->setCallee(Builtin);
237  BuiltinCall->setArg(1, ChainResult.get());
238 
239  return false;
240 }
241 
242 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
243  Scope::ScopeFlags NeededScopeFlags,
244  unsigned DiagID) {
245  // Scopes aren't available during instantiation. Fortunately, builtin
246  // functions cannot be template args so they cannot be formed through template
247  // instantiation. Therefore checking once during the parse is sufficient.
248  if (!SemaRef.ActiveTemplateInstantiations.empty())
249  return false;
250 
251  Scope *S = SemaRef.getCurScope();
252  while (S && !S->isSEHExceptScope())
253  S = S->getParent();
254  if (!S || !(S->getFlags() & NeededScopeFlags)) {
255  auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
256  SemaRef.Diag(TheCall->getExprLoc(), DiagID)
257  << DRE->getDecl()->getIdentifier();
258  return true;
259  }
260 
261  return false;
262 }
263 
264 static inline bool isBlockPointer(Expr *Arg) {
265  return Arg->getType()->isBlockPointerType();
266 }
267 
268 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
269 /// void*, which is a requirement of device side enqueue.
270 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
271  const BlockPointerType *BPT =
272  cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
273  ArrayRef<QualType> Params =
274  BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes();
275  unsigned ArgCounter = 0;
276  bool IllegalParams = false;
277  // Iterate through the block parameters until either one is found that is not
278  // a local void*, or the block is valid.
279  for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
280  I != E; ++I, ++ArgCounter) {
281  if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
282  (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
284  // Get the location of the error. If a block literal has been passed
285  // (BlockExpr) then we can point straight to the offending argument,
286  // else we just point to the variable reference.
287  SourceLocation ErrorLoc;
288  if (isa<BlockExpr>(BlockArg)) {
289  BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
290  ErrorLoc = BD->getParamDecl(ArgCounter)->getLocStart();
291  } else if (isa<DeclRefExpr>(BlockArg)) {
292  ErrorLoc = cast<DeclRefExpr>(BlockArg)->getLocStart();
293  }
294  S.Diag(ErrorLoc,
295  diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
296  IllegalParams = true;
297  }
298  }
299 
300  return IllegalParams;
301 }
302 
303 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
304 /// get_kernel_work_group_size
305 /// and get_kernel_preferred_work_group_size_multiple builtin functions.
307  if (checkArgCount(S, TheCall, 1))
308  return true;
309 
310  Expr *BlockArg = TheCall->getArg(0);
311  if (!isBlockPointer(BlockArg)) {
312  S.Diag(BlockArg->getLocStart(),
313  diag::err_opencl_enqueue_kernel_expected_type) << "block";
314  return true;
315  }
316  return checkOpenCLBlockArgs(S, BlockArg);
317 }
318 
319 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
320  unsigned Start, unsigned End);
321 
322 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
323 /// 'local void*' parameter of passed block.
325  Expr *BlockArg,
326  unsigned NumNonVarArgs) {
327  const BlockPointerType *BPT =
328  cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
329  unsigned NumBlockParams =
330  BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams();
331  unsigned TotalNumArgs = TheCall->getNumArgs();
332 
333  // For each argument passed to the block, a corresponding uint needs to
334  // be passed to describe the size of the local memory.
335  if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
336  S.Diag(TheCall->getLocStart(),
337  diag::err_opencl_enqueue_kernel_local_size_args);
338  return true;
339  }
340 
341  // Check that the sizes of the local memory are specified by integers.
342  return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
343  TotalNumArgs - 1);
344 }
345 
346 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
347 /// overload formats specified in Table 6.13.17.1.
348 /// int enqueue_kernel(queue_t queue,
349 /// kernel_enqueue_flags_t flags,
350 /// const ndrange_t ndrange,
351 /// void (^block)(void))
352 /// int enqueue_kernel(queue_t queue,
353 /// kernel_enqueue_flags_t flags,
354 /// const ndrange_t ndrange,
355 /// uint num_events_in_wait_list,
356 /// clk_event_t *event_wait_list,
357 /// clk_event_t *event_ret,
358 /// void (^block)(void))
359 /// int enqueue_kernel(queue_t queue,
360 /// kernel_enqueue_flags_t flags,
361 /// const ndrange_t ndrange,
362 /// void (^block)(local void*, ...),
363 /// uint size0, ...)
364 /// int enqueue_kernel(queue_t queue,
365 /// kernel_enqueue_flags_t flags,
366 /// const ndrange_t ndrange,
367 /// uint num_events_in_wait_list,
368 /// clk_event_t *event_wait_list,
369 /// clk_event_t *event_ret,
370 /// void (^block)(local void*, ...),
371 /// uint size0, ...)
373  unsigned NumArgs = TheCall->getNumArgs();
374 
375  if (NumArgs < 4) {
376  S.Diag(TheCall->getLocStart(), diag::err_typecheck_call_too_few_args);
377  return true;
378  }
379 
380  Expr *Arg0 = TheCall->getArg(0);
381  Expr *Arg1 = TheCall->getArg(1);
382  Expr *Arg2 = TheCall->getArg(2);
383  Expr *Arg3 = TheCall->getArg(3);
384 
385  // First argument always needs to be a queue_t type.
386  if (!Arg0->getType()->isQueueT()) {
387  S.Diag(TheCall->getArg(0)->getLocStart(),
388  diag::err_opencl_enqueue_kernel_expected_type)
389  << S.Context.OCLQueueTy;
390  return true;
391  }
392 
393  // Second argument always needs to be a kernel_enqueue_flags_t enum value.
394  if (!Arg1->getType()->isIntegerType()) {
395  S.Diag(TheCall->getArg(1)->getLocStart(),
396  diag::err_opencl_enqueue_kernel_expected_type)
397  << "'kernel_enqueue_flags_t' (i.e. uint)";
398  return true;
399  }
400 
401  // Third argument is always an ndrange_t type.
402  if (!Arg2->getType()->isNDRangeT()) {
403  S.Diag(TheCall->getArg(2)->getLocStart(),
404  diag::err_opencl_enqueue_kernel_expected_type)
405  << S.Context.OCLNDRangeTy;
406  return true;
407  }
408 
409  // With four arguments, there is only one form that the function could be
410  // called in: no events and no variable arguments.
411  if (NumArgs == 4) {
412  // check that the last argument is the right block type.
413  if (!isBlockPointer(Arg3)) {
414  S.Diag(Arg3->getLocStart(), diag::err_opencl_enqueue_kernel_expected_type)
415  << "block";
416  return true;
417  }
418  // we have a block type, check the prototype
419  const BlockPointerType *BPT =
420  cast<BlockPointerType>(Arg3->getType().getCanonicalType());
421  if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) {
422  S.Diag(Arg3->getLocStart(),
423  diag::err_opencl_enqueue_kernel_blocks_no_args);
424  return true;
425  }
426  return false;
427  }
428  // we can have block + varargs.
429  if (isBlockPointer(Arg3))
430  return (checkOpenCLBlockArgs(S, Arg3) ||
431  checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
432  // last two cases with either exactly 7 args or 7 args and varargs.
433  if (NumArgs >= 7) {
434  // check common block argument.
435  Expr *Arg6 = TheCall->getArg(6);
436  if (!isBlockPointer(Arg6)) {
437  S.Diag(Arg6->getLocStart(), diag::err_opencl_enqueue_kernel_expected_type)
438  << "block";
439  return true;
440  }
441  if (checkOpenCLBlockArgs(S, Arg6))
442  return true;
443 
444  // Forth argument has to be any integer type.
445  if (!Arg3->getType()->isIntegerType()) {
446  S.Diag(TheCall->getArg(3)->getLocStart(),
447  diag::err_opencl_enqueue_kernel_expected_type)
448  << "integer";
449  return true;
450  }
451  // check remaining common arguments.
452  Expr *Arg4 = TheCall->getArg(4);
453  Expr *Arg5 = TheCall->getArg(5);
454 
455  // Fith argument is always passed as pointers to clk_event_t.
456  if (!Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
457  S.Diag(TheCall->getArg(4)->getLocStart(),
458  diag::err_opencl_enqueue_kernel_expected_type)
460  return true;
461  }
462 
463  // Sixth argument is always passed as pointers to clk_event_t.
464  if (!(Arg5->getType()->isPointerType() &&
465  Arg5->getType()->getPointeeType()->isClkEventT())) {
466  S.Diag(TheCall->getArg(5)->getLocStart(),
467  diag::err_opencl_enqueue_kernel_expected_type)
469  return true;
470  }
471 
472  if (NumArgs == 7)
473  return false;
474 
475  return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
476  }
477 
478  // None of the specific case has been detected, give generic error
479  S.Diag(TheCall->getLocStart(),
480  diag::err_opencl_enqueue_kernel_incorrect_args);
481  return true;
482 }
483 
484 /// Returns OpenCL access qual.
485 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
486  return D->getAttr<OpenCLAccessAttr>();
487 }
488 
489 /// Returns true if pipe element type is different from the pointer.
490 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
491  const Expr *Arg0 = Call->getArg(0);
492  // First argument type should always be pipe.
493  if (!Arg0->getType()->isPipeType()) {
494  S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
495  << Call->getDirectCallee() << Arg0->getSourceRange();
496  return true;
497  }
498  OpenCLAccessAttr *AccessQual =
499  getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
500  // Validates the access qualifier is compatible with the call.
501  // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
502  // read_only and write_only, and assumed to be read_only if no qualifier is
503  // specified.
504  switch (Call->getDirectCallee()->getBuiltinID()) {
505  case Builtin::BIread_pipe:
506  case Builtin::BIreserve_read_pipe:
507  case Builtin::BIcommit_read_pipe:
508  case Builtin::BIwork_group_reserve_read_pipe:
509  case Builtin::BIsub_group_reserve_read_pipe:
510  case Builtin::BIwork_group_commit_read_pipe:
511  case Builtin::BIsub_group_commit_read_pipe:
512  if (!(!AccessQual || AccessQual->isReadOnly())) {
513  S.Diag(Arg0->getLocStart(),
514  diag::err_opencl_builtin_pipe_invalid_access_modifier)
515  << "read_only" << Arg0->getSourceRange();
516  return true;
517  }
518  break;
519  case Builtin::BIwrite_pipe:
520  case Builtin::BIreserve_write_pipe:
521  case Builtin::BIcommit_write_pipe:
522  case Builtin::BIwork_group_reserve_write_pipe:
523  case Builtin::BIsub_group_reserve_write_pipe:
524  case Builtin::BIwork_group_commit_write_pipe:
525  case Builtin::BIsub_group_commit_write_pipe:
526  if (!(AccessQual && AccessQual->isWriteOnly())) {
527  S.Diag(Arg0->getLocStart(),
528  diag::err_opencl_builtin_pipe_invalid_access_modifier)
529  << "write_only" << Arg0->getSourceRange();
530  return true;
531  }
532  break;
533  default:
534  break;
535  }
536  return false;
537 }
538 
539 /// Returns true if pipe element type is different from the pointer.
540 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
541  const Expr *Arg0 = Call->getArg(0);
542  const Expr *ArgIdx = Call->getArg(Idx);
543  const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
544  const QualType EltTy = PipeTy->getElementType();
545  const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
546  // The Idx argument should be a pointer and the type of the pointer and
547  // the type of pipe element should also be the same.
548  if (!ArgTy ||
549  !S.Context.hasSameType(
550  EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
551  S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
552  << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
553  << ArgIdx->getType() << ArgIdx->getSourceRange();
554  return true;
555  }
556  return false;
557 }
558 
559 // \brief Performs semantic analysis for the read/write_pipe call.
560 // \param S Reference to the semantic analyzer.
561 // \param Call A pointer to the builtin call.
562 // \return True if a semantic error has been found, false otherwise.
563 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
564  // OpenCL v2.0 s6.13.16.2 - The built-in read/write
565  // functions have two forms.
566  switch (Call->getNumArgs()) {
567  case 2: {
568  if (checkOpenCLPipeArg(S, Call))
569  return true;
570  // The call with 2 arguments should be
571  // read/write_pipe(pipe T, T*).
572  // Check packet type T.
573  if (checkOpenCLPipePacketType(S, Call, 1))
574  return true;
575  } break;
576 
577  case 4: {
578  if (checkOpenCLPipeArg(S, Call))
579  return true;
580  // The call with 4 arguments should be
581  // read/write_pipe(pipe T, reserve_id_t, uint, T*).
582  // Check reserve_id_t.
583  if (!Call->getArg(1)->getType()->isReserveIDT()) {
584  S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
585  << Call->getDirectCallee() << S.Context.OCLReserveIDTy
586  << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
587  return true;
588  }
589 
590  // Check the index.
591  const Expr *Arg2 = Call->getArg(2);
592  if (!Arg2->getType()->isIntegerType() &&
593  !Arg2->getType()->isUnsignedIntegerType()) {
594  S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
595  << Call->getDirectCallee() << S.Context.UnsignedIntTy
596  << Arg2->getType() << Arg2->getSourceRange();
597  return true;
598  }
599 
600  // Check packet type T.
601  if (checkOpenCLPipePacketType(S, Call, 3))
602  return true;
603  } break;
604  default:
605  S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num)
606  << Call->getDirectCallee() << Call->getSourceRange();
607  return true;
608  }
609 
610  return false;
611 }
612 
613 // \brief Performs a semantic analysis on the {work_group_/sub_group_
614 // /_}reserve_{read/write}_pipe
615 // \param S Reference to the semantic analyzer.
616 // \param Call The call to the builtin function to be analyzed.
617 // \return True if a semantic error was found, false otherwise.
618 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
619  if (checkArgCount(S, Call, 2))
620  return true;
621 
622  if (checkOpenCLPipeArg(S, Call))
623  return true;
624 
625  // Check the reserve size.
626  if (!Call->getArg(1)->getType()->isIntegerType() &&
627  !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
628  S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
629  << Call->getDirectCallee() << S.Context.UnsignedIntTy
630  << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
631  return true;
632  }
633 
634  return false;
635 }
636 
637 // \brief Performs a semantic analysis on {work_group_/sub_group_
638 // /_}commit_{read/write}_pipe
639 // \param S Reference to the semantic analyzer.
640 // \param Call The call to the builtin function to be analyzed.
641 // \return True if a semantic error was found, false otherwise.
642 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
643  if (checkArgCount(S, Call, 2))
644  return true;
645 
646  if (checkOpenCLPipeArg(S, Call))
647  return true;
648 
649  // Check reserve_id_t.
650  if (!Call->getArg(1)->getType()->isReserveIDT()) {
651  S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
652  << Call->getDirectCallee() << S.Context.OCLReserveIDTy
653  << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
654  return true;
655  }
656 
657  return false;
658 }
659 
660 // \brief Performs a semantic analysis on the call to built-in Pipe
661 // Query Functions.
662 // \param S Reference to the semantic analyzer.
663 // \param Call The call to the builtin function to be analyzed.
664 // \return True if a semantic error was found, false otherwise.
665 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
666  if (checkArgCount(S, Call, 1))
667  return true;
668 
669  if (!Call->getArg(0)->getType()->isPipeType()) {
670  S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
671  << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
672  return true;
673  }
674 
675  return false;
676 }
677 // \brief OpenCL v2.0 s6.13.9 - Address space qualifier functions.
678 // \brief Performs semantic analysis for the to_global/local/private call.
679 // \param S Reference to the semantic analyzer.
680 // \param BuiltinID ID of the builtin function.
681 // \param Call A pointer to the builtin call.
682 // \return True if a semantic error has been found, false otherwise.
683 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
684  CallExpr *Call) {
685  if (Call->getNumArgs() != 1) {
686  S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_arg_num)
687  << Call->getDirectCallee() << Call->getSourceRange();
688  return true;
689  }
690 
691  auto RT = Call->getArg(0)->getType();
692  if (!RT->isPointerType() || RT->getPointeeType()
693  .getAddressSpace() == LangAS::opencl_constant) {
694  S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg)
695  << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
696  return true;
697  }
698 
699  RT = RT->getPointeeType();
700  auto Qual = RT.getQualifiers();
701  switch (BuiltinID) {
702  case Builtin::BIto_global:
703  Qual.setAddressSpace(LangAS::opencl_global);
704  break;
705  case Builtin::BIto_local:
706  Qual.setAddressSpace(LangAS::opencl_local);
707  break;
708  default:
709  Qual.removeAddressSpace();
710  }
712  RT.getUnqualifiedType(), Qual)));
713 
714  return false;
715 }
716 
718 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
719  CallExpr *TheCall) {
720  ExprResult TheCallResult(TheCall);
721 
722  // Find out if any arguments are required to be integer constant expressions.
723  unsigned ICEArguments = 0;
725  Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
726  if (Error != ASTContext::GE_None)
727  ICEArguments = 0; // Don't diagnose previously diagnosed errors.
728 
729  // If any arguments are required to be ICE's, check and diagnose.
730  for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
731  // Skip arguments not required to be ICE's.
732  if ((ICEArguments & (1 << ArgNo)) == 0) continue;
733 
734  llvm::APSInt Result;
735  if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
736  return true;
737  ICEArguments &= ~(1 << ArgNo);
738  }
739 
740  switch (BuiltinID) {
741  case Builtin::BI__builtin___CFStringMakeConstantString:
742  assert(TheCall->getNumArgs() == 1 &&
743  "Wrong # arguments to builtin CFStringMakeConstantString");
744  if (CheckObjCString(TheCall->getArg(0)))
745  return ExprError();
746  break;
747  case Builtin::BI__builtin_stdarg_start:
748  case Builtin::BI__builtin_va_start:
749  if (SemaBuiltinVAStart(TheCall))
750  return ExprError();
751  break;
752  case Builtin::BI__va_start: {
753  switch (Context.getTargetInfo().getTriple().getArch()) {
754  case llvm::Triple::arm:
755  case llvm::Triple::thumb:
756  if (SemaBuiltinVAStartARM(TheCall))
757  return ExprError();
758  break;
759  default:
760  if (SemaBuiltinVAStart(TheCall))
761  return ExprError();
762  break;
763  }
764  break;
765  }
766  case Builtin::BI__builtin_isgreater:
767  case Builtin::BI__builtin_isgreaterequal:
768  case Builtin::BI__builtin_isless:
769  case Builtin::BI__builtin_islessequal:
770  case Builtin::BI__builtin_islessgreater:
771  case Builtin::BI__builtin_isunordered:
772  if (SemaBuiltinUnorderedCompare(TheCall))
773  return ExprError();
774  break;
775  case Builtin::BI__builtin_fpclassify:
776  if (SemaBuiltinFPClassification(TheCall, 6))
777  return ExprError();
778  break;
779  case Builtin::BI__builtin_isfinite:
780  case Builtin::BI__builtin_isinf:
781  case Builtin::BI__builtin_isinf_sign:
782  case Builtin::BI__builtin_isnan:
783  case Builtin::BI__builtin_isnormal:
784  if (SemaBuiltinFPClassification(TheCall, 1))
785  return ExprError();
786  break;
787  case Builtin::BI__builtin_shufflevector:
788  return SemaBuiltinShuffleVector(TheCall);
789  // TheCall will be freed by the smart pointer here, but that's fine, since
790  // SemaBuiltinShuffleVector guts it, but then doesn't release it.
791  case Builtin::BI__builtin_prefetch:
792  if (SemaBuiltinPrefetch(TheCall))
793  return ExprError();
794  break;
795  case Builtin::BI__assume:
796  case Builtin::BI__builtin_assume:
797  if (SemaBuiltinAssume(TheCall))
798  return ExprError();
799  break;
800  case Builtin::BI__builtin_assume_aligned:
801  if (SemaBuiltinAssumeAligned(TheCall))
802  return ExprError();
803  break;
804  case Builtin::BI__builtin_object_size:
805  if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
806  return ExprError();
807  break;
808  case Builtin::BI__builtin_longjmp:
809  if (SemaBuiltinLongjmp(TheCall))
810  return ExprError();
811  break;
812  case Builtin::BI__builtin_setjmp:
813  if (SemaBuiltinSetjmp(TheCall))
814  return ExprError();
815  break;
816  case Builtin::BI_setjmp:
817  case Builtin::BI_setjmpex:
818  if (checkArgCount(*this, TheCall, 1))
819  return true;
820  break;
821 
822  case Builtin::BI__builtin_classify_type:
823  if (checkArgCount(*this, TheCall, 1)) return true;
824  TheCall->setType(Context.IntTy);
825  break;
826  case Builtin::BI__builtin_constant_p:
827  if (checkArgCount(*this, TheCall, 1)) return true;
828  TheCall->setType(Context.IntTy);
829  break;
830  case Builtin::BI__sync_fetch_and_add:
831  case Builtin::BI__sync_fetch_and_add_1:
832  case Builtin::BI__sync_fetch_and_add_2:
833  case Builtin::BI__sync_fetch_and_add_4:
834  case Builtin::BI__sync_fetch_and_add_8:
835  case Builtin::BI__sync_fetch_and_add_16:
836  case Builtin::BI__sync_fetch_and_sub:
837  case Builtin::BI__sync_fetch_and_sub_1:
838  case Builtin::BI__sync_fetch_and_sub_2:
839  case Builtin::BI__sync_fetch_and_sub_4:
840  case Builtin::BI__sync_fetch_and_sub_8:
841  case Builtin::BI__sync_fetch_and_sub_16:
842  case Builtin::BI__sync_fetch_and_or:
843  case Builtin::BI__sync_fetch_and_or_1:
844  case Builtin::BI__sync_fetch_and_or_2:
845  case Builtin::BI__sync_fetch_and_or_4:
846  case Builtin::BI__sync_fetch_and_or_8:
847  case Builtin::BI__sync_fetch_and_or_16:
848  case Builtin::BI__sync_fetch_and_and:
849  case Builtin::BI__sync_fetch_and_and_1:
850  case Builtin::BI__sync_fetch_and_and_2:
851  case Builtin::BI__sync_fetch_and_and_4:
852  case Builtin::BI__sync_fetch_and_and_8:
853  case Builtin::BI__sync_fetch_and_and_16:
854  case Builtin::BI__sync_fetch_and_xor:
855  case Builtin::BI__sync_fetch_and_xor_1:
856  case Builtin::BI__sync_fetch_and_xor_2:
857  case Builtin::BI__sync_fetch_and_xor_4:
858  case Builtin::BI__sync_fetch_and_xor_8:
859  case Builtin::BI__sync_fetch_and_xor_16:
860  case Builtin::BI__sync_fetch_and_nand:
861  case Builtin::BI__sync_fetch_and_nand_1:
862  case Builtin::BI__sync_fetch_and_nand_2:
863  case Builtin::BI__sync_fetch_and_nand_4:
864  case Builtin::BI__sync_fetch_and_nand_8:
865  case Builtin::BI__sync_fetch_and_nand_16:
866  case Builtin::BI__sync_add_and_fetch:
867  case Builtin::BI__sync_add_and_fetch_1:
868  case Builtin::BI__sync_add_and_fetch_2:
869  case Builtin::BI__sync_add_and_fetch_4:
870  case Builtin::BI__sync_add_and_fetch_8:
871  case Builtin::BI__sync_add_and_fetch_16:
872  case Builtin::BI__sync_sub_and_fetch:
873  case Builtin::BI__sync_sub_and_fetch_1:
874  case Builtin::BI__sync_sub_and_fetch_2:
875  case Builtin::BI__sync_sub_and_fetch_4:
876  case Builtin::BI__sync_sub_and_fetch_8:
877  case Builtin::BI__sync_sub_and_fetch_16:
878  case Builtin::BI__sync_and_and_fetch:
879  case Builtin::BI__sync_and_and_fetch_1:
880  case Builtin::BI__sync_and_and_fetch_2:
881  case Builtin::BI__sync_and_and_fetch_4:
882  case Builtin::BI__sync_and_and_fetch_8:
883  case Builtin::BI__sync_and_and_fetch_16:
884  case Builtin::BI__sync_or_and_fetch:
885  case Builtin::BI__sync_or_and_fetch_1:
886  case Builtin::BI__sync_or_and_fetch_2:
887  case Builtin::BI__sync_or_and_fetch_4:
888  case Builtin::BI__sync_or_and_fetch_8:
889  case Builtin::BI__sync_or_and_fetch_16:
890  case Builtin::BI__sync_xor_and_fetch:
891  case Builtin::BI__sync_xor_and_fetch_1:
892  case Builtin::BI__sync_xor_and_fetch_2:
893  case Builtin::BI__sync_xor_and_fetch_4:
894  case Builtin::BI__sync_xor_and_fetch_8:
895  case Builtin::BI__sync_xor_and_fetch_16:
896  case Builtin::BI__sync_nand_and_fetch:
897  case Builtin::BI__sync_nand_and_fetch_1:
898  case Builtin::BI__sync_nand_and_fetch_2:
899  case Builtin::BI__sync_nand_and_fetch_4:
900  case Builtin::BI__sync_nand_and_fetch_8:
901  case Builtin::BI__sync_nand_and_fetch_16:
902  case Builtin::BI__sync_val_compare_and_swap:
903  case Builtin::BI__sync_val_compare_and_swap_1:
904  case Builtin::BI__sync_val_compare_and_swap_2:
905  case Builtin::BI__sync_val_compare_and_swap_4:
906  case Builtin::BI__sync_val_compare_and_swap_8:
907  case Builtin::BI__sync_val_compare_and_swap_16:
908  case Builtin::BI__sync_bool_compare_and_swap:
909  case Builtin::BI__sync_bool_compare_and_swap_1:
910  case Builtin::BI__sync_bool_compare_and_swap_2:
911  case Builtin::BI__sync_bool_compare_and_swap_4:
912  case Builtin::BI__sync_bool_compare_and_swap_8:
913  case Builtin::BI__sync_bool_compare_and_swap_16:
914  case Builtin::BI__sync_lock_test_and_set:
915  case Builtin::BI__sync_lock_test_and_set_1:
916  case Builtin::BI__sync_lock_test_and_set_2:
917  case Builtin::BI__sync_lock_test_and_set_4:
918  case Builtin::BI__sync_lock_test_and_set_8:
919  case Builtin::BI__sync_lock_test_and_set_16:
920  case Builtin::BI__sync_lock_release:
921  case Builtin::BI__sync_lock_release_1:
922  case Builtin::BI__sync_lock_release_2:
923  case Builtin::BI__sync_lock_release_4:
924  case Builtin::BI__sync_lock_release_8:
925  case Builtin::BI__sync_lock_release_16:
926  case Builtin::BI__sync_swap:
927  case Builtin::BI__sync_swap_1:
928  case Builtin::BI__sync_swap_2:
929  case Builtin::BI__sync_swap_4:
930  case Builtin::BI__sync_swap_8:
931  case Builtin::BI__sync_swap_16:
932  return SemaBuiltinAtomicOverloaded(TheCallResult);
933  case Builtin::BI__builtin_nontemporal_load:
934  case Builtin::BI__builtin_nontemporal_store:
935  return SemaBuiltinNontemporalOverloaded(TheCallResult);
936 #define BUILTIN(ID, TYPE, ATTRS)
937 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
938  case Builtin::BI##ID: \
939  return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
940 #include "clang/Basic/Builtins.def"
941  case Builtin::BI__builtin_annotation:
942  if (SemaBuiltinAnnotation(*this, TheCall))
943  return ExprError();
944  break;
945  case Builtin::BI__builtin_addressof:
946  if (SemaBuiltinAddressof(*this, TheCall))
947  return ExprError();
948  break;
949  case Builtin::BI__builtin_add_overflow:
950  case Builtin::BI__builtin_sub_overflow:
951  case Builtin::BI__builtin_mul_overflow:
952  if (SemaBuiltinOverflow(*this, TheCall))
953  return ExprError();
954  break;
955  case Builtin::BI__builtin_operator_new:
956  case Builtin::BI__builtin_operator_delete:
957  if (!getLangOpts().CPlusPlus) {
958  Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
959  << (BuiltinID == Builtin::BI__builtin_operator_new
960  ? "__builtin_operator_new"
961  : "__builtin_operator_delete")
962  << "C++";
963  return ExprError();
964  }
965  // CodeGen assumes it can find the global new and delete to call,
966  // so ensure that they are declared.
967  DeclareGlobalNewDelete();
968  break;
969 
970  // check secure string manipulation functions where overflows
971  // are detectable at compile time
972  case Builtin::BI__builtin___memcpy_chk:
973  case Builtin::BI__builtin___memmove_chk:
974  case Builtin::BI__builtin___memset_chk:
975  case Builtin::BI__builtin___strlcat_chk:
976  case Builtin::BI__builtin___strlcpy_chk:
977  case Builtin::BI__builtin___strncat_chk:
978  case Builtin::BI__builtin___strncpy_chk:
979  case Builtin::BI__builtin___stpncpy_chk:
980  SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
981  break;
982  case Builtin::BI__builtin___memccpy_chk:
983  SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
984  break;
985  case Builtin::BI__builtin___snprintf_chk:
986  case Builtin::BI__builtin___vsnprintf_chk:
987  SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
988  break;
989  case Builtin::BI__builtin_call_with_static_chain:
990  if (SemaBuiltinCallWithStaticChain(*this, TheCall))
991  return ExprError();
992  break;
993  case Builtin::BI__exception_code:
994  case Builtin::BI_exception_code:
996  diag::err_seh___except_block))
997  return ExprError();
998  break;
999  case Builtin::BI__exception_info:
1000  case Builtin::BI_exception_info:
1001  if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1002  diag::err_seh___except_filter))
1003  return ExprError();
1004  break;
1005  case Builtin::BI__GetExceptionInfo:
1006  if (checkArgCount(*this, TheCall, 1))
1007  return ExprError();
1008 
1009  if (CheckCXXThrowOperand(
1010  TheCall->getLocStart(),
1012  TheCall))
1013  return ExprError();
1014 
1015  TheCall->setType(Context.VoidPtrTy);
1016  break;
1017  // OpenCL v2.0, s6.13.16 - Pipe functions
1018  case Builtin::BIread_pipe:
1019  case Builtin::BIwrite_pipe:
1020  // Since those two functions are declared with var args, we need a semantic
1021  // check for the argument.
1022  if (SemaBuiltinRWPipe(*this, TheCall))
1023  return ExprError();
1024  break;
1025  case Builtin::BIreserve_read_pipe:
1026  case Builtin::BIreserve_write_pipe:
1027  case Builtin::BIwork_group_reserve_read_pipe:
1028  case Builtin::BIwork_group_reserve_write_pipe:
1029  case Builtin::BIsub_group_reserve_read_pipe:
1030  case Builtin::BIsub_group_reserve_write_pipe:
1031  if (SemaBuiltinReserveRWPipe(*this, TheCall))
1032  return ExprError();
1033  // Since return type of reserve_read/write_pipe built-in function is
1034  // reserve_id_t, which is not defined in the builtin def file , we used int
1035  // as return type and need to override the return type of these functions.
1036  TheCall->setType(Context.OCLReserveIDTy);
1037  break;
1038  case Builtin::BIcommit_read_pipe:
1039  case Builtin::BIcommit_write_pipe:
1040  case Builtin::BIwork_group_commit_read_pipe:
1041  case Builtin::BIwork_group_commit_write_pipe:
1042  case Builtin::BIsub_group_commit_read_pipe:
1043  case Builtin::BIsub_group_commit_write_pipe:
1044  if (SemaBuiltinCommitRWPipe(*this, TheCall))
1045  return ExprError();
1046  break;
1047  case Builtin::BIget_pipe_num_packets:
1048  case Builtin::BIget_pipe_max_packets:
1049  if (SemaBuiltinPipePackets(*this, TheCall))
1050  return ExprError();
1051  break;
1052  case Builtin::BIto_global:
1053  case Builtin::BIto_local:
1054  case Builtin::BIto_private:
1055  if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1056  return ExprError();
1057  break;
1058  // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1059  case Builtin::BIenqueue_kernel:
1060  if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1061  return ExprError();
1062  break;
1063  case Builtin::BIget_kernel_work_group_size:
1064  case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1065  if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1066  return ExprError();
1067  }
1068 
1069  // Since the target specific builtins for each arch overlap, only check those
1070  // of the arch we are compiling for.
1071  if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
1072  switch (Context.getTargetInfo().getTriple().getArch()) {
1073  case llvm::Triple::arm:
1074  case llvm::Triple::armeb:
1075  case llvm::Triple::thumb:
1076  case llvm::Triple::thumbeb:
1077  if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1078  return ExprError();
1079  break;
1080  case llvm::Triple::aarch64:
1081  case llvm::Triple::aarch64_be:
1082  if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
1083  return ExprError();
1084  break;
1085  case llvm::Triple::mips:
1086  case llvm::Triple::mipsel:
1087  case llvm::Triple::mips64:
1088  case llvm::Triple::mips64el:
1089  if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1090  return ExprError();
1091  break;
1092  case llvm::Triple::systemz:
1093  if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1094  return ExprError();
1095  break;
1096  case llvm::Triple::x86:
1097  case llvm::Triple::x86_64:
1098  if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1099  return ExprError();
1100  break;
1101  case llvm::Triple::ppc:
1102  case llvm::Triple::ppc64:
1103  case llvm::Triple::ppc64le:
1104  if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1105  return ExprError();
1106  break;
1107  default:
1108  break;
1109  }
1110  }
1111 
1112  return TheCallResult;
1113 }
1114 
1115 // Get the valid immediate range for the specified NEON type code.
1116 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
1117  NeonTypeFlags Type(t);
1118  int IsQuad = ForceQuad ? true : Type.isQuad();
1119  switch (Type.getEltType()) {
1120  case NeonTypeFlags::Int8:
1121  case NeonTypeFlags::Poly8:
1122  return shift ? 7 : (8 << IsQuad) - 1;
1123  case NeonTypeFlags::Int16:
1124  case NeonTypeFlags::Poly16:
1125  return shift ? 15 : (4 << IsQuad) - 1;
1126  case NeonTypeFlags::Int32:
1127  return shift ? 31 : (2 << IsQuad) - 1;
1128  case NeonTypeFlags::Int64:
1129  case NeonTypeFlags::Poly64:
1130  return shift ? 63 : (1 << IsQuad) - 1;
1132  return shift ? 127 : (1 << IsQuad) - 1;
1134  assert(!shift && "cannot shift float types!");
1135  return (4 << IsQuad) - 1;
1137  assert(!shift && "cannot shift float types!");
1138  return (2 << IsQuad) - 1;
1140  assert(!shift && "cannot shift float types!");
1141  return (1 << IsQuad) - 1;
1142  }
1143  llvm_unreachable("Invalid NeonTypeFlag!");
1144 }
1145 
1146 /// getNeonEltType - Return the QualType corresponding to the elements of
1147 /// the vector type specified by the NeonTypeFlags. This is used to check
1148 /// the pointer arguments for Neon load/store intrinsics.
1150  bool IsPolyUnsigned, bool IsInt64Long) {
1151  switch (Flags.getEltType()) {
1152  case NeonTypeFlags::Int8:
1153  return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1154  case NeonTypeFlags::Int16:
1155  return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1156  case NeonTypeFlags::Int32:
1157  return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1158  case NeonTypeFlags::Int64:
1159  if (IsInt64Long)
1160  return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1161  else
1162  return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1163  : Context.LongLongTy;
1164  case NeonTypeFlags::Poly8:
1165  return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
1166  case NeonTypeFlags::Poly16:
1167  return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
1168  case NeonTypeFlags::Poly64:
1169  if (IsInt64Long)
1170  return Context.UnsignedLongTy;
1171  else
1172  return Context.UnsignedLongLongTy;
1174  break;
1176  return Context.HalfTy;
1178  return Context.FloatTy;
1180  return Context.DoubleTy;
1181  }
1182  llvm_unreachable("Invalid NeonTypeFlag!");
1183 }
1184 
1185 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1186  llvm::APSInt Result;
1187  uint64_t mask = 0;
1188  unsigned TV = 0;
1189  int PtrArgNum = -1;
1190  bool HasConstPtr = false;
1191  switch (BuiltinID) {
1192 #define GET_NEON_OVERLOAD_CHECK
1193 #include "clang/Basic/arm_neon.inc"
1194 #undef GET_NEON_OVERLOAD_CHECK
1195  }
1196 
1197  // For NEON intrinsics which are overloaded on vector element type, validate
1198  // the immediate which specifies which variant to emit.
1199  unsigned ImmArg = TheCall->getNumArgs()-1;
1200  if (mask) {
1201  if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1202  return true;
1203 
1204  TV = Result.getLimitedValue(64);
1205  if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1206  return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
1207  << TheCall->getArg(ImmArg)->getSourceRange();
1208  }
1209 
1210  if (PtrArgNum >= 0) {
1211  // Check that pointer arguments have the specified type.
1212  Expr *Arg = TheCall->getArg(PtrArgNum);
1213  if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1214  Arg = ICE->getSubExpr();
1215  ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1216  QualType RHSTy = RHS.get()->getType();
1217 
1218  llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
1219  bool IsPolyUnsigned = Arch == llvm::Triple::aarch64;
1220  bool IsInt64Long =
1222  QualType EltTy =
1223  getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
1224  if (HasConstPtr)
1225  EltTy = EltTy.withConst();
1226  QualType LHSTy = Context.getPointerType(EltTy);
1227  AssignConvertType ConvTy;
1228  ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1229  if (RHS.isInvalid())
1230  return true;
1231  if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
1232  RHS.get(), AA_Assigning))
1233  return true;
1234  }
1235 
1236  // For NEON intrinsics which take an immediate value as part of the
1237  // instruction, range check them here.
1238  unsigned i = 0, l = 0, u = 0;
1239  switch (BuiltinID) {
1240  default:
1241  return false;
1242 #define GET_NEON_IMMEDIATE_CHECK
1243 #include "clang/Basic/arm_neon.inc"
1244 #undef GET_NEON_IMMEDIATE_CHECK
1245  }
1246 
1247  return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1248 }
1249 
1250 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1251  unsigned MaxWidth) {
1252  assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
1253  BuiltinID == ARM::BI__builtin_arm_ldaex ||
1254  BuiltinID == ARM::BI__builtin_arm_strex ||
1255  BuiltinID == ARM::BI__builtin_arm_stlex ||
1256  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1257  BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1258  BuiltinID == AArch64::BI__builtin_arm_strex ||
1259  BuiltinID == AArch64::BI__builtin_arm_stlex) &&
1260  "unexpected ARM builtin");
1261  bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
1262  BuiltinID == ARM::BI__builtin_arm_ldaex ||
1263  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1264  BuiltinID == AArch64::BI__builtin_arm_ldaex;
1265 
1266  DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1267 
1268  // Ensure that we have the proper number of arguments.
1269  if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1270  return true;
1271 
1272  // Inspect the pointer argument of the atomic builtin. This should always be
1273  // a pointer type, whose element is an integral scalar or pointer type.
1274  // Because it is a pointer type, we don't have to worry about any implicit
1275  // casts here.
1276  Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1277  ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1278  if (PointerArgRes.isInvalid())
1279  return true;
1280  PointerArg = PointerArgRes.get();
1281 
1282  const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1283  if (!pointerType) {
1284  Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1285  << PointerArg->getType() << PointerArg->getSourceRange();
1286  return true;
1287  }
1288 
1289  // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1290  // task is to insert the appropriate casts into the AST. First work out just
1291  // what the appropriate type is.
1292  QualType ValType = pointerType->getPointeeType();
1293  QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1294  if (IsLdrex)
1295  AddrType.addConst();
1296 
1297  // Issue a warning if the cast is dodgy.
1298  CastKind CastNeeded = CK_NoOp;
1299  if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1300  CastNeeded = CK_BitCast;
1301  Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
1302  << PointerArg->getType()
1303  << Context.getPointerType(AddrType)
1304  << AA_Passing << PointerArg->getSourceRange();
1305  }
1306 
1307  // Finally, do the cast and replace the argument with the corrected version.
1308  AddrType = Context.getPointerType(AddrType);
1309  PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1310  if (PointerArgRes.isInvalid())
1311  return true;
1312  PointerArg = PointerArgRes.get();
1313 
1314  TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1315 
1316  // In general, we allow ints, floats and pointers to be loaded and stored.
1317  if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1318  !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1319  Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1320  << PointerArg->getType() << PointerArg->getSourceRange();
1321  return true;
1322  }
1323 
1324  // But ARM doesn't have instructions to deal with 128-bit versions.
1325  if (Context.getTypeSize(ValType) > MaxWidth) {
1326  assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
1327  Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
1328  << PointerArg->getType() << PointerArg->getSourceRange();
1329  return true;
1330  }
1331 
1332  switch (ValType.getObjCLifetime()) {
1333  case Qualifiers::OCL_None:
1335  // okay
1336  break;
1337 
1338  case Qualifiers::OCL_Weak:
1341  Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1342  << ValType << PointerArg->getSourceRange();
1343  return true;
1344  }
1345 
1346  if (IsLdrex) {
1347  TheCall->setType(ValType);
1348  return false;
1349  }
1350 
1351  // Initialize the argument to be stored.
1352  ExprResult ValArg = TheCall->getArg(0);
1354  Context, ValType, /*consume*/ false);
1355  ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1356  if (ValArg.isInvalid())
1357  return true;
1358  TheCall->setArg(0, ValArg.get());
1359 
1360  // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1361  // but the custom checker bypasses all default analysis.
1362  TheCall->setType(Context.IntTy);
1363  return false;
1364 }
1365 
1366 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1367  llvm::APSInt Result;
1368 
1369  if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
1370  BuiltinID == ARM::BI__builtin_arm_ldaex ||
1371  BuiltinID == ARM::BI__builtin_arm_strex ||
1372  BuiltinID == ARM::BI__builtin_arm_stlex) {
1373  return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
1374  }
1375 
1376  if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1377  return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1378  SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1379  }
1380 
1381  if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1382  BuiltinID == ARM::BI__builtin_arm_wsr64)
1383  return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1384 
1385  if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1386  BuiltinID == ARM::BI__builtin_arm_rsrp ||
1387  BuiltinID == ARM::BI__builtin_arm_wsr ||
1388  BuiltinID == ARM::BI__builtin_arm_wsrp)
1389  return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1390 
1391  if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1392  return true;
1393 
1394  // For intrinsics which take an immediate value as part of the instruction,
1395  // range check them here.
1396  unsigned i = 0, l = 0, u = 0;
1397  switch (BuiltinID) {
1398  default: return false;
1399  case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
1400  case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
1401  case ARM::BI__builtin_arm_vcvtr_f:
1402  case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
1403  case ARM::BI__builtin_arm_dmb:
1404  case ARM::BI__builtin_arm_dsb:
1405  case ARM::BI__builtin_arm_isb:
1406  case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
1407  }
1408 
1409  // FIXME: VFP Intrinsics should error if VFP not present.
1410  return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1411 }
1412 
1413 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
1414  CallExpr *TheCall) {
1415  llvm::APSInt Result;
1416 
1417  if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1418  BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1419  BuiltinID == AArch64::BI__builtin_arm_strex ||
1420  BuiltinID == AArch64::BI__builtin_arm_stlex) {
1421  return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1422  }
1423 
1424  if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1425  return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1426  SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1427  SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1428  SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1429  }
1430 
1431  if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1432  BuiltinID == AArch64::BI__builtin_arm_wsr64)
1433  return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1434 
1435  if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1436  BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1437  BuiltinID == AArch64::BI__builtin_arm_wsr ||
1438  BuiltinID == AArch64::BI__builtin_arm_wsrp)
1439  return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1440 
1441  if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1442  return true;
1443 
1444  // For intrinsics which take an immediate value as part of the instruction,
1445  // range check them here.
1446  unsigned i = 0, l = 0, u = 0;
1447  switch (BuiltinID) {
1448  default: return false;
1449  case AArch64::BI__builtin_arm_dmb:
1450  case AArch64::BI__builtin_arm_dsb:
1451  case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1452  }
1453 
1454  return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1455 }
1456 
1457 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1458  unsigned i = 0, l = 0, u = 0;
1459  switch (BuiltinID) {
1460  default: return false;
1461  case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
1462  case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
1463  case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
1464  case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
1465  case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
1466  case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
1467  case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
1468  }
1469 
1470  return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1471 }
1472 
1473 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1474  unsigned i = 0, l = 0, u = 0;
1475  bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
1476  BuiltinID == PPC::BI__builtin_divdeu ||
1477  BuiltinID == PPC::BI__builtin_bpermd;
1478  bool IsTarget64Bit = Context.getTargetInfo()
1480  .getTargetInfo()
1481  .getIntPtrType()) == 64;
1482  bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
1483  BuiltinID == PPC::BI__builtin_divweu ||
1484  BuiltinID == PPC::BI__builtin_divde ||
1485  BuiltinID == PPC::BI__builtin_divdeu;
1486 
1487  if (Is64BitBltin && !IsTarget64Bit)
1488  return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
1489  << TheCall->getSourceRange();
1490 
1491  if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
1492  (BuiltinID == PPC::BI__builtin_bpermd &&
1493  !Context.getTargetInfo().hasFeature("bpermd")))
1494  return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
1495  << TheCall->getSourceRange();
1496 
1497  switch (BuiltinID) {
1498  default: return false;
1499  case PPC::BI__builtin_altivec_crypto_vshasigmaw:
1500  case PPC::BI__builtin_altivec_crypto_vshasigmad:
1501  return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1502  SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1503  case PPC::BI__builtin_tbegin:
1504  case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
1505  case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
1506  case PPC::BI__builtin_tabortwc:
1507  case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
1508  case PPC::BI__builtin_tabortwci:
1509  case PPC::BI__builtin_tabortdci:
1510  return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
1511  SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
1512  }
1513  return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1514 }
1515 
1516 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
1517  CallExpr *TheCall) {
1518  if (BuiltinID == SystemZ::BI__builtin_tabort) {
1519  Expr *Arg = TheCall->getArg(0);
1520  llvm::APSInt AbortCode(32);
1521  if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
1522  AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
1523  return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
1524  << Arg->getSourceRange();
1525  }
1526 
1527  // For intrinsics which take an immediate value as part of the instruction,
1528  // range check them here.
1529  unsigned i = 0, l = 0, u = 0;
1530  switch (BuiltinID) {
1531  default: return false;
1532  case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
1533  case SystemZ::BI__builtin_s390_verimb:
1534  case SystemZ::BI__builtin_s390_verimh:
1535  case SystemZ::BI__builtin_s390_verimf:
1536  case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
1537  case SystemZ::BI__builtin_s390_vfaeb:
1538  case SystemZ::BI__builtin_s390_vfaeh:
1539  case SystemZ::BI__builtin_s390_vfaef:
1540  case SystemZ::BI__builtin_s390_vfaebs:
1541  case SystemZ::BI__builtin_s390_vfaehs:
1542  case SystemZ::BI__builtin_s390_vfaefs:
1543  case SystemZ::BI__builtin_s390_vfaezb:
1544  case SystemZ::BI__builtin_s390_vfaezh:
1545  case SystemZ::BI__builtin_s390_vfaezf:
1546  case SystemZ::BI__builtin_s390_vfaezbs:
1547  case SystemZ::BI__builtin_s390_vfaezhs:
1548  case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
1549  case SystemZ::BI__builtin_s390_vfidb:
1550  return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1551  SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1552  case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
1553  case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
1554  case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
1555  case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
1556  case SystemZ::BI__builtin_s390_vstrcb:
1557  case SystemZ::BI__builtin_s390_vstrch:
1558  case SystemZ::BI__builtin_s390_vstrcf:
1559  case SystemZ::BI__builtin_s390_vstrczb:
1560  case SystemZ::BI__builtin_s390_vstrczh:
1561  case SystemZ::BI__builtin_s390_vstrczf:
1562  case SystemZ::BI__builtin_s390_vstrcbs:
1563  case SystemZ::BI__builtin_s390_vstrchs:
1564  case SystemZ::BI__builtin_s390_vstrcfs:
1565  case SystemZ::BI__builtin_s390_vstrczbs:
1566  case SystemZ::BI__builtin_s390_vstrczhs:
1567  case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
1568  }
1569  return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1570 }
1571 
1572 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
1573 /// This checks that the target supports __builtin_cpu_supports and
1574 /// that the string argument is constant and valid.
1575 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
1576  Expr *Arg = TheCall->getArg(0);
1577 
1578  // Check if the argument is a string literal.
1579  if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1580  return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1581  << Arg->getSourceRange();
1582 
1583  // Check the contents of the string.
1584  StringRef Feature =
1585  cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1586  if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
1587  return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
1588  << Arg->getSourceRange();
1589  return false;
1590 }
1591 
1592 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1593  int i = 0, l = 0, u = 0;
1594  switch (BuiltinID) {
1595  default:
1596  return false;
1597  case X86::BI__builtin_cpu_supports:
1598  return SemaBuiltinCpuSupports(*this, TheCall);
1599  case X86::BI__builtin_ms_va_start:
1600  return SemaBuiltinMSVAStart(TheCall);
1601  case X86::BI__builtin_ia32_extractf64x4_mask:
1602  case X86::BI__builtin_ia32_extracti64x4_mask:
1603  case X86::BI__builtin_ia32_extractf32x8_mask:
1604  case X86::BI__builtin_ia32_extracti32x8_mask:
1605  case X86::BI__builtin_ia32_extractf64x2_256_mask:
1606  case X86::BI__builtin_ia32_extracti64x2_256_mask:
1607  case X86::BI__builtin_ia32_extractf32x4_256_mask:
1608  case X86::BI__builtin_ia32_extracti32x4_256_mask:
1609  i = 1; l = 0; u = 1;
1610  break;
1611  case X86::BI_mm_prefetch:
1612  case X86::BI__builtin_ia32_extractf32x4_mask:
1613  case X86::BI__builtin_ia32_extracti32x4_mask:
1614  case X86::BI__builtin_ia32_extractf64x2_512_mask:
1615  case X86::BI__builtin_ia32_extracti64x2_512_mask:
1616  i = 1; l = 0; u = 3;
1617  break;
1618  case X86::BI__builtin_ia32_insertf32x8_mask:
1619  case X86::BI__builtin_ia32_inserti32x8_mask:
1620  case X86::BI__builtin_ia32_insertf64x4_mask:
1621  case X86::BI__builtin_ia32_inserti64x4_mask:
1622  case X86::BI__builtin_ia32_insertf64x2_256_mask:
1623  case X86::BI__builtin_ia32_inserti64x2_256_mask:
1624  case X86::BI__builtin_ia32_insertf32x4_256_mask:
1625  case X86::BI__builtin_ia32_inserti32x4_256_mask:
1626  i = 2; l = 0; u = 1;
1627  break;
1628  case X86::BI__builtin_ia32_sha1rnds4:
1629  case X86::BI__builtin_ia32_shuf_f32x4_256_mask:
1630  case X86::BI__builtin_ia32_shuf_f64x2_256_mask:
1631  case X86::BI__builtin_ia32_shuf_i32x4_256_mask:
1632  case X86::BI__builtin_ia32_shuf_i64x2_256_mask:
1633  case X86::BI__builtin_ia32_insertf64x2_512_mask:
1634  case X86::BI__builtin_ia32_inserti64x2_512_mask:
1635  case X86::BI__builtin_ia32_insertf32x4_mask:
1636  case X86::BI__builtin_ia32_inserti32x4_mask:
1637  i = 2; l = 0; u = 3;
1638  break;
1639  case X86::BI__builtin_ia32_vpermil2pd:
1640  case X86::BI__builtin_ia32_vpermil2pd256:
1641  case X86::BI__builtin_ia32_vpermil2ps:
1642  case X86::BI__builtin_ia32_vpermil2ps256:
1643  i = 3; l = 0; u = 3;
1644  break;
1645  case X86::BI__builtin_ia32_cmpb128_mask:
1646  case X86::BI__builtin_ia32_cmpw128_mask:
1647  case X86::BI__builtin_ia32_cmpd128_mask:
1648  case X86::BI__builtin_ia32_cmpq128_mask:
1649  case X86::BI__builtin_ia32_cmpb256_mask:
1650  case X86::BI__builtin_ia32_cmpw256_mask:
1651  case X86::BI__builtin_ia32_cmpd256_mask:
1652  case X86::BI__builtin_ia32_cmpq256_mask:
1653  case X86::BI__builtin_ia32_cmpb512_mask:
1654  case X86::BI__builtin_ia32_cmpw512_mask:
1655  case X86::BI__builtin_ia32_cmpd512_mask:
1656  case X86::BI__builtin_ia32_cmpq512_mask:
1657  case X86::BI__builtin_ia32_ucmpb128_mask:
1658  case X86::BI__builtin_ia32_ucmpw128_mask:
1659  case X86::BI__builtin_ia32_ucmpd128_mask:
1660  case X86::BI__builtin_ia32_ucmpq128_mask:
1661  case X86::BI__builtin_ia32_ucmpb256_mask:
1662  case X86::BI__builtin_ia32_ucmpw256_mask:
1663  case X86::BI__builtin_ia32_ucmpd256_mask:
1664  case X86::BI__builtin_ia32_ucmpq256_mask:
1665  case X86::BI__builtin_ia32_ucmpb512_mask:
1666  case X86::BI__builtin_ia32_ucmpw512_mask:
1667  case X86::BI__builtin_ia32_ucmpd512_mask:
1668  case X86::BI__builtin_ia32_ucmpq512_mask:
1669  case X86::BI__builtin_ia32_vpcomub:
1670  case X86::BI__builtin_ia32_vpcomuw:
1671  case X86::BI__builtin_ia32_vpcomud:
1672  case X86::BI__builtin_ia32_vpcomuq:
1673  case X86::BI__builtin_ia32_vpcomb:
1674  case X86::BI__builtin_ia32_vpcomw:
1675  case X86::BI__builtin_ia32_vpcomd:
1676  case X86::BI__builtin_ia32_vpcomq:
1677  i = 2; l = 0; u = 7;
1678  break;
1679  case X86::BI__builtin_ia32_roundps:
1680  case X86::BI__builtin_ia32_roundpd:
1681  case X86::BI__builtin_ia32_roundps256:
1682  case X86::BI__builtin_ia32_roundpd256:
1683  i = 1; l = 0; u = 15;
1684  break;
1685  case X86::BI__builtin_ia32_roundss:
1686  case X86::BI__builtin_ia32_roundsd:
1687  case X86::BI__builtin_ia32_rangepd128_mask:
1688  case X86::BI__builtin_ia32_rangepd256_mask:
1689  case X86::BI__builtin_ia32_rangepd512_mask:
1690  case X86::BI__builtin_ia32_rangeps128_mask:
1691  case X86::BI__builtin_ia32_rangeps256_mask:
1692  case X86::BI__builtin_ia32_rangeps512_mask:
1693  case X86::BI__builtin_ia32_getmantsd_round_mask:
1694  case X86::BI__builtin_ia32_getmantss_round_mask:
1695  i = 2; l = 0; u = 15;
1696  break;
1697  case X86::BI__builtin_ia32_cmpps:
1698  case X86::BI__builtin_ia32_cmpss:
1699  case X86::BI__builtin_ia32_cmppd:
1700  case X86::BI__builtin_ia32_cmpsd:
1701  case X86::BI__builtin_ia32_cmpps256:
1702  case X86::BI__builtin_ia32_cmppd256:
1703  case X86::BI__builtin_ia32_cmpps128_mask:
1704  case X86::BI__builtin_ia32_cmppd128_mask:
1705  case X86::BI__builtin_ia32_cmpps256_mask:
1706  case X86::BI__builtin_ia32_cmppd256_mask:
1707  case X86::BI__builtin_ia32_cmpps512_mask:
1708  case X86::BI__builtin_ia32_cmppd512_mask:
1709  case X86::BI__builtin_ia32_cmpsd_mask:
1710  case X86::BI__builtin_ia32_cmpss_mask:
1711  i = 2; l = 0; u = 31;
1712  break;
1713  case X86::BI__builtin_ia32_xabort:
1714  i = 0; l = -128; u = 255;
1715  break;
1716  case X86::BI__builtin_ia32_pshufw:
1717  case X86::BI__builtin_ia32_aeskeygenassist128:
1718  i = 1; l = -128; u = 255;
1719  break;
1720  case X86::BI__builtin_ia32_vcvtps2ph:
1721  case X86::BI__builtin_ia32_vcvtps2ph256:
1722  case X86::BI__builtin_ia32_rndscaleps_128_mask:
1723  case X86::BI__builtin_ia32_rndscalepd_128_mask:
1724  case X86::BI__builtin_ia32_rndscaleps_256_mask:
1725  case X86::BI__builtin_ia32_rndscalepd_256_mask:
1726  case X86::BI__builtin_ia32_rndscaleps_mask:
1727  case X86::BI__builtin_ia32_rndscalepd_mask:
1728  case X86::BI__builtin_ia32_reducepd128_mask:
1729  case X86::BI__builtin_ia32_reducepd256_mask:
1730  case X86::BI__builtin_ia32_reducepd512_mask:
1731  case X86::BI__builtin_ia32_reduceps128_mask:
1732  case X86::BI__builtin_ia32_reduceps256_mask:
1733  case X86::BI__builtin_ia32_reduceps512_mask:
1734  case X86::BI__builtin_ia32_prold512_mask:
1735  case X86::BI__builtin_ia32_prolq512_mask:
1736  case X86::BI__builtin_ia32_prold128_mask:
1737  case X86::BI__builtin_ia32_prold256_mask:
1738  case X86::BI__builtin_ia32_prolq128_mask:
1739  case X86::BI__builtin_ia32_prolq256_mask:
1740  case X86::BI__builtin_ia32_prord128_mask:
1741  case X86::BI__builtin_ia32_prord256_mask:
1742  case X86::BI__builtin_ia32_prorq128_mask:
1743  case X86::BI__builtin_ia32_prorq256_mask:
1744  case X86::BI__builtin_ia32_psllwi512_mask:
1745  case X86::BI__builtin_ia32_psllwi128_mask:
1746  case X86::BI__builtin_ia32_psllwi256_mask:
1747  case X86::BI__builtin_ia32_psrldi128_mask:
1748  case X86::BI__builtin_ia32_psrldi256_mask:
1749  case X86::BI__builtin_ia32_psrldi512_mask:
1750  case X86::BI__builtin_ia32_psrlqi128_mask:
1751  case X86::BI__builtin_ia32_psrlqi256_mask:
1752  case X86::BI__builtin_ia32_psrlqi512_mask:
1753  case X86::BI__builtin_ia32_psrawi512_mask:
1754  case X86::BI__builtin_ia32_psrawi128_mask:
1755  case X86::BI__builtin_ia32_psrawi256_mask:
1756  case X86::BI__builtin_ia32_psrlwi512_mask:
1757  case X86::BI__builtin_ia32_psrlwi128_mask:
1758  case X86::BI__builtin_ia32_psrlwi256_mask:
1759  case X86::BI__builtin_ia32_psradi128_mask:
1760  case X86::BI__builtin_ia32_psradi256_mask:
1761  case X86::BI__builtin_ia32_psradi512_mask:
1762  case X86::BI__builtin_ia32_psraqi128_mask:
1763  case X86::BI__builtin_ia32_psraqi256_mask:
1764  case X86::BI__builtin_ia32_psraqi512_mask:
1765  case X86::BI__builtin_ia32_pslldi128_mask:
1766  case X86::BI__builtin_ia32_pslldi256_mask:
1767  case X86::BI__builtin_ia32_pslldi512_mask:
1768  case X86::BI__builtin_ia32_psllqi128_mask:
1769  case X86::BI__builtin_ia32_psllqi256_mask:
1770  case X86::BI__builtin_ia32_psllqi512_mask:
1771  case X86::BI__builtin_ia32_fpclasspd128_mask:
1772  case X86::BI__builtin_ia32_fpclasspd256_mask:
1773  case X86::BI__builtin_ia32_fpclassps128_mask:
1774  case X86::BI__builtin_ia32_fpclassps256_mask:
1775  case X86::BI__builtin_ia32_fpclassps512_mask:
1776  case X86::BI__builtin_ia32_fpclasspd512_mask:
1777  case X86::BI__builtin_ia32_fpclasssd_mask:
1778  case X86::BI__builtin_ia32_fpclassss_mask:
1779  i = 1; l = 0; u = 255;
1780  break;
1781  case X86::BI__builtin_ia32_palignr:
1782  case X86::BI__builtin_ia32_insertps128:
1783  case X86::BI__builtin_ia32_dpps:
1784  case X86::BI__builtin_ia32_dppd:
1785  case X86::BI__builtin_ia32_dpps256:
1786  case X86::BI__builtin_ia32_mpsadbw128:
1787  case X86::BI__builtin_ia32_mpsadbw256:
1788  case X86::BI__builtin_ia32_pcmpistrm128:
1789  case X86::BI__builtin_ia32_pcmpistri128:
1790  case X86::BI__builtin_ia32_pcmpistria128:
1791  case X86::BI__builtin_ia32_pcmpistric128:
1792  case X86::BI__builtin_ia32_pcmpistrio128:
1793  case X86::BI__builtin_ia32_pcmpistris128:
1794  case X86::BI__builtin_ia32_pcmpistriz128:
1795  case X86::BI__builtin_ia32_pclmulqdq128:
1796  case X86::BI__builtin_ia32_vperm2f128_pd256:
1797  case X86::BI__builtin_ia32_vperm2f128_ps256:
1798  case X86::BI__builtin_ia32_vperm2f128_si256:
1799  case X86::BI__builtin_ia32_permti256:
1800  i = 2; l = -128; u = 255;
1801  break;
1802  case X86::BI__builtin_ia32_palignr128:
1803  case X86::BI__builtin_ia32_palignr256:
1804  case X86::BI__builtin_ia32_palignr128_mask:
1805  case X86::BI__builtin_ia32_palignr256_mask:
1806  case X86::BI__builtin_ia32_palignr512_mask:
1807  case X86::BI__builtin_ia32_alignq512_mask:
1808  case X86::BI__builtin_ia32_alignd512_mask:
1809  case X86::BI__builtin_ia32_alignd128_mask:
1810  case X86::BI__builtin_ia32_alignd256_mask:
1811  case X86::BI__builtin_ia32_alignq128_mask:
1812  case X86::BI__builtin_ia32_alignq256_mask:
1813  case X86::BI__builtin_ia32_vcomisd:
1814  case X86::BI__builtin_ia32_vcomiss:
1815  case X86::BI__builtin_ia32_shuf_f32x4_mask:
1816  case X86::BI__builtin_ia32_shuf_f64x2_mask:
1817  case X86::BI__builtin_ia32_shuf_i32x4_mask:
1818  case X86::BI__builtin_ia32_shuf_i64x2_mask:
1819  case X86::BI__builtin_ia32_dbpsadbw128_mask:
1820  case X86::BI__builtin_ia32_dbpsadbw256_mask:
1821  case X86::BI__builtin_ia32_dbpsadbw512_mask:
1822  i = 2; l = 0; u = 255;
1823  break;
1824  case X86::BI__builtin_ia32_fixupimmpd512_mask:
1825  case X86::BI__builtin_ia32_fixupimmpd512_maskz:
1826  case X86::BI__builtin_ia32_fixupimmps512_mask:
1827  case X86::BI__builtin_ia32_fixupimmps512_maskz:
1828  case X86::BI__builtin_ia32_fixupimmsd_mask:
1829  case X86::BI__builtin_ia32_fixupimmsd_maskz:
1830  case X86::BI__builtin_ia32_fixupimmss_mask:
1831  case X86::BI__builtin_ia32_fixupimmss_maskz:
1832  case X86::BI__builtin_ia32_fixupimmpd128_mask:
1833  case X86::BI__builtin_ia32_fixupimmpd128_maskz:
1834  case X86::BI__builtin_ia32_fixupimmpd256_mask:
1835  case X86::BI__builtin_ia32_fixupimmpd256_maskz:
1836  case X86::BI__builtin_ia32_fixupimmps128_mask:
1837  case X86::BI__builtin_ia32_fixupimmps128_maskz:
1838  case X86::BI__builtin_ia32_fixupimmps256_mask:
1839  case X86::BI__builtin_ia32_fixupimmps256_maskz:
1840  case X86::BI__builtin_ia32_pternlogd512_mask:
1841  case X86::BI__builtin_ia32_pternlogd512_maskz:
1842  case X86::BI__builtin_ia32_pternlogq512_mask:
1843  case X86::BI__builtin_ia32_pternlogq512_maskz:
1844  case X86::BI__builtin_ia32_pternlogd128_mask:
1845  case X86::BI__builtin_ia32_pternlogd128_maskz:
1846  case X86::BI__builtin_ia32_pternlogd256_mask:
1847  case X86::BI__builtin_ia32_pternlogd256_maskz:
1848  case X86::BI__builtin_ia32_pternlogq128_mask:
1849  case X86::BI__builtin_ia32_pternlogq128_maskz:
1850  case X86::BI__builtin_ia32_pternlogq256_mask:
1851  case X86::BI__builtin_ia32_pternlogq256_maskz:
1852  i = 3; l = 0; u = 255;
1853  break;
1854  case X86::BI__builtin_ia32_pcmpestrm128:
1855  case X86::BI__builtin_ia32_pcmpestri128:
1856  case X86::BI__builtin_ia32_pcmpestria128:
1857  case X86::BI__builtin_ia32_pcmpestric128:
1858  case X86::BI__builtin_ia32_pcmpestrio128:
1859  case X86::BI__builtin_ia32_pcmpestris128:
1860  case X86::BI__builtin_ia32_pcmpestriz128:
1861  i = 4; l = -128; u = 255;
1862  break;
1863  case X86::BI__builtin_ia32_rndscalesd_round_mask:
1864  case X86::BI__builtin_ia32_rndscaless_round_mask:
1865  i = 4; l = 0; u = 255;
1866  break;
1867  }
1868  return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1869 }
1870 
1871 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
1872 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
1873 /// Returns true when the format fits the function and the FormatStringInfo has
1874 /// been populated.
1875 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
1876  FormatStringInfo *FSI) {
1877  FSI->HasVAListArg = Format->getFirstArg() == 0;
1878  FSI->FormatIdx = Format->getFormatIdx() - 1;
1879  FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
1880 
1881  // The way the format attribute works in GCC, the implicit this argument
1882  // of member functions is counted. However, it doesn't appear in our own
1883  // lists, so decrement format_idx in that case.
1884  if (IsCXXMember) {
1885  if(FSI->FormatIdx == 0)
1886  return false;
1887  --FSI->FormatIdx;
1888  if (FSI->FirstDataArg != 0)
1889  --FSI->FirstDataArg;
1890  }
1891  return true;
1892 }
1893 
1894 /// Checks if a the given expression evaluates to null.
1895 ///
1896 /// \brief Returns true if the value evaluates to null.
1897 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
1898  // If the expression has non-null type, it doesn't evaluate to null.
1899  if (auto nullability
1900  = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
1901  if (*nullability == NullabilityKind::NonNull)
1902  return false;
1903  }
1904 
1905  // As a special case, transparent unions initialized with zero are
1906  // considered null for the purposes of the nonnull attribute.
1907  if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
1908  if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
1909  if (const CompoundLiteralExpr *CLE =
1910  dyn_cast<CompoundLiteralExpr>(Expr))
1911  if (const InitListExpr *ILE =
1912  dyn_cast<InitListExpr>(CLE->getInitializer()))
1913  Expr = ILE->getInit(0);
1914  }
1915 
1916  bool Result;
1917  return (!Expr->isValueDependent() &&
1918  Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
1919  !Result);
1920 }
1921 
1923  const Expr *ArgExpr,
1924  SourceLocation CallSiteLoc) {
1925  if (CheckNonNullExpr(S, ArgExpr))
1926  S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
1927  S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
1928 }
1929 
1930 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
1931  FormatStringInfo FSI;
1932  if ((GetFormatStringType(Format) == FST_NSString) &&
1933  getFormatStringInfo(Format, false, &FSI)) {
1934  Idx = FSI.FormatIdx;
1935  return true;
1936  }
1937  return false;
1938 }
1939 /// \brief Diagnose use of %s directive in an NSString which is being passed
1940 /// as formatting string to formatting method.
1941 static void
1943  const NamedDecl *FDecl,
1944  Expr **Args,
1945  unsigned NumArgs) {
1946  unsigned Idx = 0;
1947  bool Format = false;
1949  if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
1950  Idx = 2;
1951  Format = true;
1952  }
1953  else
1954  for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
1955  if (S.GetFormatNSStringIdx(I, Idx)) {
1956  Format = true;
1957  break;
1958  }
1959  }
1960  if (!Format || NumArgs <= Idx)
1961  return;
1962  const Expr *FormatExpr = Args[Idx];
1963  if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
1964  FormatExpr = CSCE->getSubExpr();
1965  const StringLiteral *FormatString;
1966  if (const ObjCStringLiteral *OSL =
1967  dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
1968  FormatString = OSL->getString();
1969  else
1970  FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
1971  if (!FormatString)
1972  return;
1973  if (S.FormatStringHasSArg(FormatString)) {
1974  S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
1975  << "%s" << 1 << 1;
1976  S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
1977  << FDecl->getDeclName();
1978  }
1979 }
1980 
1981 /// Determine whether the given type has a non-null nullability annotation.
1983  if (auto nullability = type->getNullability(ctx))
1984  return *nullability == NullabilityKind::NonNull;
1985 
1986  return false;
1987 }
1988 
1990  const NamedDecl *FDecl,
1991  const FunctionProtoType *Proto,
1992  ArrayRef<const Expr *> Args,
1993  SourceLocation CallSiteLoc) {
1994  assert((FDecl || Proto) && "Need a function declaration or prototype");
1995 
1996  // Check the attributes attached to the method/function itself.
1997  llvm::SmallBitVector NonNullArgs;
1998  if (FDecl) {
1999  // Handle the nonnull attribute on the function/method declaration itself.
2000  for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
2001  if (!NonNull->args_size()) {
2002  // Easy case: all pointer arguments are nonnull.
2003  for (const auto *Arg : Args)
2004  if (S.isValidPointerAttrType(Arg->getType()))
2005  CheckNonNullArgument(S, Arg, CallSiteLoc);
2006  return;
2007  }
2008 
2009  for (unsigned Val : NonNull->args()) {
2010  if (Val >= Args.size())
2011  continue;
2012  if (NonNullArgs.empty())
2013  NonNullArgs.resize(Args.size());
2014  NonNullArgs.set(Val);
2015  }
2016  }
2017  }
2018 
2019  if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
2020  // Handle the nonnull attribute on the parameters of the
2021  // function/method.
2022  ArrayRef<ParmVarDecl*> parms;
2023  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
2024  parms = FD->parameters();
2025  else
2026  parms = cast<ObjCMethodDecl>(FDecl)->parameters();
2027 
2028  unsigned ParamIndex = 0;
2029  for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
2030  I != E; ++I, ++ParamIndex) {
2031  const ParmVarDecl *PVD = *I;
2032  if (PVD->hasAttr<NonNullAttr>() ||
2033  isNonNullType(S.Context, PVD->getType())) {
2034  if (NonNullArgs.empty())
2035  NonNullArgs.resize(Args.size());
2036 
2037  NonNullArgs.set(ParamIndex);
2038  }
2039  }
2040  } else {
2041  // If we have a non-function, non-method declaration but no
2042  // function prototype, try to dig out the function prototype.
2043  if (!Proto) {
2044  if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
2045  QualType type = VD->getType().getNonReferenceType();
2046  if (auto pointerType = type->getAs<PointerType>())
2047  type = pointerType->getPointeeType();
2048  else if (auto blockType = type->getAs<BlockPointerType>())
2049  type = blockType->getPointeeType();
2050  // FIXME: data member pointers?
2051 
2052  // Dig out the function prototype, if there is one.
2053  Proto = type->getAs<FunctionProtoType>();
2054  }
2055  }
2056 
2057  // Fill in non-null argument information from the nullability
2058  // information on the parameter types (if we have them).
2059  if (Proto) {
2060  unsigned Index = 0;
2061  for (auto paramType : Proto->getParamTypes()) {
2062  if (isNonNullType(S.Context, paramType)) {
2063  if (NonNullArgs.empty())
2064  NonNullArgs.resize(Args.size());
2065 
2066  NonNullArgs.set(Index);
2067  }
2068 
2069  ++Index;
2070  }
2071  }
2072  }
2073 
2074  // Check for non-null arguments.
2075  for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
2076  ArgIndex != ArgIndexEnd; ++ArgIndex) {
2077  if (NonNullArgs[ArgIndex])
2078  CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
2079  }
2080 }
2081 
2082 /// Handles the checks for format strings, non-POD arguments to vararg
2083 /// functions, and NULL arguments passed to non-NULL parameters.
2084 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
2085  ArrayRef<const Expr *> Args, bool IsMemberFunction,
2086  SourceLocation Loc, SourceRange Range,
2087  VariadicCallType CallType) {
2088  // FIXME: We should check as much as we can in the template definition.
2089  if (CurContext->isDependentContext())
2090  return;
2091 
2092  // Printf and scanf checking.
2093  llvm::SmallBitVector CheckedVarArgs;
2094  if (FDecl) {
2095  for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2096  // Only create vector if there are format attributes.
2097  CheckedVarArgs.resize(Args.size());
2098 
2099  CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
2100  CheckedVarArgs);
2101  }
2102  }
2103 
2104  // Refuse POD arguments that weren't caught by the format string
2105  // checks above.
2106  if (CallType != VariadicDoesNotApply) {
2107  unsigned NumParams = Proto ? Proto->getNumParams()
2108  : FDecl && isa<FunctionDecl>(FDecl)
2109  ? cast<FunctionDecl>(FDecl)->getNumParams()
2110  : FDecl && isa<ObjCMethodDecl>(FDecl)
2111  ? cast<ObjCMethodDecl>(FDecl)->param_size()
2112  : 0;
2113 
2114  for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
2115  // Args[ArgIdx] can be null in malformed code.
2116  if (const Expr *Arg = Args[ArgIdx]) {
2117  if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
2118  checkVariadicArgument(Arg, CallType);
2119  }
2120  }
2121  }
2122 
2123  if (FDecl || Proto) {
2124  CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
2125 
2126  // Type safety checking.
2127  if (FDecl) {
2128  for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
2129  CheckArgumentWithTypeTag(I, Args.data());
2130  }
2131  }
2132 }
2133 
2134 /// CheckConstructorCall - Check a constructor call for correctness and safety
2135 /// properties not enforced by the C type system.
2136 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
2137  ArrayRef<const Expr *> Args,
2138  const FunctionProtoType *Proto,
2139  SourceLocation Loc) {
2140  VariadicCallType CallType =
2141  Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
2142  checkCall(FDecl, Proto, Args, /*IsMemberFunction=*/true, Loc, SourceRange(),
2143  CallType);
2144 }
2145 
2146 /// CheckFunctionCall - Check a direct function call for various correctness
2147 /// and safety properties not strictly enforced by the C type system.
2148 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
2149  const FunctionProtoType *Proto) {
2150  bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
2151  isa<CXXMethodDecl>(FDecl);
2152  bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
2153  IsMemberOperatorCall;
2154  VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
2155  TheCall->getCallee());
2156  Expr** Args = TheCall->getArgs();
2157  unsigned NumArgs = TheCall->getNumArgs();
2158  if (IsMemberOperatorCall) {
2159  // If this is a call to a member operator, hide the first argument
2160  // from checkCall.
2161  // FIXME: Our choice of AST representation here is less than ideal.
2162  ++Args;
2163  --NumArgs;
2164  }
2165  checkCall(FDecl, Proto, llvm::makeArrayRef(Args, NumArgs),
2166  IsMemberFunction, TheCall->getRParenLoc(),
2167  TheCall->getCallee()->getSourceRange(), CallType);
2168 
2169  IdentifierInfo *FnInfo = FDecl->getIdentifier();
2170  // None of the checks below are needed for functions that don't have
2171  // simple names (e.g., C++ conversion functions).
2172  if (!FnInfo)
2173  return false;
2174 
2175  CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
2176  if (getLangOpts().ObjC1)
2177  DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
2178 
2179  unsigned CMId = FDecl->getMemoryFunctionKind();
2180  if (CMId == 0)
2181  return false;
2182 
2183  // Handle memory setting and copying functions.
2184  if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
2185  CheckStrlcpycatArguments(TheCall, FnInfo);
2186  else if (CMId == Builtin::BIstrncat)
2187  CheckStrncatArguments(TheCall, FnInfo);
2188  else
2189  CheckMemaccessArguments(TheCall, CMId, FnInfo);
2190 
2191  return false;
2192 }
2193 
2194 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
2195  ArrayRef<const Expr *> Args) {
2196  VariadicCallType CallType =
2197  Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
2198 
2199  checkCall(Method, nullptr, Args,
2200  /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
2201  CallType);
2202 
2203  return false;
2204 }
2205 
2206 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
2207  const FunctionProtoType *Proto) {
2208  QualType Ty;
2209  if (const auto *V = dyn_cast<VarDecl>(NDecl))
2210  Ty = V->getType().getNonReferenceType();
2211  else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
2212  Ty = F->getType().getNonReferenceType();
2213  else
2214  return false;
2215 
2216  if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
2217  !Ty->isFunctionProtoType())
2218  return false;
2219 
2220  VariadicCallType CallType;
2221  if (!Proto || !Proto->isVariadic()) {
2222  CallType = VariadicDoesNotApply;
2223  } else if (Ty->isBlockPointerType()) {
2224  CallType = VariadicBlock;
2225  } else { // Ty->isFunctionPointerType()
2226  CallType = VariadicFunction;
2227  }
2228 
2229  checkCall(NDecl, Proto,
2230  llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2231  /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
2232  TheCall->getCallee()->getSourceRange(), CallType);
2233 
2234  return false;
2235 }
2236 
2237 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
2238 /// such as function pointers returned from functions.
2239 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
2240  VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
2241  TheCall->getCallee());
2242  checkCall(/*FDecl=*/nullptr, Proto,
2243  llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2244  /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
2245  TheCall->getCallee()->getSourceRange(), CallType);
2246 
2247  return false;
2248 }
2249 
2250 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
2251  if (!llvm::isValidAtomicOrderingCABI(Ordering))
2252  return false;
2253 
2254  auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
2255  switch (Op) {
2256  case AtomicExpr::AO__c11_atomic_init:
2257  llvm_unreachable("There is no ordering argument for an init");
2258 
2259  case AtomicExpr::AO__c11_atomic_load:
2260  case AtomicExpr::AO__atomic_load_n:
2261  case AtomicExpr::AO__atomic_load:
2262  return OrderingCABI != llvm::AtomicOrderingCABI::release &&
2263  OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
2264 
2265  case AtomicExpr::AO__c11_atomic_store:
2266  case AtomicExpr::AO__atomic_store:
2267  case AtomicExpr::AO__atomic_store_n:
2268  return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
2269  OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
2270  OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
2271 
2272  default:
2273  return true;
2274  }
2275 }
2276 
2277 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
2278  AtomicExpr::AtomicOp Op) {
2279  CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
2280  DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2281 
2282  // All these operations take one of the following forms:
2283  enum {
2284  // C __c11_atomic_init(A *, C)
2285  Init,
2286  // C __c11_atomic_load(A *, int)
2287  Load,
2288  // void __atomic_load(A *, CP, int)
2289  LoadCopy,
2290  // void __atomic_store(A *, CP, int)
2291  Copy,
2292  // C __c11_atomic_add(A *, M, int)
2293  Arithmetic,
2294  // C __atomic_exchange_n(A *, CP, int)
2295  Xchg,
2296  // void __atomic_exchange(A *, C *, CP, int)
2297  GNUXchg,
2298  // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
2299  C11CmpXchg,
2300  // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
2301  GNUCmpXchg
2302  } Form = Init;
2303  const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
2304  const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
2305  // where:
2306  // C is an appropriate type,
2307  // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
2308  // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
2309  // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
2310  // the int parameters are for orderings.
2311 
2312  static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
2313  AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
2314  AtomicExpr::AO__atomic_load,
2315  "need to update code for modified C11 atomics");
2316  bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
2317  Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
2318  bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
2319  Op == AtomicExpr::AO__atomic_store_n ||
2320  Op == AtomicExpr::AO__atomic_exchange_n ||
2321  Op == AtomicExpr::AO__atomic_compare_exchange_n;
2322  bool IsAddSub = false;
2323 
2324  switch (Op) {
2325  case AtomicExpr::AO__c11_atomic_init:
2326  Form = Init;
2327  break;
2328 
2329  case AtomicExpr::AO__c11_atomic_load:
2330  case AtomicExpr::AO__atomic_load_n:
2331  Form = Load;
2332  break;
2333 
2334  case AtomicExpr::AO__atomic_load:
2335  Form = LoadCopy;
2336  break;
2337 
2338  case AtomicExpr::AO__c11_atomic_store:
2339  case AtomicExpr::AO__atomic_store:
2340  case AtomicExpr::AO__atomic_store_n:
2341  Form = Copy;
2342  break;
2343 
2344  case AtomicExpr::AO__c11_atomic_fetch_add:
2345  case AtomicExpr::AO__c11_atomic_fetch_sub:
2346  case AtomicExpr::AO__atomic_fetch_add:
2347  case AtomicExpr::AO__atomic_fetch_sub:
2348  case AtomicExpr::AO__atomic_add_fetch:
2349  case AtomicExpr::AO__atomic_sub_fetch:
2350  IsAddSub = true;
2351  // Fall through.
2352  case AtomicExpr::AO__c11_atomic_fetch_and:
2353  case AtomicExpr::AO__c11_atomic_fetch_or:
2354  case AtomicExpr::AO__c11_atomic_fetch_xor:
2355  case AtomicExpr::AO__atomic_fetch_and:
2356  case AtomicExpr::AO__atomic_fetch_or:
2357  case AtomicExpr::AO__atomic_fetch_xor:
2358  case AtomicExpr::AO__atomic_fetch_nand:
2359  case AtomicExpr::AO__atomic_and_fetch:
2360  case AtomicExpr::AO__atomic_or_fetch:
2361  case AtomicExpr::AO__atomic_xor_fetch:
2362  case AtomicExpr::AO__atomic_nand_fetch:
2363  Form = Arithmetic;
2364  break;
2365 
2366  case AtomicExpr::AO__c11_atomic_exchange:
2367  case AtomicExpr::AO__atomic_exchange_n:
2368  Form = Xchg;
2369  break;
2370 
2371  case AtomicExpr::AO__atomic_exchange:
2372  Form = GNUXchg;
2373  break;
2374 
2375  case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
2376  case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
2377  Form = C11CmpXchg;
2378  break;
2379 
2380  case AtomicExpr::AO__atomic_compare_exchange:
2381  case AtomicExpr::AO__atomic_compare_exchange_n:
2382  Form = GNUCmpXchg;
2383  break;
2384  }
2385 
2386  // Check we have the right number of arguments.
2387  if (TheCall->getNumArgs() < NumArgs[Form]) {
2388  Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
2389  << 0 << NumArgs[Form] << TheCall->getNumArgs()
2390  << TheCall->getCallee()->getSourceRange();
2391  return ExprError();
2392  } else if (TheCall->getNumArgs() > NumArgs[Form]) {
2393  Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
2394  diag::err_typecheck_call_too_many_args)
2395  << 0 << NumArgs[Form] << TheCall->getNumArgs()
2396  << TheCall->getCallee()->getSourceRange();
2397  return ExprError();
2398  }
2399 
2400  // Inspect the first argument of the atomic operation.
2401  Expr *Ptr = TheCall->getArg(0);
2402  ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
2403  if (ConvertedPtr.isInvalid())
2404  return ExprError();
2405 
2406  Ptr = ConvertedPtr.get();
2407  const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
2408  if (!pointerType) {
2409  Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
2410  << Ptr->getType() << Ptr->getSourceRange();
2411  return ExprError();
2412  }
2413 
2414  // For a __c11 builtin, this should be a pointer to an _Atomic type.
2415  QualType AtomTy = pointerType->getPointeeType(); // 'A'
2416  QualType ValType = AtomTy; // 'C'
2417  if (IsC11) {
2418  if (!AtomTy->isAtomicType()) {
2419  Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
2420  << Ptr->getType() << Ptr->getSourceRange();
2421  return ExprError();
2422  }
2423  if (AtomTy.isConstQualified()) {
2424  Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
2425  << Ptr->getType() << Ptr->getSourceRange();
2426  return ExprError();
2427  }
2428  ValType = AtomTy->getAs<AtomicType>()->getValueType();
2429  } else if (Form != Load && Form != LoadCopy) {
2430  if (ValType.isConstQualified()) {
2431  Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
2432  << Ptr->getType() << Ptr->getSourceRange();
2433  return ExprError();
2434  }
2435  }
2436 
2437  // For an arithmetic operation, the implied arithmetic must be well-formed.
2438  if (Form == Arithmetic) {
2439  // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
2440  if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
2441  Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
2442  << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2443  return ExprError();
2444  }
2445  if (!IsAddSub && !ValType->isIntegerType()) {
2446  Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
2447  << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2448  return ExprError();
2449  }
2450  if (IsC11 && ValType->isPointerType() &&
2451  RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
2452  diag::err_incomplete_type)) {
2453  return ExprError();
2454  }
2455  } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
2456  // For __atomic_*_n operations, the value type must be a scalar integral or
2457  // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
2458  Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
2459  << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2460  return ExprError();
2461  }
2462 
2463  if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
2464  !AtomTy->isScalarType()) {
2465  // For GNU atomics, require a trivially-copyable type. This is not part of
2466  // the GNU atomics specification, but we enforce it for sanity.
2467  Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
2468  << Ptr->getType() << Ptr->getSourceRange();
2469  return ExprError();
2470  }
2471 
2472  switch (ValType.getObjCLifetime()) {
2473  case Qualifiers::OCL_None:
2475  // okay
2476  break;
2477 
2478  case Qualifiers::OCL_Weak:
2481  // FIXME: Can this happen? By this point, ValType should be known
2482  // to be trivially copyable.
2483  Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
2484  << ValType << Ptr->getSourceRange();
2485  return ExprError();
2486  }
2487 
2488  // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the
2489  // volatile-ness of the pointee-type inject itself into the result or the
2490  // other operands. Similarly atomic_load can take a pointer to a const 'A'.
2491  ValType.removeLocalVolatile();
2492  ValType.removeLocalConst();
2493  QualType ResultType = ValType;
2494  if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init)
2495  ResultType = Context.VoidTy;
2496  else if (Form == C11CmpXchg || Form == GNUCmpXchg)
2497  ResultType = Context.BoolTy;
2498 
2499  // The type of a parameter passed 'by value'. In the GNU atomics, such
2500  // arguments are actually passed as pointers.
2501  QualType ByValType = ValType; // 'CP'
2502  if (!IsC11 && !IsN)
2503  ByValType = Ptr->getType();
2504 
2505  // The first argument --- the pointer --- has a fixed type; we
2506  // deduce the types of the rest of the arguments accordingly. Walk
2507  // the remaining arguments, converting them to the deduced value type.
2508  for (unsigned i = 1; i != NumArgs[Form]; ++i) {
2509  QualType Ty;
2510  if (i < NumVals[Form] + 1) {
2511  switch (i) {
2512  case 1:
2513  // The second argument is the non-atomic operand. For arithmetic, this
2514  // is always passed by value, and for a compare_exchange it is always
2515  // passed by address. For the rest, GNU uses by-address and C11 uses
2516  // by-value.
2517  assert(Form != Load);
2518  if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
2519  Ty = ValType;
2520  else if (Form == Copy || Form == Xchg)
2521  Ty = ByValType;
2522  else if (Form == Arithmetic)
2523  Ty = Context.getPointerDiffType();
2524  else {
2525  Expr *ValArg = TheCall->getArg(i);
2526  unsigned AS = 0;
2527  // Keep address space of non-atomic pointer type.
2528  if (const PointerType *PtrTy =
2529  ValArg->getType()->getAs<PointerType>()) {
2530  AS = PtrTy->getPointeeType().getAddressSpace();
2531  }
2532  Ty = Context.getPointerType(
2534  }
2535  break;
2536  case 2:
2537  // The third argument to compare_exchange / GNU exchange is a
2538  // (pointer to a) desired value.
2539  Ty = ByValType;
2540  break;
2541  case 3:
2542  // The fourth argument to GNU compare_exchange is a 'weak' flag.
2543  Ty = Context.BoolTy;
2544  break;
2545  }
2546  } else {
2547  // The order(s) are always converted to int.
2548  Ty = Context.IntTy;
2549  }
2550 
2551  InitializedEntity Entity =
2553  ExprResult Arg = TheCall->getArg(i);
2554  Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2555  if (Arg.isInvalid())
2556  return true;
2557  TheCall->setArg(i, Arg.get());
2558  }
2559 
2560  // Permute the arguments into a 'consistent' order.
2561  SmallVector<Expr*, 5> SubExprs;
2562  SubExprs.push_back(Ptr);
2563  switch (Form) {
2564  case Init:
2565  // Note, AtomicExpr::getVal1() has a special case for this atomic.
2566  SubExprs.push_back(TheCall->getArg(1)); // Val1
2567  break;
2568  case Load:
2569  SubExprs.push_back(TheCall->getArg(1)); // Order
2570  break;
2571  case LoadCopy:
2572  case Copy:
2573  case Arithmetic:
2574  case Xchg:
2575  SubExprs.push_back(TheCall->getArg(2)); // Order
2576  SubExprs.push_back(TheCall->getArg(1)); // Val1
2577  break;
2578  case GNUXchg:
2579  // Note, AtomicExpr::getVal2() has a special case for this atomic.
2580  SubExprs.push_back(TheCall->getArg(3)); // Order
2581  SubExprs.push_back(TheCall->getArg(1)); // Val1
2582  SubExprs.push_back(TheCall->getArg(2)); // Val2
2583  break;
2584  case C11CmpXchg:
2585  SubExprs.push_back(TheCall->getArg(3)); // Order
2586  SubExprs.push_back(TheCall->getArg(1)); // Val1
2587  SubExprs.push_back(TheCall->getArg(4)); // OrderFail
2588  SubExprs.push_back(TheCall->getArg(2)); // Val2
2589  break;
2590  case GNUCmpXchg:
2591  SubExprs.push_back(TheCall->getArg(4)); // Order
2592  SubExprs.push_back(TheCall->getArg(1)); // Val1
2593  SubExprs.push_back(TheCall->getArg(5)); // OrderFail
2594  SubExprs.push_back(TheCall->getArg(2)); // Val2
2595  SubExprs.push_back(TheCall->getArg(3)); // Weak
2596  break;
2597  }
2598 
2599  if (SubExprs.size() >= 2 && Form != Init) {
2600  llvm::APSInt Result(32);
2601  if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
2602  !isValidOrderingForOp(Result.getSExtValue(), Op))
2603  Diag(SubExprs[1]->getLocStart(),
2604  diag::warn_atomic_op_has_invalid_memory_order)
2605  << SubExprs[1]->getSourceRange();
2606  }
2607 
2608  AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
2609  SubExprs, ResultType, Op,
2610  TheCall->getRParenLoc());
2611 
2612  if ((Op == AtomicExpr::AO__c11_atomic_load ||
2613  (Op == AtomicExpr::AO__c11_atomic_store)) &&
2615  Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
2616  ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
2617 
2618  return AE;
2619 }
2620 
2621 /// checkBuiltinArgument - Given a call to a builtin function, perform
2622 /// normal type-checking on the given argument, updating the call in
2623 /// place. This is useful when a builtin function requires custom
2624 /// type-checking for some of its arguments but not necessarily all of
2625 /// them.
2626 ///
2627 /// Returns true on error.
2628 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
2629  FunctionDecl *Fn = E->getDirectCallee();
2630  assert(Fn && "builtin call without direct callee!");
2631 
2632  ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
2633  InitializedEntity Entity =
2635 
2636  ExprResult Arg = E->getArg(0);
2637  Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
2638  if (Arg.isInvalid())
2639  return true;
2640 
2641  E->setArg(ArgIndex, Arg.get());
2642  return false;
2643 }
2644 
2645 /// SemaBuiltinAtomicOverloaded - We have a call to a function like
2646 /// __sync_fetch_and_add, which is an overloaded function based on the pointer
2647 /// type of its first argument. The main ActOnCallExpr routines have already
2648 /// promoted the types of arguments because all of these calls are prototyped as
2649 /// void(...).
2650 ///
2651 /// This function goes through and does final semantic checking for these
2652 /// builtins,
2653 ExprResult
2654 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
2655  CallExpr *TheCall = (CallExpr *)TheCallResult.get();
2656  DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2657  FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2658 
2659  // Ensure that we have at least one argument to do type inference from.
2660  if (TheCall->getNumArgs() < 1) {
2661  Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
2662  << 0 << 1 << TheCall->getNumArgs()
2663  << TheCall->getCallee()->getSourceRange();
2664  return ExprError();
2665  }
2666 
2667  // Inspect the first argument of the atomic builtin. This should always be
2668  // a pointer type, whose element is an integral scalar or pointer type.
2669  // Because it is a pointer type, we don't have to worry about any implicit
2670  // casts here.
2671  // FIXME: We don't allow floating point scalars as input.
2672  Expr *FirstArg = TheCall->getArg(0);
2673  ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
2674  if (FirstArgResult.isInvalid())
2675  return ExprError();
2676  FirstArg = FirstArgResult.get();
2677  TheCall->setArg(0, FirstArg);
2678 
2679  const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
2680  if (!pointerType) {
2681  Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
2682  << FirstArg->getType() << FirstArg->getSourceRange();
2683  return ExprError();
2684  }
2685 
2686  QualType ValType = pointerType->getPointeeType();
2687  if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2688  !ValType->isBlockPointerType()) {
2689  Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
2690  << FirstArg->getType() << FirstArg->getSourceRange();
2691  return ExprError();
2692  }
2693 
2694  switch (ValType.getObjCLifetime()) {
2695  case Qualifiers::OCL_None:
2697  // okay
2698  break;
2699 
2700  case Qualifiers::OCL_Weak:
2703  Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
2704  << ValType << FirstArg->getSourceRange();
2705  return ExprError();
2706  }
2707 
2708  // Strip any qualifiers off ValType.
2709  ValType = ValType.getUnqualifiedType();
2710 
2711  // The majority of builtins return a value, but a few have special return
2712  // types, so allow them to override appropriately below.
2713  QualType ResultType = ValType;
2714 
2715  // We need to figure out which concrete builtin this maps onto. For example,
2716  // __sync_fetch_and_add with a 2 byte object turns into
2717  // __sync_fetch_and_add_2.
2718 #define BUILTIN_ROW(x) \
2719  { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
2720  Builtin::BI##x##_8, Builtin::BI##x##_16 }
2721 
2722  static const unsigned BuiltinIndices[][5] = {
2723  BUILTIN_ROW(__sync_fetch_and_add),
2724  BUILTIN_ROW(__sync_fetch_and_sub),
2725  BUILTIN_ROW(__sync_fetch_and_or),
2726  BUILTIN_ROW(__sync_fetch_and_and),
2727  BUILTIN_ROW(__sync_fetch_and_xor),
2728  BUILTIN_ROW(__sync_fetch_and_nand),
2729 
2730  BUILTIN_ROW(__sync_add_and_fetch),
2731  BUILTIN_ROW(__sync_sub_and_fetch),
2732  BUILTIN_ROW(__sync_and_and_fetch),
2733  BUILTIN_ROW(__sync_or_and_fetch),
2734  BUILTIN_ROW(__sync_xor_and_fetch),
2735  BUILTIN_ROW(__sync_nand_and_fetch),
2736 
2737  BUILTIN_ROW(__sync_val_compare_and_swap),
2738  BUILTIN_ROW(__sync_bool_compare_and_swap),
2739  BUILTIN_ROW(__sync_lock_test_and_set),
2740  BUILTIN_ROW(__sync_lock_release),
2741  BUILTIN_ROW(__sync_swap)
2742  };
2743 #undef BUILTIN_ROW
2744 
2745  // Determine the index of the size.
2746  unsigned SizeIndex;
2747  switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
2748  case 1: SizeIndex = 0; break;
2749  case 2: SizeIndex = 1; break;
2750  case 4: SizeIndex = 2; break;
2751  case 8: SizeIndex = 3; break;
2752  case 16: SizeIndex = 4; break;
2753  default:
2754  Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
2755  << FirstArg->getType() << FirstArg->getSourceRange();
2756  return ExprError();
2757  }
2758 
2759  // Each of these builtins has one pointer argument, followed by some number of
2760  // values (0, 1 or 2) followed by a potentially empty varags list of stuff
2761  // that we ignore. Find out which row of BuiltinIndices to read from as well
2762  // as the number of fixed args.
2763  unsigned BuiltinID = FDecl->getBuiltinID();
2764  unsigned BuiltinIndex, NumFixed = 1;
2765  bool WarnAboutSemanticsChange = false;
2766  switch (BuiltinID) {
2767  default: llvm_unreachable("Unknown overloaded atomic builtin!");
2768  case Builtin::BI__sync_fetch_and_add:
2769  case Builtin::BI__sync_fetch_and_add_1:
2770  case Builtin::BI__sync_fetch_and_add_2:
2771  case Builtin::BI__sync_fetch_and_add_4:
2772  case Builtin::BI__sync_fetch_and_add_8:
2773  case Builtin::BI__sync_fetch_and_add_16:
2774  BuiltinIndex = 0;
2775  break;
2776 
2777  case Builtin::BI__sync_fetch_and_sub:
2778  case Builtin::BI__sync_fetch_and_sub_1:
2779  case Builtin::BI__sync_fetch_and_sub_2:
2780  case Builtin::BI__sync_fetch_and_sub_4:
2781  case Builtin::BI__sync_fetch_and_sub_8:
2782  case Builtin::BI__sync_fetch_and_sub_16:
2783  BuiltinIndex = 1;
2784  break;
2785 
2786  case Builtin::BI__sync_fetch_and_or:
2787  case Builtin::BI__sync_fetch_and_or_1:
2788  case Builtin::BI__sync_fetch_and_or_2:
2789  case Builtin::BI__sync_fetch_and_or_4:
2790  case Builtin::BI__sync_fetch_and_or_8:
2791  case Builtin::BI__sync_fetch_and_or_16:
2792  BuiltinIndex = 2;
2793  break;
2794 
2795  case Builtin::BI__sync_fetch_and_and:
2796  case Builtin::BI__sync_fetch_and_and_1:
2797  case Builtin::BI__sync_fetch_and_and_2:
2798  case Builtin::BI__sync_fetch_and_and_4:
2799  case Builtin::BI__sync_fetch_and_and_8:
2800  case Builtin::BI__sync_fetch_and_and_16:
2801  BuiltinIndex = 3;
2802  break;
2803 
2804  case Builtin::BI__sync_fetch_and_xor:
2805  case Builtin::BI__sync_fetch_and_xor_1:
2806  case Builtin::BI__sync_fetch_and_xor_2:
2807  case Builtin::BI__sync_fetch_and_xor_4:
2808  case Builtin::BI__sync_fetch_and_xor_8:
2809  case Builtin::BI__sync_fetch_and_xor_16:
2810  BuiltinIndex = 4;
2811  break;
2812 
2813  case Builtin::BI__sync_fetch_and_nand:
2814  case Builtin::BI__sync_fetch_and_nand_1:
2815  case Builtin::BI__sync_fetch_and_nand_2:
2816  case Builtin::BI__sync_fetch_and_nand_4:
2817  case Builtin::BI__sync_fetch_and_nand_8:
2818  case Builtin::BI__sync_fetch_and_nand_16:
2819  BuiltinIndex = 5;
2820  WarnAboutSemanticsChange = true;
2821  break;
2822 
2823  case Builtin::BI__sync_add_and_fetch:
2824  case Builtin::BI__sync_add_and_fetch_1:
2825  case Builtin::BI__sync_add_and_fetch_2:
2826  case Builtin::BI__sync_add_and_fetch_4:
2827  case Builtin::BI__sync_add_and_fetch_8:
2828  case Builtin::BI__sync_add_and_fetch_16:
2829  BuiltinIndex = 6;
2830  break;
2831 
2832  case Builtin::BI__sync_sub_and_fetch:
2833  case Builtin::BI__sync_sub_and_fetch_1:
2834  case Builtin::BI__sync_sub_and_fetch_2:
2835  case Builtin::BI__sync_sub_and_fetch_4:
2836  case Builtin::BI__sync_sub_and_fetch_8:
2837  case Builtin::BI__sync_sub_and_fetch_16:
2838  BuiltinIndex = 7;
2839  break;
2840 
2841  case Builtin::BI__sync_and_and_fetch:
2842  case Builtin::BI__sync_and_and_fetch_1:
2843  case Builtin::BI__sync_and_and_fetch_2:
2844  case Builtin::BI__sync_and_and_fetch_4:
2845  case Builtin::BI__sync_and_and_fetch_8:
2846  case Builtin::BI__sync_and_and_fetch_16:
2847  BuiltinIndex = 8;
2848  break;
2849 
2850  case Builtin::BI__sync_or_and_fetch:
2851  case Builtin::BI__sync_or_and_fetch_1:
2852  case Builtin::BI__sync_or_and_fetch_2:
2853  case Builtin::BI__sync_or_and_fetch_4:
2854  case Builtin::BI__sync_or_and_fetch_8:
2855  case Builtin::BI__sync_or_and_fetch_16:
2856  BuiltinIndex = 9;
2857  break;
2858 
2859  case Builtin::BI__sync_xor_and_fetch:
2860  case Builtin::BI__sync_xor_and_fetch_1:
2861  case Builtin::BI__sync_xor_and_fetch_2:
2862  case Builtin::BI__sync_xor_and_fetch_4:
2863  case Builtin::BI__sync_xor_and_fetch_8:
2864  case Builtin::BI__sync_xor_and_fetch_16:
2865  BuiltinIndex = 10;
2866  break;
2867 
2868  case Builtin::BI__sync_nand_and_fetch:
2869  case Builtin::BI__sync_nand_and_fetch_1:
2870  case Builtin::BI__sync_nand_and_fetch_2:
2871  case Builtin::BI__sync_nand_and_fetch_4:
2872  case Builtin::BI__sync_nand_and_fetch_8:
2873  case Builtin::BI__sync_nand_and_fetch_16:
2874  BuiltinIndex = 11;
2875  WarnAboutSemanticsChange = true;
2876  break;
2877 
2878  case Builtin::BI__sync_val_compare_and_swap:
2879  case Builtin::BI__sync_val_compare_and_swap_1:
2880  case Builtin::BI__sync_val_compare_and_swap_2:
2881  case Builtin::BI__sync_val_compare_and_swap_4:
2882  case Builtin::BI__sync_val_compare_and_swap_8:
2883  case Builtin::BI__sync_val_compare_and_swap_16:
2884  BuiltinIndex = 12;
2885  NumFixed = 2;
2886  break;
2887 
2888  case Builtin::BI__sync_bool_compare_and_swap:
2889  case Builtin::BI__sync_bool_compare_and_swap_1:
2890  case Builtin::BI__sync_bool_compare_and_swap_2:
2891  case Builtin::BI__sync_bool_compare_and_swap_4:
2892  case Builtin::BI__sync_bool_compare_and_swap_8:
2893  case Builtin::BI__sync_bool_compare_and_swap_16:
2894  BuiltinIndex = 13;
2895  NumFixed = 2;
2896  ResultType = Context.BoolTy;
2897  break;
2898 
2899  case Builtin::BI__sync_lock_test_and_set:
2900  case Builtin::BI__sync_lock_test_and_set_1:
2901  case Builtin::BI__sync_lock_test_and_set_2:
2902  case Builtin::BI__sync_lock_test_and_set_4:
2903  case Builtin::BI__sync_lock_test_and_set_8:
2904  case Builtin::BI__sync_lock_test_and_set_16:
2905  BuiltinIndex = 14;
2906  break;
2907 
2908  case Builtin::BI__sync_lock_release:
2909  case Builtin::BI__sync_lock_release_1:
2910  case Builtin::BI__sync_lock_release_2:
2911  case Builtin::BI__sync_lock_release_4:
2912  case Builtin::BI__sync_lock_release_8:
2913  case Builtin::BI__sync_lock_release_16:
2914  BuiltinIndex = 15;
2915  NumFixed = 0;
2916  ResultType = Context.VoidTy;
2917  break;
2918 
2919  case Builtin::BI__sync_swap:
2920  case Builtin::BI__sync_swap_1:
2921  case Builtin::BI__sync_swap_2:
2922  case Builtin::BI__sync_swap_4:
2923  case Builtin::BI__sync_swap_8:
2924  case Builtin::BI__sync_swap_16:
2925  BuiltinIndex = 16;
2926  break;
2927  }
2928 
2929  // Now that we know how many fixed arguments we expect, first check that we
2930  // have at least that many.
2931  if (TheCall->getNumArgs() < 1+NumFixed) {
2932  Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
2933  << 0 << 1+NumFixed << TheCall->getNumArgs()
2934  << TheCall->getCallee()->getSourceRange();
2935  return ExprError();
2936  }
2937 
2938  if (WarnAboutSemanticsChange) {
2939  Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
2940  << TheCall->getCallee()->getSourceRange();
2941  }
2942 
2943  // Get the decl for the concrete builtin from this, we can tell what the
2944  // concrete integer type we should convert to is.
2945  unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
2946  const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
2947  FunctionDecl *NewBuiltinDecl;
2948  if (NewBuiltinID == BuiltinID)
2949  NewBuiltinDecl = FDecl;
2950  else {
2951  // Perform builtin lookup to avoid redeclaring it.
2952  DeclarationName DN(&Context.Idents.get(NewBuiltinName));
2953  LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
2954  LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
2955  assert(Res.getFoundDecl());
2956  NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
2957  if (!NewBuiltinDecl)
2958  return ExprError();
2959  }
2960 
2961  // The first argument --- the pointer --- has a fixed type; we
2962  // deduce the types of the rest of the arguments accordingly. Walk
2963  // the remaining arguments, converting them to the deduced value type.
2964  for (unsigned i = 0; i != NumFixed; ++i) {
2965  ExprResult Arg = TheCall->getArg(i+1);
2966 
2967  // GCC does an implicit conversion to the pointer or integer ValType. This
2968  // can fail in some cases (1i -> int**), check for this error case now.
2969  // Initialize the argument.
2971  ValType, /*consume*/ false);
2972  Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2973  if (Arg.isInvalid())
2974  return ExprError();
2975 
2976  // Okay, we have something that *can* be converted to the right type. Check
2977  // to see if there is a potentially weird extension going on here. This can
2978  // happen when you do an atomic operation on something like an char* and
2979  // pass in 42. The 42 gets converted to char. This is even more strange
2980  // for things like 45.123 -> char, etc.
2981  // FIXME: Do this check.
2982  TheCall->setArg(i+1, Arg.get());
2983  }
2984 
2985  ASTContext& Context = this->getASTContext();
2986 
2987  // Create a new DeclRefExpr to refer to the new decl.
2988  DeclRefExpr* NewDRE = DeclRefExpr::Create(
2989  Context,
2990  DRE->getQualifierLoc(),
2991  SourceLocation(),
2992  NewBuiltinDecl,
2993  /*enclosing*/ false,
2994  DRE->getLocation(),
2995  Context.BuiltinFnTy,
2996  DRE->getValueKind());
2997 
2998  // Set the callee in the CallExpr.
2999  // FIXME: This loses syntactic information.
3000  QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
3001  ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
3002  CK_BuiltinFnToFnPtr);
3003  TheCall->setCallee(PromotedCall.get());
3004 
3005  // Change the result type of the call to match the original value type. This
3006  // is arbitrary, but the codegen for these builtins ins design to handle it
3007  // gracefully.
3008  TheCall->setType(ResultType);
3009 
3010  return TheCallResult;
3011 }
3012 
3013 /// SemaBuiltinNontemporalOverloaded - We have a call to
3014 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
3015 /// overloaded function based on the pointer type of its last argument.
3016 ///
3017 /// This function goes through and does final semantic checking for these
3018 /// builtins.
3019 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
3020  CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3021  DeclRefExpr *DRE =
3022  cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3023  FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3024  unsigned BuiltinID = FDecl->getBuiltinID();
3025  assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
3026  BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
3027  "Unexpected nontemporal load/store builtin!");
3028  bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
3029  unsigned numArgs = isStore ? 2 : 1;
3030 
3031  // Ensure that we have the proper number of arguments.
3032  if (checkArgCount(*this, TheCall, numArgs))
3033  return ExprError();
3034 
3035  // Inspect the last argument of the nontemporal builtin. This should always
3036  // be a pointer type, from which we imply the type of the memory access.
3037  // Because it is a pointer type, we don't have to worry about any implicit
3038  // casts here.
3039  Expr *PointerArg = TheCall->getArg(numArgs - 1);
3040  ExprResult PointerArgResult =
3041  DefaultFunctionArrayLvalueConversion(PointerArg);
3042 
3043  if (PointerArgResult.isInvalid())
3044  return ExprError();
3045  PointerArg = PointerArgResult.get();
3046  TheCall->setArg(numArgs - 1, PointerArg);
3047 
3048  const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
3049  if (!pointerType) {
3050  Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
3051  << PointerArg->getType() << PointerArg->getSourceRange();
3052  return ExprError();
3053  }
3054 
3055  QualType ValType = pointerType->getPointeeType();
3056 
3057  // Strip any qualifiers off ValType.
3058  ValType = ValType.getUnqualifiedType();
3059  if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3060  !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
3061  !ValType->isVectorType()) {
3062  Diag(DRE->getLocStart(),
3063  diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
3064  << PointerArg->getType() << PointerArg->getSourceRange();
3065  return ExprError();
3066  }
3067 
3068  if (!isStore) {
3069  TheCall->setType(ValType);
3070  return TheCallResult;
3071  }
3072 
3073  ExprResult ValArg = TheCall->getArg(0);
3075  Context, ValType, /*consume*/ false);
3076  ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
3077  if (ValArg.isInvalid())
3078  return ExprError();
3079 
3080  TheCall->setArg(0, ValArg.get());
3081  TheCall->setType(Context.VoidTy);
3082  return TheCallResult;
3083 }
3084 
3085 /// CheckObjCString - Checks that the argument to the builtin
3086 /// CFString constructor is correct
3087 /// Note: It might also make sense to do the UTF-16 conversion here (would
3088 /// simplify the backend).
3089 bool Sema::CheckObjCString(Expr *Arg) {
3090  Arg = Arg->IgnoreParenCasts();
3091  StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
3092 
3093  if (!Literal || !Literal->isAscii()) {
3094  Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
3095  << Arg->getSourceRange();
3096  return true;
3097  }
3098 
3099  if (Literal->containsNonAsciiOrNull()) {
3100  StringRef String = Literal->getString();
3101  unsigned NumBytes = String.size();
3102  SmallVector<UTF16, 128> ToBuf(NumBytes);
3103  const UTF8 *FromPtr = (const UTF8 *)String.data();
3104  UTF16 *ToPtr = &ToBuf[0];
3105 
3106  ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
3107  &ToPtr, ToPtr + NumBytes,
3108  strictConversion);
3109  // Check for conversion failure.
3110  if (Result != conversionOK)
3111  Diag(Arg->getLocStart(),
3112  diag::warn_cfstring_truncated) << Arg->getSourceRange();
3113  }
3114  return false;
3115 }
3116 
3117 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
3118 /// for validity. Emit an error and return true on failure; return false
3119 /// on success.
3120 bool Sema::SemaBuiltinVAStartImpl(CallExpr *TheCall) {
3121  Expr *Fn = TheCall->getCallee();
3122  if (TheCall->getNumArgs() > 2) {
3123  Diag(TheCall->getArg(2)->getLocStart(),
3124  diag::err_typecheck_call_too_many_args)
3125  << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3126  << Fn->getSourceRange()
3127  << SourceRange(TheCall->getArg(2)->getLocStart(),
3128  (*(TheCall->arg_end()-1))->getLocEnd());
3129  return true;
3130  }
3131 
3132  if (TheCall->getNumArgs() < 2) {
3133  return Diag(TheCall->getLocEnd(),
3134  diag::err_typecheck_call_too_few_args_at_least)
3135  << 0 /*function call*/ << 2 << TheCall->getNumArgs();
3136  }
3137 
3138  // Type-check the first argument normally.
3139  if (checkBuiltinArgument(*this, TheCall, 0))
3140  return true;
3141 
3142  // Determine whether the current function is variadic or not.
3143  BlockScopeInfo *CurBlock = getCurBlock();
3144  bool isVariadic;
3145  if (CurBlock)
3146  isVariadic = CurBlock->TheDecl->isVariadic();
3147  else if (FunctionDecl *FD = getCurFunctionDecl())
3148  isVariadic = FD->isVariadic();
3149  else
3150  isVariadic = getCurMethodDecl()->isVariadic();
3151 
3152  if (!isVariadic) {
3153  Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
3154  return true;
3155  }
3156 
3157  // Verify that the second argument to the builtin is the last argument of the
3158  // current function or method.
3159  bool SecondArgIsLastNamedArgument = false;
3160  const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
3161 
3162  // These are valid if SecondArgIsLastNamedArgument is false after the next
3163  // block.
3164  QualType Type;
3165  SourceLocation ParamLoc;
3166  bool IsCRegister = false;
3167 
3168  if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
3169  if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
3170  // FIXME: This isn't correct for methods (results in bogus warning).
3171  // Get the last formal in the current function.
3172  const ParmVarDecl *LastArg;
3173  if (CurBlock)
3174  LastArg = CurBlock->TheDecl->parameters().back();
3175  else if (FunctionDecl *FD = getCurFunctionDecl())
3176  LastArg = FD->parameters().back();
3177  else
3178  LastArg = getCurMethodDecl()->parameters().back();
3179  SecondArgIsLastNamedArgument = PV == LastArg;
3180 
3181  Type = PV->getType();
3182  ParamLoc = PV->getLocation();
3183  IsCRegister =
3184  PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
3185  }
3186  }
3187 
3188  if (!SecondArgIsLastNamedArgument)
3189  Diag(TheCall->getArg(1)->getLocStart(),
3190  diag::warn_second_arg_of_va_start_not_last_named_param);
3191  else if (IsCRegister || Type->isReferenceType() ||
3192  Type->isPromotableIntegerType() ||
3193  Type->isSpecificBuiltinType(BuiltinType::Float)) {
3194  unsigned Reason = 0;
3195  if (Type->isReferenceType()) Reason = 1;
3196  else if (IsCRegister) Reason = 2;
3197  Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
3198  Diag(ParamLoc, diag::note_parameter_type) << Type;
3199  }
3200 
3201  TheCall->setType(Context.VoidTy);
3202  return false;
3203 }
3204 
3205 /// Check the arguments to '__builtin_va_start' for validity, and that
3206 /// it was called from a function of the native ABI.
3207 /// Emit an error and return true on failure; return false on success.
3208 bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
3209  // On x86-64 Unix, don't allow this in Win64 ABI functions.
3210  // On x64 Windows, don't allow this in System V ABI functions.
3211  // (Yes, that means there's no corresponding way to support variadic
3212  // System V ABI functions on Windows.)
3213  if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64) {
3214  unsigned OS = Context.getTargetInfo().getTriple().getOS();
3215  clang::CallingConv CC = CC_C;
3216  if (const FunctionDecl *FD = getCurFunctionDecl())
3217  CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3218  if ((OS == llvm::Triple::Win32 && CC == CC_X86_64SysV) ||
3219  (OS != llvm::Triple::Win32 && CC == CC_X86_64Win64))
3220  return Diag(TheCall->getCallee()->getLocStart(),
3221  diag::err_va_start_used_in_wrong_abi_function)
3222  << (OS != llvm::Triple::Win32);
3223  }
3224  return SemaBuiltinVAStartImpl(TheCall);
3225 }
3226 
3227 /// Check the arguments to '__builtin_ms_va_start' for validity, and that
3228 /// it was called from a Win64 ABI function.
3229 /// Emit an error and return true on failure; return false on success.
3230 bool Sema::SemaBuiltinMSVAStart(CallExpr *TheCall) {
3231  // This only makes sense for x86-64.
3232  const llvm::Triple &TT = Context.getTargetInfo().getTriple();
3233  Expr *Callee = TheCall->getCallee();
3234  if (TT.getArch() != llvm::Triple::x86_64)
3235  return Diag(Callee->getLocStart(), diag::err_x86_builtin_32_bit_tgt);
3236  // Don't allow this in System V ABI functions.
3237  clang::CallingConv CC = CC_C;
3238  if (const FunctionDecl *FD = getCurFunctionDecl())
3239  CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3240  if (CC == CC_X86_64SysV ||
3241  (TT.getOS() != llvm::Triple::Win32 && CC != CC_X86_64Win64))
3242  return Diag(Callee->getLocStart(),
3243  diag::err_ms_va_start_used_in_sysv_function);
3244  return SemaBuiltinVAStartImpl(TheCall);
3245 }
3246 
3247 bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
3248  // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
3249  // const char *named_addr);
3250 
3251  Expr *Func = Call->getCallee();
3252 
3253  if (Call->getNumArgs() < 3)
3254  return Diag(Call->getLocEnd(),
3255  diag::err_typecheck_call_too_few_args_at_least)
3256  << 0 /*function call*/ << 3 << Call->getNumArgs();
3257 
3258  // Determine whether the current function is variadic or not.
3259  bool IsVariadic;
3260  if (BlockScopeInfo *CurBlock = getCurBlock())
3261  IsVariadic = CurBlock->TheDecl->isVariadic();
3262  else if (FunctionDecl *FD = getCurFunctionDecl())
3263  IsVariadic = FD->isVariadic();
3264  else if (ObjCMethodDecl *MD = getCurMethodDecl())
3265  IsVariadic = MD->isVariadic();
3266  else
3267  llvm_unreachable("unexpected statement type");
3268 
3269  if (!IsVariadic) {
3270  Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
3271  return true;
3272  }
3273 
3274  // Type-check the first argument normally.
3275  if (checkBuiltinArgument(*this, Call, 0))
3276  return true;
3277 
3278  const struct {
3279  unsigned ArgNo;
3280  QualType Type;
3281  } ArgumentTypes[] = {
3282  { 1, Context.getPointerType(Context.CharTy.withConst()) },
3283  { 2, Context.getSizeType() },
3284  };
3285 
3286  for (const auto &AT : ArgumentTypes) {
3287  const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
3288  if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
3289  continue;
3290  Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
3291  << Arg->getType() << AT.Type << 1 /* different class */
3292  << 0 /* qualifier difference */ << 3 /* parameter mismatch */
3293  << AT.ArgNo + 1 << Arg->getType() << AT.Type;
3294  }
3295 
3296  return false;
3297 }
3298 
3299 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
3300 /// friends. This is declared to take (...), so we have to check everything.
3301 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
3302  if (TheCall->getNumArgs() < 2)
3303  return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
3304  << 0 << 2 << TheCall->getNumArgs()/*function call*/;
3305  if (TheCall->getNumArgs() > 2)
3306  return Diag(TheCall->getArg(2)->getLocStart(),
3307  diag::err_typecheck_call_too_many_args)
3308  << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3309  << SourceRange(TheCall->getArg(2)->getLocStart(),
3310  (*(TheCall->arg_end()-1))->getLocEnd());
3311 
3312  ExprResult OrigArg0 = TheCall->getArg(0);
3313  ExprResult OrigArg1 = TheCall->getArg(1);
3314 
3315  // Do standard promotions between the two arguments, returning their common
3316  // type.
3317  QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
3318  if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
3319  return true;
3320 
3321  // Make sure any conversions are pushed back into the call; this is
3322  // type safe since unordered compare builtins are declared as "_Bool
3323  // foo(...)".
3324  TheCall->setArg(0, OrigArg0.get());
3325  TheCall->setArg(1, OrigArg1.get());
3326 
3327  if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
3328  return false;
3329 
3330  // If the common type isn't a real floating type, then the arguments were
3331  // invalid for this operation.
3332  if (Res.isNull() || !Res->isRealFloatingType())
3333  return Diag(OrigArg0.get()->getLocStart(),
3334  diag::err_typecheck_call_invalid_ordered_compare)
3335  << OrigArg0.get()->getType() << OrigArg1.get()->getType()
3336  << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
3337 
3338  return false;
3339 }
3340 
3341 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
3342 /// __builtin_isnan and friends. This is declared to take (...), so we have
3343 /// to check everything. We expect the last argument to be a floating point
3344 /// value.
3345 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
3346  if (TheCall->getNumArgs() < NumArgs)
3347  return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
3348  << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
3349  if (TheCall->getNumArgs() > NumArgs)
3350  return Diag(TheCall->getArg(NumArgs)->getLocStart(),
3351  diag::err_typecheck_call_too_many_args)
3352  << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
3353  << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
3354  (*(TheCall->arg_end()-1))->getLocEnd());
3355 
3356  Expr *OrigArg = TheCall->getArg(NumArgs-1);
3357 
3358  if (OrigArg->isTypeDependent())
3359  return false;
3360 
3361  // This operation requires a non-_Complex floating-point number.
3362  if (!OrigArg->getType()->isRealFloatingType())
3363  return Diag(OrigArg->getLocStart(),
3364  diag::err_typecheck_call_invalid_unary_fp)
3365  << OrigArg->getType() << OrigArg->getSourceRange();
3366 
3367  // If this is an implicit conversion from float -> double, remove it.
3368  if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
3369  Expr *CastArg = Cast->getSubExpr();
3370  if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
3371  assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
3372  "promotion from float to double is the only expected cast here");
3373  Cast->setSubExpr(nullptr);
3374  TheCall->setArg(NumArgs-1, CastArg);
3375  }
3376  }
3377 
3378  return false;
3379 }
3380 
3381 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
3382 // This is declared to take (...), so we have to check everything.
3384  if (TheCall->getNumArgs() < 2)
3385  return ExprError(Diag(TheCall->getLocEnd(),
3386  diag::err_typecheck_call_too_few_args_at_least)
3387  << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3388  << TheCall->getSourceRange());
3389 
3390  // Determine which of the following types of shufflevector we're checking:
3391  // 1) unary, vector mask: (lhs, mask)
3392  // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
3393  QualType resType = TheCall->getArg(0)->getType();
3394  unsigned numElements = 0;
3395 
3396  if (!TheCall->getArg(0)->isTypeDependent() &&
3397  !TheCall->getArg(1)->isTypeDependent()) {
3398  QualType LHSType = TheCall->getArg(0)->getType();
3399  QualType RHSType = TheCall->getArg(1)->getType();
3400 
3401  if (!LHSType->isVectorType() || !RHSType->isVectorType())
3402  return ExprError(Diag(TheCall->getLocStart(),
3403  diag::err_shufflevector_non_vector)
3404  << SourceRange(TheCall->getArg(0)->getLocStart(),
3405  TheCall->getArg(1)->getLocEnd()));
3406 
3407  numElements = LHSType->getAs<VectorType>()->getNumElements();
3408  unsigned numResElements = TheCall->getNumArgs() - 2;
3409 
3410  // Check to see if we have a call with 2 vector arguments, the unary shuffle
3411  // with mask. If so, verify that RHS is an integer vector type with the
3412  // same number of elts as lhs.
3413  if (TheCall->getNumArgs() == 2) {
3414  if (!RHSType->hasIntegerRepresentation() ||
3415  RHSType->getAs<VectorType>()->getNumElements() != numElements)
3416  return ExprError(Diag(TheCall->getLocStart(),
3417  diag::err_shufflevector_incompatible_vector)
3418  << SourceRange(TheCall->getArg(1)->getLocStart(),
3419  TheCall->getArg(1)->getLocEnd()));
3420  } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
3421  return ExprError(Diag(TheCall->getLocStart(),
3422  diag::err_shufflevector_incompatible_vector)
3423  << SourceRange(TheCall->getArg(0)->getLocStart(),
3424  TheCall->getArg(1)->getLocEnd()));
3425  } else if (numElements != numResElements) {
3426  QualType eltType = LHSType->getAs<VectorType>()->getElementType();
3427  resType = Context.getVectorType(eltType, numResElements,
3429  }
3430  }
3431 
3432  for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
3433  if (TheCall->getArg(i)->isTypeDependent() ||
3434  TheCall->getArg(i)->isValueDependent())
3435  continue;
3436 
3437  llvm::APSInt Result(32);
3438  if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
3439  return ExprError(Diag(TheCall->getLocStart(),
3440  diag::err_shufflevector_nonconstant_argument)
3441  << TheCall->getArg(i)->getSourceRange());
3442 
3443  // Allow -1 which will be translated to undef in the IR.
3444  if (Result.isSigned() && Result.isAllOnesValue())
3445  continue;
3446 
3447  if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
3448  return ExprError(Diag(TheCall->getLocStart(),
3449  diag::err_shufflevector_argument_too_large)
3450  << TheCall->getArg(i)->getSourceRange());
3451  }
3452 
3453  SmallVector<Expr*, 32> exprs;
3454 
3455  for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
3456  exprs.push_back(TheCall->getArg(i));
3457  TheCall->setArg(i, nullptr);
3458  }
3459 
3460  return new (Context) ShuffleVectorExpr(Context, exprs, resType,
3461  TheCall->getCallee()->getLocStart(),
3462  TheCall->getRParenLoc());
3463 }
3464 
3465 /// SemaConvertVectorExpr - Handle __builtin_convertvector
3467  SourceLocation BuiltinLoc,
3468  SourceLocation RParenLoc) {
3469  ExprValueKind VK = VK_RValue;
3471  QualType DstTy = TInfo->getType();
3472  QualType SrcTy = E->getType();
3473 
3474  if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
3475  return ExprError(Diag(BuiltinLoc,
3476  diag::err_convertvector_non_vector)
3477  << E->getSourceRange());
3478  if (!DstTy->isVectorType() && !DstTy->isDependentType())
3479  return ExprError(Diag(BuiltinLoc,
3480  diag::err_convertvector_non_vector_type));
3481 
3482  if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
3483  unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
3484  unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
3485  if (SrcElts != DstElts)
3486  return ExprError(Diag(BuiltinLoc,
3487  diag::err_convertvector_incompatible_vector)
3488  << E->getSourceRange());
3489  }
3490 
3491  return new (Context)
3492  ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
3493 }
3494 
3495 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
3496 // This is declared to take (const void*, ...) and can take two
3497 // optional constant int args.
3498 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
3499  unsigned NumArgs = TheCall->getNumArgs();
3500 
3501  if (NumArgs > 3)
3502  return Diag(TheCall->getLocEnd(),
3503  diag::err_typecheck_call_too_many_args_at_most)
3504  << 0 /*function call*/ << 3 << NumArgs
3505  << TheCall->getSourceRange();
3506 
3507  // Argument 0 is checked for us and the remaining arguments must be
3508  // constant integers.
3509  for (unsigned i = 1; i != NumArgs; ++i)
3510  if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
3511  return true;
3512 
3513  return false;
3514 }
3515 
3516 /// SemaBuiltinAssume - Handle __assume (MS Extension).
3517 // __assume does not evaluate its arguments, and should warn if its argument
3518 // has side effects.
3519 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
3520  Expr *Arg = TheCall->getArg(0);
3521  if (Arg->isInstantiationDependent()) return false;
3522 
3523  if (Arg->HasSideEffects(Context))
3524  Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
3525  << Arg->getSourceRange()
3526  << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
3527 
3528  return false;
3529 }
3530 
3531 /// Handle __builtin_assume_aligned. This is declared
3532 /// as (const void*, size_t, ...) and can take one optional constant int arg.
3533 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
3534  unsigned NumArgs = TheCall->getNumArgs();
3535 
3536  if (NumArgs > 3)
3537  return Diag(TheCall->getLocEnd(),
3538  diag::err_typecheck_call_too_many_args_at_most)
3539  << 0 /*function call*/ << 3 << NumArgs
3540  << TheCall->getSourceRange();
3541 
3542  // The alignment must be a constant integer.
3543  Expr *Arg = TheCall->getArg(1);
3544 
3545  // We can't check the value of a dependent argument.
3546  if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
3547  llvm::APSInt Result;
3548  if (SemaBuiltinConstantArg(TheCall, 1, Result))
3549  return true;
3550 
3551  if (!Result.isPowerOf2())
3552  return Diag(TheCall->getLocStart(),
3553  diag::err_alignment_not_power_of_two)
3554  << Arg->getSourceRange();
3555  }
3556 
3557  if (NumArgs > 2) {
3558  ExprResult Arg(TheCall->getArg(2));
3560  Context.getSizeType(), false);
3561  Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3562  if (Arg.isInvalid()) return true;
3563  TheCall->setArg(2, Arg.get());
3564  }
3565 
3566  return false;
3567 }
3568 
3569 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
3570 /// TheCall is a constant expression.
3571 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
3572  llvm::APSInt &Result) {
3573  Expr *Arg = TheCall->getArg(ArgNum);
3574  DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3575  FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3576 
3577  if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
3578 
3579  if (!Arg->isIntegerConstantExpr(Result, Context))
3580  return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
3581  << FDecl->getDeclName() << Arg->getSourceRange();
3582 
3583  return false;
3584 }
3585 
3586 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
3587 /// TheCall is a constant expression in the range [Low, High].
3588 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
3589  int Low, int High) {
3590  llvm::APSInt Result;
3591 
3592  // We can't check the value of a dependent argument.
3593  Expr *Arg = TheCall->getArg(ArgNum);
3594  if (Arg->isTypeDependent() || Arg->isValueDependent())
3595  return false;
3596 
3597  // Check constant-ness first.
3598  if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3599  return true;
3600 
3601  if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
3602  return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
3603  << Low << High << Arg->getSourceRange();
3604 
3605  return false;
3606 }
3607 
3608 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
3609 /// TheCall is an ARM/AArch64 special register string literal.
3610 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
3611  int ArgNum, unsigned ExpectedFieldNum,
3612  bool AllowName) {
3613  bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
3614  BuiltinID == ARM::BI__builtin_arm_wsr64 ||
3615  BuiltinID == ARM::BI__builtin_arm_rsr ||
3616  BuiltinID == ARM::BI__builtin_arm_rsrp ||
3617  BuiltinID == ARM::BI__builtin_arm_wsr ||
3618  BuiltinID == ARM::BI__builtin_arm_wsrp;
3619  bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
3620  BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
3621  BuiltinID == AArch64::BI__builtin_arm_rsr ||
3622  BuiltinID == AArch64::BI__builtin_arm_rsrp ||
3623  BuiltinID == AArch64::BI__builtin_arm_wsr ||
3624  BuiltinID == AArch64::BI__builtin_arm_wsrp;
3625  assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
3626 
3627  // We can't check the value of a dependent argument.
3628  Expr *Arg = TheCall->getArg(ArgNum);
3629  if (Arg->isTypeDependent() || Arg->isValueDependent())
3630  return false;
3631 
3632  // Check if the argument is a string literal.
3633  if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3634  return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
3635  << Arg->getSourceRange();
3636 
3637  // Check the type of special register given.
3638  StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3640  Reg.split(Fields, ":");
3641 
3642  if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
3643  return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
3644  << Arg->getSourceRange();
3645 
3646  // If the string is the name of a register then we cannot check that it is
3647  // valid here but if the string is of one the forms described in ACLE then we
3648  // can check that the supplied fields are integers and within the valid
3649  // ranges.
3650  if (Fields.size() > 1) {
3651  bool FiveFields = Fields.size() == 5;
3652 
3653  bool ValidString = true;
3654  if (IsARMBuiltin) {
3655  ValidString &= Fields[0].startswith_lower("cp") ||
3656  Fields[0].startswith_lower("p");
3657  if (ValidString)
3658  Fields[0] =
3659  Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
3660 
3661  ValidString &= Fields[2].startswith_lower("c");
3662  if (ValidString)
3663  Fields[2] = Fields[2].drop_front(1);
3664 
3665  if (FiveFields) {
3666  ValidString &= Fields[3].startswith_lower("c");
3667  if (ValidString)
3668  Fields[3] = Fields[3].drop_front(1);
3669  }
3670  }
3671 
3672  SmallVector<int, 5> Ranges;
3673  if (FiveFields)
3674  Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 7, 15, 15});
3675  else
3676  Ranges.append({15, 7, 15});
3677 
3678  for (unsigned i=0; i<Fields.size(); ++i) {
3679  int IntField;
3680  ValidString &= !Fields[i].getAsInteger(10, IntField);
3681  ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
3682  }
3683 
3684  if (!ValidString)
3685  return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
3686  << Arg->getSourceRange();
3687 
3688  } else if (IsAArch64Builtin && Fields.size() == 1) {
3689  // If the register name is one of those that appear in the condition below
3690  // and the special register builtin being used is one of the write builtins,
3691  // then we require that the argument provided for writing to the register
3692  // is an integer constant expression. This is because it will be lowered to
3693  // an MSR (immediate) instruction, so we need to know the immediate at
3694  // compile time.
3695  if (TheCall->getNumArgs() != 2)
3696  return false;
3697 
3698  std::string RegLower = Reg.lower();
3699  if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
3700  RegLower != "pan" && RegLower != "uao")
3701  return false;
3702 
3703  return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
3704  }
3705 
3706  return false;
3707 }
3708 
3709 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
3710 /// This checks that the target supports __builtin_longjmp and
3711 /// that val is a constant 1.
3712 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
3713  if (!Context.getTargetInfo().hasSjLjLowering())
3714  return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
3715  << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
3716 
3717  Expr *Arg = TheCall->getArg(1);
3718  llvm::APSInt Result;
3719 
3720  // TODO: This is less than ideal. Overload this to take a value.
3721  if (SemaBuiltinConstantArg(TheCall, 1, Result))
3722  return true;
3723 
3724  if (Result != 1)
3725  return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
3726  << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
3727 
3728  return false;
3729 }
3730 
3731 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
3732 /// This checks that the target supports __builtin_setjmp.
3733 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
3734  if (!Context.getTargetInfo().hasSjLjLowering())
3735  return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
3736  << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
3737  return false;
3738 }
3739 
3740 namespace {
3741 class UncoveredArgHandler {
3742  enum { Unknown = -1, AllCovered = -2 };
3743  signed FirstUncoveredArg;
3744  SmallVector<const Expr *, 4> DiagnosticExprs;
3745 
3746 public:
3747  UncoveredArgHandler() : FirstUncoveredArg(Unknown) { }
3748 
3749  bool hasUncoveredArg() const {
3750  return (FirstUncoveredArg >= 0);
3751  }
3752 
3753  unsigned getUncoveredArg() const {
3754  assert(hasUncoveredArg() && "no uncovered argument");
3755  return FirstUncoveredArg;
3756  }
3757 
3758  void setAllCovered() {
3759  // A string has been found with all arguments covered, so clear out
3760  // the diagnostics.
3761  DiagnosticExprs.clear();
3762  FirstUncoveredArg = AllCovered;
3763  }
3764 
3765  void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
3766  assert(NewFirstUncoveredArg >= 0 && "Outside range");
3767 
3768  // Don't update if a previous string covers all arguments.
3769  if (FirstUncoveredArg == AllCovered)
3770  return;
3771 
3772  // UncoveredArgHandler tracks the highest uncovered argument index
3773  // and with it all the strings that match this index.
3774  if (NewFirstUncoveredArg == FirstUncoveredArg)
3775  DiagnosticExprs.push_back(StrExpr);
3776  else if (NewFirstUncoveredArg > FirstUncoveredArg) {
3777  DiagnosticExprs.clear();
3778  DiagnosticExprs.push_back(StrExpr);
3779  FirstUncoveredArg = NewFirstUncoveredArg;
3780  }
3781  }
3782 
3783  void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
3784 };
3785 
3787  SLCT_NotALiteral,
3788  SLCT_UncheckedLiteral,
3789  SLCT_CheckedLiteral
3790 };
3791 } // end anonymous namespace
3792 
3793 static void CheckFormatString(Sema &S, const StringLiteral *FExpr,
3794  const Expr *OrigFormatExpr,
3795  ArrayRef<const Expr *> Args,
3796  bool HasVAListArg, unsigned format_idx,
3797  unsigned firstDataArg,
3799  bool inFunctionCall,
3800  Sema::VariadicCallType CallType,
3801  llvm::SmallBitVector &CheckedVarArgs,
3802  UncoveredArgHandler &UncoveredArg);
3803 
3804 // Determine if an expression is a string literal or constant string.
3805 // If this function returns false on the arguments to a function expecting a
3806 // format string, we will usually need to emit a warning.
3807 // True string literals are then checked by CheckFormatString.
3809 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
3810  bool HasVAListArg, unsigned format_idx,
3811  unsigned firstDataArg, Sema::FormatStringType Type,
3812  Sema::VariadicCallType CallType, bool InFunctionCall,
3813  llvm::SmallBitVector &CheckedVarArgs,
3814  UncoveredArgHandler &UncoveredArg) {
3815  tryAgain:
3816  if (E->isTypeDependent() || E->isValueDependent())
3817  return SLCT_NotALiteral;
3818 
3819  E = E->IgnoreParenCasts();
3820 
3822  // Technically -Wformat-nonliteral does not warn about this case.
3823  // The behavior of printf and friends in this case is implementation
3824  // dependent. Ideally if the format string cannot be null then
3825  // it should have a 'nonnull' attribute in the function prototype.
3826  return SLCT_UncheckedLiteral;
3827 
3828  switch (E->getStmtClass()) {
3829  case Stmt::BinaryConditionalOperatorClass:
3830  case Stmt::ConditionalOperatorClass: {
3831  // The expression is a literal if both sub-expressions were, and it was
3832  // completely checked only if both sub-expressions were checked.
3833  const AbstractConditionalOperator *C =
3834  cast<AbstractConditionalOperator>(E);
3835 
3836  // Determine whether it is necessary to check both sub-expressions, for
3837  // example, because the condition expression is a constant that can be
3838  // evaluated at compile time.
3839  bool CheckLeft = true, CheckRight = true;
3840 
3841  bool Cond;
3842  if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
3843  if (Cond)
3844  CheckRight = false;
3845  else
3846  CheckLeft = false;
3847  }
3848 
3850  if (!CheckLeft)
3851  Left = SLCT_UncheckedLiteral;
3852  else {
3853  Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
3854  HasVAListArg, format_idx, firstDataArg,
3855  Type, CallType, InFunctionCall,
3856  CheckedVarArgs, UncoveredArg);
3857  if (Left == SLCT_NotALiteral || !CheckRight)
3858  return Left;
3859  }
3860 
3861  StringLiteralCheckType Right =
3862  checkFormatStringExpr(S, C->getFalseExpr(), Args,
3863  HasVAListArg, format_idx, firstDataArg,
3864  Type, CallType, InFunctionCall, CheckedVarArgs,
3865  UncoveredArg);
3866 
3867  return (CheckLeft && Left < Right) ? Left : Right;
3868  }
3869 
3870  case Stmt::ImplicitCastExprClass: {
3871  E = cast<ImplicitCastExpr>(E)->getSubExpr();
3872  goto tryAgain;
3873  }
3874 
3875  case Stmt::OpaqueValueExprClass:
3876  if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
3877  E = src;
3878  goto tryAgain;
3879  }
3880  return SLCT_NotALiteral;
3881 
3882  case Stmt::PredefinedExprClass:
3883  // While __func__, etc., are technically not string literals, they
3884  // cannot contain format specifiers and thus are not a security
3885  // liability.
3886  return SLCT_UncheckedLiteral;
3887 
3888  case Stmt::DeclRefExprClass: {
3889  const DeclRefExpr *DR = cast<DeclRefExpr>(E);
3890 
3891  // As an exception, do not flag errors for variables binding to
3892  // const string literals.
3893  if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
3894  bool isConstant = false;
3895  QualType T = DR->getType();
3896 
3897  if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
3898  isConstant = AT->getElementType().isConstant(S.Context);
3899  } else if (const PointerType *PT = T->getAs<PointerType>()) {
3900  isConstant = T.isConstant(S.Context) &&
3901  PT->getPointeeType().isConstant(S.Context);
3902  } else if (T->isObjCObjectPointerType()) {
3903  // In ObjC, there is usually no "const ObjectPointer" type,
3904  // so don't check if the pointee type is constant.
3905  isConstant = T.isConstant(S.Context);
3906  }
3907 
3908  if (isConstant) {
3909  if (const Expr *Init = VD->getAnyInitializer()) {
3910  // Look through initializers like const char c[] = { "foo" }
3911  if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
3912  if (InitList->isStringLiteralInit())
3913  Init = InitList->getInit(0)->IgnoreParenImpCasts();
3914  }
3915  return checkFormatStringExpr(S, Init, Args,
3916  HasVAListArg, format_idx,
3917  firstDataArg, Type, CallType,
3918  /*InFunctionCall*/false, CheckedVarArgs,
3919  UncoveredArg);
3920  }
3921  }
3922 
3923  // For vprintf* functions (i.e., HasVAListArg==true), we add a
3924  // special check to see if the format string is a function parameter
3925  // of the function calling the printf function. If the function
3926  // has an attribute indicating it is a printf-like function, then we
3927  // should suppress warnings concerning non-literals being used in a call
3928  // to a vprintf function. For example:
3929  //
3930  // void
3931  // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
3932  // va_list ap;
3933  // va_start(ap, fmt);
3934  // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
3935  // ...
3936  // }
3937  if (HasVAListArg) {
3938  if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
3939  if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
3940  int PVIndex = PV->getFunctionScopeIndex() + 1;
3941  for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
3942  // adjust for implicit parameter
3943  if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
3944  if (MD->isInstance())
3945  ++PVIndex;
3946  // We also check if the formats are compatible.
3947  // We can't pass a 'scanf' string to a 'printf' function.
3948  if (PVIndex == PVFormat->getFormatIdx() &&
3949  Type == S.GetFormatStringType(PVFormat))
3950  return SLCT_UncheckedLiteral;
3951  }
3952  }
3953  }
3954  }
3955  }
3956 
3957  return SLCT_NotALiteral;
3958  }
3959 
3960  case Stmt::CallExprClass:
3961  case Stmt::CXXMemberCallExprClass: {
3962  const CallExpr *CE = cast<CallExpr>(E);
3963  if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
3964  if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
3965  unsigned ArgIndex = FA->getFormatIdx();
3966  if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
3967  if (MD->isInstance())
3968  --ArgIndex;
3969  const Expr *Arg = CE->getArg(ArgIndex - 1);
3970 
3971  return checkFormatStringExpr(S, Arg, Args,
3972  HasVAListArg, format_idx, firstDataArg,
3973  Type, CallType, InFunctionCall,
3974  CheckedVarArgs, UncoveredArg);
3975  } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
3976  unsigned BuiltinID = FD->getBuiltinID();
3977  if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
3978  BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
3979  const Expr *Arg = CE->getArg(0);
3980  return checkFormatStringExpr(S, Arg, Args,
3981  HasVAListArg, format_idx,
3982  firstDataArg, Type, CallType,
3983  InFunctionCall, CheckedVarArgs,
3984  UncoveredArg);
3985  }
3986  }
3987  }
3988 
3989  return SLCT_NotALiteral;
3990  }
3991  case Stmt::ObjCStringLiteralClass:
3992  case Stmt::StringLiteralClass: {
3993  const StringLiteral *StrE = nullptr;
3994 
3995  if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
3996  StrE = ObjCFExpr->getString();
3997  else
3998  StrE = cast<StringLiteral>(E);
3999 
4000  if (StrE) {
4001  CheckFormatString(S, StrE, E, Args, HasVAListArg, format_idx,
4002  firstDataArg, Type, InFunctionCall, CallType,
4003  CheckedVarArgs, UncoveredArg);
4004  return SLCT_CheckedLiteral;
4005  }
4006 
4007  return SLCT_NotALiteral;
4008  }
4009 
4010  default:
4011  return SLCT_NotALiteral;
4012  }
4013 }
4014 
4016  return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
4017  .Case("scanf", FST_Scanf)
4018  .Cases("printf", "printf0", FST_Printf)
4019  .Cases("NSString", "CFString", FST_NSString)
4020  .Case("strftime", FST_Strftime)
4021  .Case("strfmon", FST_Strfmon)
4022  .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
4023  .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
4024  .Case("os_trace", FST_OSTrace)
4025  .Default(FST_Unknown);
4026 }
4027 
4028 /// CheckFormatArguments - Check calls to printf and scanf (and similar
4029 /// functions) for correct use of format strings.
4030 /// Returns true if a format string has been fully checked.
4031 bool Sema::CheckFormatArguments(const FormatAttr *Format,
4033  bool IsCXXMember,
4034  VariadicCallType CallType,
4035  SourceLocation Loc, SourceRange Range,
4036  llvm::SmallBitVector &CheckedVarArgs) {
4037  FormatStringInfo FSI;
4038  if (getFormatStringInfo(Format, IsCXXMember, &FSI))
4039  return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
4040  FSI.FirstDataArg, GetFormatStringType(Format),
4041  CallType, Loc, Range, CheckedVarArgs);
4042  return false;
4043 }
4044 
4045 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
4046  bool HasVAListArg, unsigned format_idx,
4047  unsigned firstDataArg, FormatStringType Type,
4048  VariadicCallType CallType,
4049  SourceLocation Loc, SourceRange Range,
4050  llvm::SmallBitVector &CheckedVarArgs) {
4051  // CHECK: printf/scanf-like function is called with no format string.
4052  if (format_idx >= Args.size()) {
4053  Diag(Loc, diag::warn_missing_format_string) << Range;
4054  return false;
4055  }
4056 
4057  const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
4058 
4059  // CHECK: format string is not a string literal.
4060  //
4061  // Dynamically generated format strings are difficult to
4062  // automatically vet at compile time. Requiring that format strings
4063  // are string literals: (1) permits the checking of format strings by
4064  // the compiler and thereby (2) can practically remove the source of
4065  // many format string exploits.
4066 
4067  // Format string can be either ObjC string (e.g. @"%d") or
4068  // C string (e.g. "%d")
4069  // ObjC string uses the same format specifiers as C string, so we can use
4070  // the same format string checking logic for both ObjC and C strings.
4071  UncoveredArgHandler UncoveredArg;
4073  checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
4074  format_idx, firstDataArg, Type, CallType,
4075  /*IsFunctionCall*/true, CheckedVarArgs,
4076  UncoveredArg);
4077 
4078  // Generate a diagnostic where an uncovered argument is detected.
4079  if (UncoveredArg.hasUncoveredArg()) {
4080  unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
4081  assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
4082  UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
4083  }
4084 
4085  if (CT != SLCT_NotALiteral)
4086  // Literal format string found, check done!
4087  return CT == SLCT_CheckedLiteral;
4088 
4089  // Strftime is particular as it always uses a single 'time' argument,
4090  // so it is safe to pass a non-literal string.
4091  if (Type == FST_Strftime)
4092  return false;
4093 
4094  // Do not emit diag when the string param is a macro expansion and the
4095  // format is either NSString or CFString. This is a hack to prevent
4096  // diag when using the NSLocalizedString and CFCopyLocalizedString macros
4097  // which are usually used in place of NS and CF string literals.
4098  SourceLocation FormatLoc = Args[format_idx]->getLocStart();
4099  if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
4100  return false;
4101 
4102  // If there are no arguments specified, warn with -Wformat-security, otherwise
4103  // warn only with -Wformat-nonliteral.
4104  if (Args.size() == firstDataArg) {
4105  Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
4106  << OrigFormatExpr->getSourceRange();
4107  switch (Type) {
4108  default:
4109  break;
4110  case FST_Kprintf:
4111  case FST_FreeBSDKPrintf:
4112  case FST_Printf:
4113  Diag(FormatLoc, diag::note_format_security_fixit)
4114  << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
4115  break;
4116  case FST_NSString:
4117  Diag(FormatLoc, diag::note_format_security_fixit)
4118  << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
4119  break;
4120  }
4121  } else {
4122  Diag(FormatLoc, diag::warn_format_nonliteral)
4123  << OrigFormatExpr->getSourceRange();
4124  }
4125  return false;
4126 }
4127 
4128 namespace {
4129 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
4130 protected:
4131  Sema &S;
4132  const StringLiteral *FExpr;
4133  const Expr *OrigFormatExpr;
4134  const unsigned FirstDataArg;
4135  const unsigned NumDataArgs;
4136  const char *Beg; // Start of format string.
4137  const bool HasVAListArg;
4138  ArrayRef<const Expr *> Args;
4139  unsigned FormatIdx;
4140  llvm::SmallBitVector CoveredArgs;
4141  bool usesPositionalArgs;
4142  bool atFirstArg;
4143  bool inFunctionCall;
4144  Sema::VariadicCallType CallType;
4145  llvm::SmallBitVector &CheckedVarArgs;
4146  UncoveredArgHandler &UncoveredArg;
4147 
4148 public:
4149  CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
4150  const Expr *origFormatExpr, unsigned firstDataArg,
4151  unsigned numDataArgs, const char *beg, bool hasVAListArg,
4152  ArrayRef<const Expr *> Args,
4153  unsigned formatIdx, bool inFunctionCall,
4154  Sema::VariadicCallType callType,
4155  llvm::SmallBitVector &CheckedVarArgs,
4156  UncoveredArgHandler &UncoveredArg)
4157  : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
4158  FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
4159  Beg(beg), HasVAListArg(hasVAListArg),
4160  Args(Args), FormatIdx(formatIdx),
4161  usesPositionalArgs(false), atFirstArg(true),
4162  inFunctionCall(inFunctionCall), CallType(callType),
4163  CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
4164  CoveredArgs.resize(numDataArgs);
4165  CoveredArgs.reset();
4166  }
4167 
4168  void DoneProcessing();
4169 
4170  void HandleIncompleteSpecifier(const char *startSpecifier,
4171  unsigned specifierLen) override;
4172 
4173  void HandleInvalidLengthModifier(
4176  const char *startSpecifier, unsigned specifierLen,
4177  unsigned DiagID);
4178 
4179  void HandleNonStandardLengthModifier(
4181  const char *startSpecifier, unsigned specifierLen);
4182 
4183  void HandleNonStandardConversionSpecifier(
4185  const char *startSpecifier, unsigned specifierLen);
4186 
4187  void HandlePosition(const char *startPos, unsigned posLen) override;
4188 
4189  void HandleInvalidPosition(const char *startSpecifier,
4190  unsigned specifierLen,
4192 
4193  void HandleZeroPosition(const char *startPos, unsigned posLen) override;
4194 
4195  void HandleNullChar(const char *nullCharacter) override;
4196 
4197  template <typename Range>
4198  static void
4199  EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
4200  const PartialDiagnostic &PDiag, SourceLocation StringLoc,
4201  bool IsStringLocation, Range StringRange,
4202  ArrayRef<FixItHint> Fixit = None);
4203 
4204 protected:
4205  bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
4206  const char *startSpec,
4207  unsigned specifierLen,
4208  const char *csStart, unsigned csLen);
4209 
4210  void HandlePositionalNonpositionalArgs(SourceLocation Loc,
4211  const char *startSpec,
4212  unsigned specifierLen);
4213 
4214  SourceRange getFormatStringRange();
4215  CharSourceRange getSpecifierRange(const char *startSpecifier,
4216  unsigned specifierLen);
4217  SourceLocation getLocationOfByte(const char *x);
4218 
4219  const Expr *getDataArg(unsigned i) const;
4220 
4221  bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
4223  const char *startSpecifier, unsigned specifierLen,
4224  unsigned argIndex);
4225 
4226  template <typename Range>
4227  void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
4228  bool IsStringLocation, Range StringRange,
4229  ArrayRef<FixItHint> Fixit = None);
4230 };
4231 } // end anonymous namespace
4232 
4233 SourceRange CheckFormatHandler::getFormatStringRange() {
4234  return OrigFormatExpr->getSourceRange();
4235 }
4236 
4237 CharSourceRange CheckFormatHandler::
4238 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
4239  SourceLocation Start = getLocationOfByte(startSpecifier);
4240  SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
4241 
4242  // Advance the end SourceLocation by one due to half-open ranges.
4243  End = End.getLocWithOffset(1);
4244 
4245  return CharSourceRange::getCharRange(Start, End);
4246 }
4247 
4248 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
4249  return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
4250 }
4251 
4252 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
4253  unsigned specifierLen){
4254  EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
4255  getLocationOfByte(startSpecifier),
4256  /*IsStringLocation*/true,
4257  getSpecifierRange(startSpecifier, specifierLen));
4258 }
4259 
4260 void CheckFormatHandler::HandleInvalidLengthModifier(
4263  const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
4264  using namespace analyze_format_string;
4265 
4266  const LengthModifier &LM = FS.getLengthModifier();
4267  CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
4268 
4269  // See if we know how to fix this length modifier.
4270  Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
4271  if (FixedLM) {
4272  EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
4273  getLocationOfByte(LM.getStart()),
4274  /*IsStringLocation*/true,
4275  getSpecifierRange(startSpecifier, specifierLen));
4276 
4277  S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
4278  << FixedLM->toString()
4279  << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
4280 
4281  } else {
4282  FixItHint Hint;
4283  if (DiagID == diag::warn_format_nonsensical_length)
4284  Hint = FixItHint::CreateRemoval(LMRange);
4285 
4286  EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
4287  getLocationOfByte(LM.getStart()),
4288  /*IsStringLocation*/true,
4289  getSpecifierRange(startSpecifier, specifierLen),
4290  Hint);
4291  }
4292 }
4293 
4294 void CheckFormatHandler::HandleNonStandardLengthModifier(
4296  const char *startSpecifier, unsigned specifierLen) {
4297  using namespace analyze_format_string;
4298 
4299  const LengthModifier &LM = FS.getLengthModifier();
4300  CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
4301 
4302  // See if we know how to fix this length modifier.
4303  Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
4304  if (FixedLM) {
4305  EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4306  << LM.toString() << 0,
4307  getLocationOfByte(LM.getStart()),
4308  /*IsStringLocation*/true,
4309  getSpecifierRange(startSpecifier, specifierLen));
4310 
4311  S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
4312  << FixedLM->toString()
4313  << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
4314 
4315  } else {
4316  EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4317  << LM.toString() << 0,
4318  getLocationOfByte(LM.getStart()),
4319  /*IsStringLocation*/true,
4320  getSpecifierRange(startSpecifier, specifierLen));
4321  }
4322 }
4323 
4324 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
4326  const char *startSpecifier, unsigned specifierLen) {
4327  using namespace analyze_format_string;
4328 
4329  // See if we know how to fix this conversion specifier.
4330  Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
4331  if (FixedCS) {
4332  EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4333  << CS.toString() << /*conversion specifier*/1,
4334  getLocationOfByte(CS.getStart()),
4335  /*IsStringLocation*/true,
4336  getSpecifierRange(startSpecifier, specifierLen));
4337 
4338  CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
4339  S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
4340  << FixedCS->toString()
4341  << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
4342  } else {
4343  EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4344  << CS.toString() << /*conversion specifier*/1,
4345  getLocationOfByte(CS.getStart()),
4346  /*IsStringLocation*/true,
4347  getSpecifierRange(startSpecifier, specifierLen));
4348  }
4349 }
4350 
4351 void CheckFormatHandler::HandlePosition(const char *startPos,
4352  unsigned posLen) {
4353  EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
4354  getLocationOfByte(startPos),
4355  /*IsStringLocation*/true,
4356  getSpecifierRange(startPos, posLen));
4357 }
4358 
4359 void
4360 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
4362  EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
4363  << (unsigned) p,
4364  getLocationOfByte(startPos), /*IsStringLocation*/true,
4365  getSpecifierRange(startPos, posLen));
4366 }
4367 
4368 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
4369  unsigned posLen) {
4370  EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
4371  getLocationOfByte(startPos),
4372  /*IsStringLocation*/true,
4373  getSpecifierRange(startPos, posLen));
4374 }
4375 
4376 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
4377  if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
4378  // The presence of a null character is likely an error.
4379  EmitFormatDiagnostic(
4380  S.PDiag(diag::warn_printf_format_string_contains_null_char),
4381  getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
4382  getFormatStringRange());
4383  }
4384 }
4385 
4386 // Note that this may return NULL if there was an error parsing or building
4387 // one of the argument expressions.
4388 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
4389  return Args[FirstDataArg + i];
4390 }
4391 
4392 void CheckFormatHandler::DoneProcessing() {
4393  // Does the number of data arguments exceed the number of
4394  // format conversions in the format string?
4395  if (!HasVAListArg) {
4396  // Find any arguments that weren't covered.
4397  CoveredArgs.flip();
4398  signed notCoveredArg = CoveredArgs.find_first();
4399  if (notCoveredArg >= 0) {
4400  assert((unsigned)notCoveredArg < NumDataArgs);
4401  UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
4402  } else {
4403  UncoveredArg.setAllCovered();
4404  }
4405  }
4406 }
4407 
4408 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
4409  const Expr *ArgExpr) {
4410  assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
4411  "Invalid state");
4412 
4413  if (!ArgExpr)
4414  return;
4415 
4416  SourceLocation Loc = ArgExpr->getLocStart();
4417 
4418  if (S.getSourceManager().isInSystemMacro(Loc))
4419  return;
4420 
4421  PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
4422  for (auto E : DiagnosticExprs)
4423  PDiag << E->getSourceRange();
4424 
4425  CheckFormatHandler::EmitFormatDiagnostic(
4426  S, IsFunctionCall, DiagnosticExprs[0],
4427  PDiag, Loc, /*IsStringLocation*/false,
4428  DiagnosticExprs[0]->getSourceRange());
4429 }
4430 
4431 bool
4432 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
4433  SourceLocation Loc,
4434  const char *startSpec,
4435  unsigned specifierLen,
4436  const char *csStart,
4437  unsigned csLen) {
4438  bool keepGoing = true;
4439  if (argIndex < NumDataArgs) {
4440  // Consider the argument coverered, even though the specifier doesn't
4441  // make sense.
4442  CoveredArgs.set(argIndex);
4443  }
4444  else {
4445  // If argIndex exceeds the number of data arguments we
4446  // don't issue a warning because that is just a cascade of warnings (and
4447  // they may have intended '%%' anyway). We don't want to continue processing
4448  // the format string after this point, however, as we will like just get
4449  // gibberish when trying to match arguments.
4450  keepGoing = false;
4451  }
4452 
4453  StringRef Specifier(csStart, csLen);
4454 
4455  // If the specifier in non-printable, it could be the first byte of a UTF-8
4456  // sequence. In that case, print the UTF-8 code point. If not, print the byte
4457  // hex value.
4458  std::string CodePointStr;
4459  if (!llvm::sys::locale::isPrint(*csStart)) {
4460  UTF32 CodePoint;
4461  const UTF8 **B = reinterpret_cast<const UTF8 **>(&csStart);
4462  const UTF8 *E =
4463  reinterpret_cast<const UTF8 *>(csStart + csLen);
4464  ConversionResult Result =
4465  llvm::convertUTF8Sequence(B, E, &CodePoint, strictConversion);
4466 
4467  if (Result != conversionOK) {
4468  unsigned char FirstChar = *csStart;
4469  CodePoint = (UTF32)FirstChar;
4470  }
4471 
4472  llvm::raw_string_ostream OS(CodePointStr);
4473  if (CodePoint < 256)
4474  OS << "\\x" << llvm::format("%02x", CodePoint);
4475  else if (CodePoint <= 0xFFFF)
4476  OS << "\\u" << llvm::format("%04x", CodePoint);
4477  else
4478  OS << "\\U" << llvm::format("%08x", CodePoint);
4479  OS.flush();
4480  Specifier = CodePointStr;
4481  }
4482 
4483  EmitFormatDiagnostic(
4484  S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
4485  /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
4486 
4487  return keepGoing;
4488 }
4489 
4490 void
4491 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
4492  const char *startSpec,
4493  unsigned specifierLen) {
4494  EmitFormatDiagnostic(
4495  S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
4496  Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
4497 }
4498 
4499 bool
4500 CheckFormatHandler::CheckNumArgs(
4503  const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
4504 
4505  if (argIndex >= NumDataArgs) {
4507  ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
4508  << (argIndex+1) << NumDataArgs)
4509  : S.PDiag(diag::warn_printf_insufficient_data_args);
4510  EmitFormatDiagnostic(
4511  PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
4512  getSpecifierRange(startSpecifier, specifierLen));
4513 
4514  // Since more arguments than conversion tokens are given, by extension
4515  // all arguments are covered, so mark this as so.
4516  UncoveredArg.setAllCovered();
4517  return false;
4518  }
4519  return true;
4520 }
4521 
4522 template<typename Range>
4523 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
4524  SourceLocation Loc,
4525  bool IsStringLocation,
4526  Range StringRange,
4527  ArrayRef<FixItHint> FixIt) {
4528  EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
4529  Loc, IsStringLocation, StringRange, FixIt);
4530 }
4531 
4532 /// \brief If the format string is not within the funcion call, emit a note
4533 /// so that the function call and string are in diagnostic messages.
4534 ///
4535 /// \param InFunctionCall if true, the format string is within the function
4536 /// call and only one diagnostic message will be produced. Otherwise, an
4537 /// extra note will be emitted pointing to location of the format string.
4538 ///
4539 /// \param ArgumentExpr the expression that is passed as the format string
4540 /// argument in the function call. Used for getting locations when two
4541 /// diagnostics are emitted.
4542 ///
4543 /// \param PDiag the callee should already have provided any strings for the
4544 /// diagnostic message. This function only adds locations and fixits
4545 /// to diagnostics.
4546 ///
4547 /// \param Loc primary location for diagnostic. If two diagnostics are
4548 /// required, one will be at Loc and a new SourceLocation will be created for
4549 /// the other one.
4550 ///
4551 /// \param IsStringLocation if true, Loc points to the format string should be
4552 /// used for the note. Otherwise, Loc points to the argument list and will
4553 /// be used with PDiag.
4554 ///
4555 /// \param StringRange some or all of the string to highlight. This is
4556 /// templated so it can accept either a CharSourceRange or a SourceRange.
4557 ///
4558 /// \param FixIt optional fix it hint for the format string.
4559 template <typename Range>
4560 void CheckFormatHandler::EmitFormatDiagnostic(
4561  Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
4562  const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
4563  Range StringRange, ArrayRef<FixItHint> FixIt) {
4564  if (InFunctionCall) {
4565  const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
4566  D << StringRange;
4567  D << FixIt;
4568  } else {
4569  S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
4570  << ArgumentExpr->getSourceRange();
4571 
4573  S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
4574  diag::note_format_string_defined);
4575 
4576  Note << StringRange;
4577  Note << FixIt;
4578  }
4579 }
4580 
4581 //===--- CHECK: Printf format string checking ------------------------------===//
4582 
4583 namespace {
4584 class CheckPrintfHandler : public CheckFormatHandler {
4585  bool ObjCContext;
4586 
4587 public:
4588  CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
4589  const Expr *origFormatExpr, unsigned firstDataArg,
4590  unsigned numDataArgs, bool isObjC,
4591  const char *beg, bool hasVAListArg,
4592  ArrayRef<const Expr *> Args,
4593  unsigned formatIdx, bool inFunctionCall,
4594  Sema::VariadicCallType CallType,
4595  llvm::SmallBitVector &CheckedVarArgs,
4596  UncoveredArgHandler &UncoveredArg)
4597  : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
4598  numDataArgs, beg, hasVAListArg, Args,
4599  formatIdx, inFunctionCall, CallType, CheckedVarArgs,
4600  UncoveredArg),
4601  ObjCContext(isObjC)
4602  {}
4603 
4604  bool HandleInvalidPrintfConversionSpecifier(
4606  const char *startSpecifier,
4607  unsigned specifierLen) override;
4608 
4609  bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
4610  const char *startSpecifier,
4611  unsigned specifierLen) override;
4612  bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
4613  const char *StartSpecifier,
4614  unsigned SpecifierLen,
4615  const Expr *E);
4616 
4617  bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
4618  const char *startSpecifier, unsigned specifierLen);
4619  void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
4620  const analyze_printf::OptionalAmount &Amt,
4621  unsigned type,
4622  const char *startSpecifier, unsigned specifierLen);
4623  void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
4624  const analyze_printf::OptionalFlag &flag,
4625  const char *startSpecifier, unsigned specifierLen);
4626  void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
4627  const analyze_printf::OptionalFlag &ignoredFlag,
4628  const analyze_printf::OptionalFlag &flag,
4629  const char *startSpecifier, unsigned specifierLen);
4630  bool checkForCStrMembers(const analyze_printf::ArgType &AT,
4631  const Expr *E);
4632 
4633  void HandleEmptyObjCModifierFlag(const char *startFlag,
4634  unsigned flagLen) override;
4635 
4636  void HandleInvalidObjCModifierFlag(const char *startFlag,
4637  unsigned flagLen) override;
4638 
4639  void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
4640  const char *flagsEnd,
4641  const char *conversionPosition)
4642  override;
4643 };
4644 } // end anonymous namespace
4645 
4646 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
4648  const char *startSpecifier,
4649  unsigned specifierLen) {
4652 
4653  return HandleInvalidConversionSpecifier(FS.getArgIndex(),
4654  getLocationOfByte(CS.getStart()),
4655  startSpecifier, specifierLen,
4656  CS.getStart(), CS.getLength());
4657 }
4658 
4659 bool CheckPrintfHandler::HandleAmount(
4661  unsigned k, const char *startSpecifier,
4662  unsigned specifierLen) {
4663  if (Amt.hasDataArgument()) {
4664  if (!HasVAListArg) {
4665  unsigned argIndex = Amt.getArgIndex();
4666  if (argIndex >= NumDataArgs) {
4667  EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
4668  << k,
4669  getLocationOfByte(Amt.getStart()),
4670  /*IsStringLocation*/true,
4671  getSpecifierRange(startSpecifier, specifierLen));
4672  // Don't do any more checking. We will just emit
4673  // spurious errors.
4674  return false;
4675  }
4676 
4677  // Type check the data argument. It should be an 'int'.
4678  // Although not in conformance with C99, we also allow the argument to be
4679  // an 'unsigned int' as that is a reasonably safe case. GCC also
4680  // doesn't emit a warning for that case.
4681  CoveredArgs.set(argIndex);
4682  const Expr *Arg = getDataArg(argIndex);
4683  if (!Arg)
4684  return false;
4685 
4686  QualType T = Arg->getType();
4687 
4688  const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
4689  assert(AT.isValid());
4690 
4691  if (!AT.matchesType(S.Context, T)) {
4692  EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
4693  << k << AT.getRepresentativeTypeName(S.Context)
4694  << T << Arg->getSourceRange(),
4695  getLocationOfByte(Amt.getStart()),
4696  /*IsStringLocation*/true,
4697  getSpecifierRange(startSpecifier, specifierLen));
4698  // Don't do any more checking. We will just emit
4699  // spurious errors.
4700  return false;
4701  }
4702  }
4703  }
4704  return true;
4705 }
4706 
4707 void CheckPrintfHandler::HandleInvalidAmount(
4709  const analyze_printf::OptionalAmount &Amt,
4710  unsigned type,
4711  const char *startSpecifier,
4712  unsigned specifierLen) {
4715 
4716  FixItHint fixit =
4717  Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
4718  ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
4719  Amt.getConstantLength()))
4720  : FixItHint();
4721 
4722  EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
4723  << type << CS.toString(),
4724  getLocationOfByte(Amt.getStart()),
4725  /*IsStringLocation*/true,
4726  getSpecifierRange(startSpecifier, specifierLen),
4727  fixit);
4728 }
4729 
4730 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
4731  const analyze_printf::OptionalFlag &flag,
4732  const char *startSpecifier,
4733  unsigned specifierLen) {
4734  // Warn about pointless flag with a fixit removal.
4737  EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
4738  << flag.toString() << CS.toString(),
4739  getLocationOfByte(flag.getPosition()),
4740  /*IsStringLocation*/true,
4741  getSpecifierRange(startSpecifier, specifierLen),
4743  getSpecifierRange(flag.getPosition(), 1)));
4744 }
4745 
4746 void CheckPrintfHandler::HandleIgnoredFlag(
4748  const analyze_printf::OptionalFlag &ignoredFlag,
4749  const analyze_printf::OptionalFlag &flag,
4750  const char *startSpecifier,
4751  unsigned specifierLen) {
4752  // Warn about ignored flag with a fixit removal.
4753  EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
4754  << ignoredFlag.toString() << flag.toString(),
4755  getLocationOfByte(ignoredFlag.getPosition()),
4756  /*IsStringLocation*/true,
4757  getSpecifierRange(startSpecifier, specifierLen),
4759  getSpecifierRange(ignoredFlag.getPosition(), 1)));
4760 }
4761 
4762 // void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
4763 // bool IsStringLocation, Range StringRange,
4764 // ArrayRef<FixItHint> Fixit = None);
4765 
4766 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
4767  unsigned flagLen) {
4768  // Warn about an empty flag.
4769  EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
4770  getLocationOfByte(startFlag),
4771  /*IsStringLocation*/true,
4772  getSpecifierRange(startFlag, flagLen));
4773 }
4774 
4775 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
4776  unsigned flagLen) {
4777  // Warn about an invalid flag.
4778  auto Range = getSpecifierRange(startFlag, flagLen);
4779  StringRef flag(startFlag, flagLen);
4780  EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
4781  getLocationOfByte(startFlag),
4782  /*IsStringLocation*/true,
4783  Range, FixItHint::CreateRemoval(Range));
4784 }
4785 
4786 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
4787  const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
4788  // Warn about using '[...]' without a '@' conversion.
4789  auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
4790  auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
4791  EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
4792  getLocationOfByte(conversionPosition),
4793  /*IsStringLocation*/true,
4794  Range, FixItHint::CreateRemoval(Range));
4795 }
4796 
4797 // Determines if the specified is a C++ class or struct containing
4798 // a member with the specified name and kind (e.g. a CXXMethodDecl named
4799 // "c_str()").
4800 template<typename MemberKind>
4801 static llvm::SmallPtrSet<MemberKind*, 1>
4803  const RecordType *RT = Ty->getAs<RecordType>();
4804  llvm::SmallPtrSet<MemberKind*, 1> Results;
4805 
4806  if (!RT)
4807  return Results;
4808  const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
4809  if (!RD || !RD->getDefinition())
4810  return Results;
4811 
4812  LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
4814  R.suppressDiagnostics();
4815 
4816  // We just need to include all members of the right kind turned up by the
4817  // filter, at this point.
4818  if (S.LookupQualifiedName(R, RT->getDecl()))
4819  for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
4820  NamedDecl *decl = (*I)->getUnderlyingDecl();
4821  if (MemberKind *FK = dyn_cast<MemberKind>(decl))
4822  Results.insert(FK);
4823  }
4824  return Results;
4825 }
4826 
4827 /// Check if we could call '.c_str()' on an object.
4828 ///
4829 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
4830 /// allow the call, or if it would be ambiguous).
4831 bool Sema::hasCStrMethod(const Expr *E) {
4832  typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
4833  MethodSet Results =
4834  CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
4835  for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
4836  MI != ME; ++MI)
4837  if ((*MI)->getMinRequiredArguments() == 0)
4838  return true;
4839  return false;
4840 }
4841 
4842 // Check if a (w)string was passed when a (w)char* was needed, and offer a
4843 // better diagnostic if so. AT is assumed to be valid.
4844 // Returns true when a c_str() conversion method is found.
4845 bool CheckPrintfHandler::checkForCStrMembers(
4846  const analyze_printf::ArgType &AT, const Expr *E) {
4847  typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
4848 
4849  MethodSet Results =
4850  CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
4851 
4852  for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
4853  MI != ME; ++MI) {
4854  const CXXMethodDecl *Method = *MI;
4855  if (Method->getMinRequiredArguments() == 0 &&
4856  AT.matchesType(S.Context, Method->getReturnType())) {
4857  // FIXME: Suggest parens if the expression needs them.
4858  SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
4859  S.Diag(E->getLocStart(), diag::note_printf_c_str)
4860  << "c_str()"
4861  << FixItHint::CreateInsertion(EndLoc, ".c_str()");
4862  return true;
4863  }
4864  }
4865 
4866  return false;
4867 }
4868 
4869 bool
4870 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
4871  &FS,
4872  const char *startSpecifier,
4873  unsigned specifierLen) {
4874  using namespace analyze_format_string;
4875  using namespace analyze_printf;
4876  const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
4877 
4878  if (FS.consumesDataArgument()) {
4879  if (atFirstArg) {
4880  atFirstArg = false;
4881  usesPositionalArgs = FS.usesPositionalArg();
4882  }
4883  else if (usesPositionalArgs != FS.usesPositionalArg()) {
4884  HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
4885  startSpecifier, specifierLen);
4886  return false;
4887  }
4888  }
4889 
4890  // First check if the field width, precision, and conversion specifier
4891  // have matching data arguments.
4892  if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
4893  startSpecifier, specifierLen)) {
4894  return false;
4895  }
4896 
4897  if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
4898  startSpecifier, specifierLen)) {
4899  return false;
4900  }
4901 
4902  if (!CS.consumesDataArgument()) {
4903  // FIXME: Technically specifying a precision or field width here
4904  // makes no sense. Worth issuing a warning at some point.
4905  return true;
4906  }
4907 
4908  // Consume the argument.
4909  unsigned argIndex = FS.getArgIndex();
4910  if (argIndex < NumDataArgs) {
4911  // The check to see if the argIndex is valid will come later.
4912  // We set the bit here because we may exit early from this
4913  // function if we encounter some other error.
4914  CoveredArgs.set(argIndex);
4915  }
4916 
4917  // FreeBSD kernel extensions.
4918  if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
4919  CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
4920  // We need at least two arguments.
4921  if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
4922  return false;
4923 
4924  // Claim the second argument.
4925  CoveredArgs.set(argIndex + 1);
4926 
4927  // Type check the first argument (int for %b, pointer for %D)
4928  const Expr *Ex = getDataArg(argIndex);
4929  const analyze_printf::ArgType &AT =
4930  (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
4931  ArgType(S.Context.IntTy) : ArgType::CPointerTy;
4932  if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
4933  EmitFormatDiagnostic(
4934  S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4935  << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
4936  << false << Ex->getSourceRange(),
4937  Ex->getLocStart(), /*IsStringLocation*/false,
4938  getSpecifierRange(startSpecifier, specifierLen));
4939 
4940  // Type check the second argument (char * for both %b and %D)
4941  Ex = getDataArg(argIndex + 1);
4942  const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
4943  if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
4944  EmitFormatDiagnostic(
4945  S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4946  << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
4947  << false << Ex->getSourceRange(),
4948  Ex->getLocStart(), /*IsStringLocation*/false,
4949  getSpecifierRange(startSpecifier, specifierLen));
4950 
4951  return true;
4952  }
4953 
4954  // Check for using an Objective-C specific conversion specifier
4955  // in a non-ObjC literal.
4956  if (!ObjCContext && CS.isObjCArg()) {
4957  return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
4958  specifierLen);
4959  }
4960 
4961  // Check for invalid use of field width
4962  if (!FS.hasValidFieldWidth()) {
4963  HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
4964  startSpecifier, specifierLen);
4965  }
4966 
4967  // Check for invalid use of precision
4968  if (!FS.hasValidPrecision()) {
4969  HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
4970  startSpecifier, specifierLen);
4971  }
4972 
4973  // Check each flag does not conflict with any other component.
4975  HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
4976  if (!FS.hasValidLeadingZeros())
4977  HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
4978  if (!FS.hasValidPlusPrefix())
4979  HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
4980  if (!FS.hasValidSpacePrefix())
4981  HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
4982  if (!FS.hasValidAlternativeForm())
4983  HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
4984  if (!FS.hasValidLeftJustified())
4985  HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
4986 
4987  // Check that flags are not ignored by another flag
4988  if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
4989  HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
4990  startSpecifier, specifierLen);
4991  if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
4992  HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
4993  startSpecifier, specifierLen);
4994 
4995  // Check the length modifier is valid with the given conversion specifier.
4996  if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
4997  HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4998  diag::warn_format_nonsensical_length);
4999  else if (!FS.hasStandardLengthModifier())
5000  HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
5002  HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5003  diag::warn_format_non_standard_conversion_spec);
5004 
5005  if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
5006  HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
5007 
5008  // The remaining checks depend on the data arguments.
5009  if (HasVAListArg)
5010  return true;
5011 
5012  if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
5013  return false;
5014 
5015  const Expr *Arg = getDataArg(argIndex);
5016  if (!Arg)
5017  return true;
5018 
5019  return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
5020 }
5021 
5022 static bool requiresParensToAddCast(const Expr *E) {
5023  // FIXME: We should have a general way to reason about operator
5024  // precedence and whether parens are actually needed here.
5025  // Take care of a few common cases where they aren't.
5026  const Expr *Inside = E->IgnoreImpCasts();
5027  if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
5028  Inside = POE->getSyntacticForm()->IgnoreImpCasts();
5029 
5030  switch (Inside->getStmtClass()) {
5031  case Stmt::ArraySubscriptExprClass:
5032  case Stmt::CallExprClass:
5033  case Stmt::CharacterLiteralClass:
5034  case Stmt::CXXBoolLiteralExprClass:
5035  case Stmt::DeclRefExprClass:
5036  case Stmt::FloatingLiteralClass:
5037  case Stmt::IntegerLiteralClass:
5038  case Stmt::MemberExprClass:
5039  case Stmt::ObjCArrayLiteralClass:
5040  case Stmt::ObjCBoolLiteralExprClass:
5041  case Stmt::ObjCBoxedExprClass:
5042  case Stmt::ObjCDictionaryLiteralClass:
5043  case Stmt::ObjCEncodeExprClass:
5044  case Stmt::ObjCIvarRefExprClass:
5045  case Stmt::ObjCMessageExprClass:
5046  case Stmt::ObjCPropertyRefExprClass:
5047  case Stmt::ObjCStringLiteralClass:
5048  case Stmt::ObjCSubscriptRefExprClass:
5049  case Stmt::ParenExprClass:
5050  case Stmt::StringLiteralClass:
5051  case Stmt::UnaryOperatorClass:
5052  return false;
5053  default:
5054  return true;
5055  }
5056 }
5057 
5058 static std::pair<QualType, StringRef>
5060  QualType IntendedTy,
5061  const Expr *E) {
5062  // Use a 'while' to peel off layers of typedefs.
5063  QualType TyTy = IntendedTy;
5064  while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
5065  StringRef Name = UserTy->getDecl()->getName();
5066  QualType CastTy = llvm::StringSwitch<QualType>(Name)
5067  .Case("NSInteger", Context.LongTy)
5068  .Case("NSUInteger", Context.UnsignedLongTy)
5069  .Case("SInt32", Context.IntTy)
5070  .Case("UInt32", Context.UnsignedIntTy)
5071  .Default(QualType());
5072 
5073  if (!CastTy.isNull())
5074  return std::make_pair(CastTy, Name);
5075 
5076  TyTy = UserTy->desugar();
5077  }
5078 
5079  // Strip parens if necessary.
5080  if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
5081  return shouldNotPrintDirectly(Context,
5082  PE->getSubExpr()->getType(),
5083  PE->getSubExpr());
5084 
5085  // If this is a conditional expression, then its result type is constructed
5086  // via usual arithmetic conversions and thus there might be no necessary
5087  // typedef sugar there. Recurse to operands to check for NSInteger &
5088  // Co. usage condition.
5089  if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
5090  QualType TrueTy, FalseTy;
5091  StringRef TrueName, FalseName;
5092 
5093  std::tie(TrueTy, TrueName) =
5094  shouldNotPrintDirectly(Context,
5095  CO->getTrueExpr()->getType(),
5096  CO->getTrueExpr());
5097  std::tie(FalseTy, FalseName) =
5098  shouldNotPrintDirectly(Context,
5099  CO->getFalseExpr()->getType(),
5100  CO->getFalseExpr());
5101 
5102  if (TrueTy == FalseTy)
5103  return std::make_pair(TrueTy, TrueName);
5104  else if (TrueTy.isNull())
5105  return std::make_pair(FalseTy, FalseName);
5106  else if (FalseTy.isNull())
5107  return std::make_pair(TrueTy, TrueName);
5108  }
5109 
5110  return std::make_pair(QualType(), StringRef());
5111 }
5112 
5113 bool
5114 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5115  const char *StartSpecifier,
5116  unsigned SpecifierLen,
5117  const Expr *E) {
5118  using namespace analyze_format_string;
5119  using namespace analyze_printf;
5120  // Now type check the data expression that matches the
5121  // format specifier.
5122  const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
5123  ObjCContext);
5124  if (!AT.isValid())
5125  return true;
5126 
5127  QualType ExprTy = E->getType();
5128  while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
5129  ExprTy = TET->getUnderlyingExpr()->getType();
5130  }
5131 
5132  analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
5133 
5134  if (match == analyze_printf::ArgType::Match) {
5135  return true;
5136  }
5137 
5138  // Look through argument promotions for our error message's reported type.
5139  // This includes the integral and floating promotions, but excludes array
5140  // and function pointer decay; seeing that an argument intended to be a
5141  // string has type 'char [6]' is probably more confusing than 'char *'.
5142  if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5143  if (ICE->getCastKind() == CK_IntegralCast ||
5144  ICE->getCastKind() == CK_FloatingCast) {
5145  E = ICE->getSubExpr();
5146  ExprTy = E->getType();
5147 
5148  // Check if we didn't match because of an implicit cast from a 'char'
5149  // or 'short' to an 'int'. This is done because printf is a varargs
5150  // function.
5151  if (ICE->getType() == S.Context.IntTy ||
5152  ICE->getType() == S.Context.UnsignedIntTy) {
5153  // All further checking is done on the subexpression.
5154  if (AT.matchesType(S.Context, ExprTy))
5155  return true;
5156  }
5157  }
5158  } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
5159  // Special case for 'a', which has type 'int' in C.
5160  // Note, however, that we do /not/ want to treat multibyte constants like
5161  // 'MooV' as characters! This form is deprecated but still exists.
5162  if (ExprTy == S.Context.IntTy)
5163  if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
5164  ExprTy = S.Context.CharTy;
5165  }
5166 
5167  // Look through enums to their underlying type.
5168  bool IsEnum = false;
5169  if (auto EnumTy = ExprTy->getAs<EnumType>()) {
5170  ExprTy = EnumTy->getDecl()->getIntegerType();
5171  IsEnum = true;
5172  }
5173 
5174  // %C in an Objective-C context prints a unichar, not a wchar_t.
5175  // If the argument is an integer of some kind, believe the %C and suggest
5176  // a cast instead of changing the conversion specifier.
5177  QualType IntendedTy = ExprTy;
5178  if (ObjCContext &&
5179  FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
5180  if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
5181  !ExprTy->isCharType()) {
5182  // 'unichar' is defined as a typedef of unsigned short, but we should
5183  // prefer using the typedef if it is visible.
5184  IntendedTy = S.Context.UnsignedShortTy;
5185 
5186  // While we are here, check if the value is an IntegerLiteral that happens
5187  // to be within the valid range.
5188  if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
5189  const llvm::APInt &V = IL->getValue();
5190  if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
5191  return true;
5192  }
5193 
5194  LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
5196  if (S.LookupName(Result, S.getCurScope())) {
5197  NamedDecl *ND = Result.getFoundDecl();
5198  if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
5199  if (TD->getUnderlyingType() == IntendedTy)
5200  IntendedTy = S.Context.getTypedefType(TD);
5201  }
5202  }
5203  }
5204 
5205  // Special-case some of Darwin's platform-independence types by suggesting
5206  // casts to primitive types that are known to be large enough.
5207  bool ShouldNotPrintDirectly = false; StringRef CastTyName;
5208  if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
5209  QualType CastTy;
5210  std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
5211  if (!CastTy.isNull()) {
5212  IntendedTy = CastTy;
5213  ShouldNotPrintDirectly = true;
5214  }
5215  }
5216 
5217  // We may be able to offer a FixItHint if it is a supported type.
5218  PrintfSpecifier fixedFS = FS;
5219  bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
5220  S.Context, ObjCContext);
5221 
5222  if (success) {
5223  // Get the fix string from the fixed format specifier
5224  SmallString<16> buf;
5225  llvm::raw_svector_ostream os(buf);
5226  fixedFS.toString(os);
5227 
5228  CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
5229 
5230  if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
5231  unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
5233  diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
5234  }
5235  // In this case, the specifier is wrong and should be changed to match
5236  // the argument.
5237  EmitFormatDiagnostic(S.PDiag(diag)
5238  << AT.getRepresentativeTypeName(S.Context)
5239  << IntendedTy << IsEnum << E->getSourceRange(),
5240  E->getLocStart(),
5241  /*IsStringLocation*/ false, SpecRange,
5242  FixItHint::CreateReplacement(SpecRange, os.str()));
5243  } else {
5244  // The canonical type for formatting this value is different from the
5245  // actual type of the expression. (This occurs, for example, with Darwin's
5246  // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
5247  // should be printed as 'long' for 64-bit compatibility.)
5248  // Rather than emitting a normal format/argument mismatch, we want to
5249  // add a cast to the recommended type (and correct the format string
5250  // if necessary).
5251  SmallString<16> CastBuf;
5252  llvm::raw_svector_ostream CastFix(CastBuf);
5253  CastFix << "(";
5254  IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
5255  CastFix << ")";
5256 
5258  if (!AT.matchesType(S.Context, IntendedTy))
5259  Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
5260 
5261  if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
5262  // If there's already a cast present, just replace it.
5263  SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
5264  Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
5265 
5266  } else if (!requiresParensToAddCast(E)) {
5267  // If the expression has high enough precedence,
5268  // just write the C-style cast.
5269  Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
5270  CastFix.str()));
5271  } else {
5272  // Otherwise, add parens around the expression as well as the cast.
5273  CastFix << "(";
5274  Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
5275  CastFix.str()));
5276 
5277  SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
5278  Hints.push_back(FixItHint::CreateInsertion(After, ")"));
5279  }
5280 
5281  if (ShouldNotPrintDirectly) {
5282  // The expression has a type that should not be printed directly.
5283  // We extract the name from the typedef because we don't want to show
5284  // the underlying type in the diagnostic.
5285  StringRef Name;
5286  if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
5287  Name = TypedefTy->getDecl()->getName();
5288  else
5289  Name = CastTyName;
5290  EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
5291  << Name << IntendedTy << IsEnum
5292  << E->getSourceRange(),
5293  E->getLocStart(), /*IsStringLocation=*/false,
5294  SpecRange, Hints);
5295  } else {
5296  // In this case, the expression could be printed using a different
5297  // specifier, but we've decided that the specifier is probably correct
5298  // and we should cast instead. Just use the normal warning message.
5299  EmitFormatDiagnostic(
5300  S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5301  << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
5302  << E->getSourceRange(),
5303  E->getLocStart(), /*IsStringLocation*/false,
5304  SpecRange, Hints);
5305  }
5306  }
5307  } else {
5308  const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
5309  SpecifierLen);
5310  // Since the warning for passing non-POD types to variadic functions
5311  // was deferred until now, we emit a warning for non-POD
5312  // arguments here.
5313  switch (S.isValidVarArgType(ExprTy)) {
5314  case Sema::VAK_Valid:
5315  case Sema::VAK_ValidInCXX11: {
5316  unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
5317  if (match == analyze_printf::ArgType::NoMatchPedantic) {
5318  diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
5319  }
5320 
5321  EmitFormatDiagnostic(
5322  S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
5323  << IsEnum << CSR << E->getSourceRange(),
5324  E->getLocStart(), /*IsStringLocation*/ false, CSR);
5325  break;
5326  }
5327  case Sema::VAK_Undefined:
5329  EmitFormatDiagnostic(
5330  S.PDiag(diag::warn_non_pod_vararg_with_format_string)
5331  << S.getLangOpts().CPlusPlus11
5332  << ExprTy
5333  << CallType
5334  << AT.getRepresentativeTypeName(S.Context)
5335  << CSR
5336  << E->getSourceRange(),
5337  E->getLocStart(), /*IsStringLocation*/false, CSR);
5338  checkForCStrMembers(AT, E);
5339  break;
5340 
5341  case Sema::VAK_Invalid:
5342  if (ExprTy->isObjCObjectType())
5343  EmitFormatDiagnostic(
5344  S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
5345  << S.getLangOpts().CPlusPlus11
5346  << ExprTy
5347  << CallType
5348  << AT.getRepresentativeTypeName(S.Context)
5349  << CSR
5350  << E->getSourceRange(),
5351  E->getLocStart(), /*IsStringLocation*/false, CSR);
5352  else
5353  // FIXME: If this is an initializer list, suggest removing the braces
5354  // or inserting a cast to the target type.
5355  S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
5356  << isa<InitListExpr>(E) << ExprTy << CallType
5357  << AT.getRepresentativeTypeName(S.Context)
5358  << E->getSourceRange();
5359  break;
5360  }
5361 
5362  assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
5363  "format string specifier index out of range");
5364  CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
5365  }
5366 
5367  return true;
5368 }
5369 
5370 //===--- CHECK: Scanf format string checking ------------------------------===//
5371 
5372 namespace {
5373 class CheckScanfHandler : public CheckFormatHandler {
5374 public:
5375  CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
5376  const Expr *origFormatExpr, unsigned firstDataArg,
5377  unsigned numDataArgs, const char *beg, bool hasVAListArg,
5378  ArrayRef<const Expr *> Args,
5379  unsigned formatIdx, bool inFunctionCall,
5380  Sema::VariadicCallType CallType,
5381  llvm::SmallBitVector &CheckedVarArgs,
5382  UncoveredArgHandler &UncoveredArg)
5383  : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
5384  numDataArgs, beg, hasVAListArg,
5385  Args, formatIdx, inFunctionCall, CallType,
5386  CheckedVarArgs, UncoveredArg)
5387  {}
5388 
5389  bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
5390  const char *startSpecifier,
5391  unsigned specifierLen) override;
5392 
5393  bool HandleInvalidScanfConversionSpecifier(
5395  const char *startSpecifier,
5396  unsigned specifierLen) override;
5397 
5398  void HandleIncompleteScanList(const char *start, const char *end) override;
5399 };
5400 } // end anonymous namespace
5401 
5402 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
5403  const char *end) {
5404  EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
5405  getLocationOfByte(end), /*IsStringLocation*/true,
5406  getSpecifierRange(start, end - start));
5407 }
5408 
5409 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
5411  const char *startSpecifier,
5412  unsigned specifierLen) {
5413 
5416 
5417  return HandleInvalidConversionSpecifier(FS.getArgIndex(),
5418  getLocationOfByte(CS.getStart()),
5419  startSpecifier, specifierLen,
5420  CS.getStart(), CS.getLength());
5421 }
5422 
5423 bool CheckScanfHandler::HandleScanfSpecifier(
5425  const char *startSpecifier,
5426  unsigned specifierLen) {
5427  using namespace analyze_scanf;
5428  using namespace analyze_format_string;
5429 
5430  const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
5431 
5432  // Handle case where '%' and '*' don't consume an argument. These shouldn't
5433  // be used to decide if we are using positional arguments consistently.
5434  if (FS.consumesDataArgument()) {
5435  if (atFirstArg) {
5436  atFirstArg = false;
5437  usesPositionalArgs = FS.usesPositionalArg();
5438  }
5439  else if (usesPositionalArgs != FS.usesPositionalArg()) {
5440  HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
5441  startSpecifier, specifierLen);
5442  return false;
5443  }
5444  }
5445 
5446  // Check if the field with is non-zero.
5447  const OptionalAmount &Amt = FS.getFieldWidth();
5448  if (Amt.getHowSpecified() == OptionalAmount::Constant) {
5449  if (Amt.getConstantAmount() == 0) {
5450  const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
5451  Amt.getConstantLength());
5452  EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
5453  getLocationOfByte(Amt.getStart()),
5454  /*IsStringLocation*/true, R,
5455  FixItHint::CreateRemoval(R));
5456  }
5457  }
5458 
5459  if (!FS.consumesDataArgument()) {
5460  // FIXME: Technically specifying a precision or field width here
5461  // makes no sense. Worth issuing a warning at some point.
5462  return true;
5463  }
5464 
5465  // Consume the argument.
5466  unsigned argIndex = FS.getArgIndex();
5467  if (argIndex < NumDataArgs) {
5468  // The check to see if the argIndex is valid will come later.
5469  // We set the bit here because we may exit early from this
5470  // function if we encounter some other error.
5471  CoveredArgs.set(argIndex);
5472  }
5473 
5474  // Check the length modifier is valid with the given conversion specifier.
5475  if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
5476  HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5477  diag::warn_format_nonsensical_length);
5478  else if (!FS.hasStandardLengthModifier())
5479  HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
5481  HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5482  diag::warn_format_non_standard_conversion_spec);
5483 
5484  if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
5485  HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
5486 
5487  // The remaining checks depend on the data arguments.
5488  if (HasVAListArg)
5489  return true;
5490 
5491  if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
5492  return false;
5493 
5494  // Check that the argument type matches the format specifier.
5495  const Expr *Ex = getDataArg(argIndex);
5496  if (!Ex)
5497  return true;
5498 
5499  const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
5500 
5501  if (!AT.isValid()) {
5502  return true;
5503  }
5504 
5506  AT.matchesType(S.Context, Ex->getType());
5508  return true;
5509  }
5510 
5511  ScanfSpecifier fixedFS = FS;
5512  bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
5513  S.getLangOpts(), S.Context);
5514 
5515  unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
5517  diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
5518  }
5519 
5520  if (success) {
5521  // Get the fix string from the fixed format specifier.
5522  SmallString<128> buf;
5523  llvm::raw_svector_ostream os(buf);
5524  fixedFS.toString(os);
5525 
5526  EmitFormatDiagnostic(
5527  S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
5528  << Ex->getType() << false << Ex->getSourceRange(),
5529  Ex->getLocStart(),
5530  /*IsStringLocation*/ false,
5531  getSpecifierRange(startSpecifier, specifierLen),
5533  getSpecifierRange(startSpecifier, specifierLen), os.str()));
5534  } else {
5535  EmitFormatDiagnostic(S.PDiag(diag)
5536  << AT.getRepresentativeTypeName(S.Context)
5537  << Ex->getType() << false << Ex->getSourceRange(),
5538  Ex->getLocStart(),
5539  /*IsStringLocation*/ false,
5540  getSpecifierRange(startSpecifier, specifierLen));
5541  }
5542 
5543  return true;
5544 }
5545 
5546 static void CheckFormatString(Sema &S, const StringLiteral *FExpr,
5547  const Expr *OrigFormatExpr,
5548  ArrayRef<const Expr *> Args,
5549  bool HasVAListArg, unsigned format_idx,
5550  unsigned firstDataArg,
5552  bool inFunctionCall,
5553  Sema::VariadicCallType CallType,
5554  llvm::SmallBitVector &CheckedVarArgs,
5555  UncoveredArgHandler &UncoveredArg) {
5556  // CHECK: is the format string a wide literal?
5557  if (!FExpr->isAscii() && !FExpr->isUTF8()) {
5558  CheckFormatHandler::EmitFormatDiagnostic(
5559  S, inFunctionCall, Args[format_idx],
5560  S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
5561  /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
5562  return;
5563  }
5564 
5565  // Str - The format string. NOTE: this is NOT null-terminated!
5566  StringRef StrRef = FExpr->getString();
5567  const char *Str = StrRef.data();
5568  // Account for cases where the string literal is truncated in a declaration.
5569  const ConstantArrayType *T =
5571  assert(T && "String literal not of constant array type!");
5572  size_t TypeSize = T->getSize().getZExtValue();
5573  size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
5574  const unsigned numDataArgs = Args.size() - firstDataArg;
5575 
5576  // Emit a warning if the string literal is truncated and does not contain an
5577  // embedded null character.
5578  if (TypeSize <= StrRef.size() &&
5579  StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
5580  CheckFormatHandler::EmitFormatDiagnostic(
5581  S, inFunctionCall, Args[format_idx],
5582  S.PDiag(diag::warn_printf_format_string_not_null_terminated),
5583  FExpr->getLocStart(),
5584  /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
5585  return;
5586  }
5587 
5588  // CHECK: empty format string?
5589  if (StrLen == 0 && numDataArgs > 0) {
5590  CheckFormatHandler::EmitFormatDiagnostic(
5591  S, inFunctionCall, Args[format_idx],
5592  S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
5593  /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
5594  return;
5595  }
5596 
5597  if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
5598  Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSTrace) {
5599  CheckPrintfHandler H(S, FExpr, OrigFormatExpr, firstDataArg,
5600  numDataArgs, (Type == Sema::FST_NSString ||
5601  Type == Sema::FST_OSTrace),
5602  Str, HasVAListArg, Args, format_idx,
5603  inFunctionCall, CallType, CheckedVarArgs,
5604  UncoveredArg);
5605 
5606  if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
5607  S.getLangOpts(),
5608  S.Context.getTargetInfo(),
5609  Type == Sema::FST_FreeBSDKPrintf))
5610  H.DoneProcessing();
5611  } else if (Type == Sema::FST_Scanf) {
5612  CheckScanfHandler H(S, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
5613  Str, HasVAListArg, Args, format_idx,
5614  inFunctionCall, CallType, CheckedVarArgs,
5615  UncoveredArg);
5616 
5617  if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
5618  S.getLangOpts(),
5619  S.Context.getTargetInfo()))
5620  H.DoneProcessing();
5621  } // TODO: handle other formats
5622 }
5623 
5625  // Str - The format string. NOTE: this is NOT null-terminated!
5626  StringRef StrRef = FExpr->getString();
5627  const char *Str = StrRef.data();
5628  // Account for cases where the string literal is truncated in a declaration.
5629  const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
5630  assert(T && "String literal not of constant array type!");
5631  size_t TypeSize = T->getSize().getZExtValue();
5632  size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
5633  return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
5634  getLangOpts(),
5635  Context.getTargetInfo());
5636 }
5637 
5638 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
5639 
5640 // Returns the related absolute value function that is larger, of 0 if one
5641 // does not exist.
5642 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
5643  switch (AbsFunction) {
5644  default:
5645  return 0;
5646 
5647  case Builtin::BI__builtin_abs:
5648  return Builtin::BI__builtin_labs;
5649  case Builtin::BI__builtin_labs:
5650  return Builtin::BI__builtin_llabs;
5651  case Builtin::BI__builtin_llabs:
5652  return 0;
5653 
5654  case Builtin::BI__builtin_fabsf:
5655  return Builtin::BI__builtin_fabs;
5656  case Builtin::BI__builtin_fabs:
5657  return Builtin::BI__builtin_fabsl;
5658  case Builtin::BI__builtin_fabsl:
5659  return 0;
5660 
5661  case Builtin::BI__builtin_cabsf:
5662  return Builtin::BI__builtin_cabs;
5663  case Builtin::BI__builtin_cabs:
5664  return Builtin::BI__builtin_cabsl;
5665  case Builtin::BI__builtin_cabsl:
5666  return 0;
5667 
5668  case Builtin::BIabs:
5669  return Builtin::BIlabs;
5670  case Builtin::BIlabs:
5671  return Builtin::BIllabs;
5672  case Builtin::BIllabs:
5673  return 0;
5674 
5675  case Builtin::BIfabsf:
5676  return Builtin::BIfabs;
5677  case Builtin::BIfabs:
5678  return Builtin::BIfabsl;
5679  case Builtin::BIfabsl:
5680  return 0;
5681 
5682  case Builtin::BIcabsf:
5683  return Builtin::BIcabs;
5684  case Builtin::BIcabs:
5685  return Builtin::BIcabsl;
5686  case Builtin::BIcabsl:
5687  return 0;
5688  }
5689 }
5690 
5691 // Returns the argument type of the absolute value function.
5693  unsigned AbsType) {
5694  if (AbsType == 0)
5695  return QualType();
5696 
5698  QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
5699  if (Error != ASTContext::GE_None)
5700  return QualType();
5701 
5702  const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
5703  if (!FT)
5704  return QualType();
5705 
5706  if (FT->getNumParams() != 1)
5707  return QualType();
5708 
5709  return FT->getParamType(0);
5710 }
5711 
5712 // Returns the best absolute value function, or zero, based on type and
5713 // current absolute value function.
5714 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
5715  unsigned AbsFunctionKind) {
5716  unsigned BestKind = 0;
5717  uint64_t ArgSize = Context.getTypeSize(ArgType);
5718  for (unsigned Kind = AbsFunctionKind; Kind != 0;
5720  QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
5721  if (Context.getTypeSize(ParamType) >= ArgSize) {
5722  if (BestKind == 0)
5723  BestKind = Kind;
5724  else if (Context.hasSameType(ParamType, ArgType)) {
5725  BestKind = Kind;
5726  break;
5727  }
5728  }
5729  }
5730  return BestKind;
5731 }
5732 
5737 };
5738 
5740  if (T->isIntegralOrEnumerationType())
5741  return AVK_Integer;
5742  if (T->isRealFloatingType())
5743  return AVK_Floating;
5744  if (T->isAnyComplexType())
5745  return AVK_Complex;
5746 
5747  llvm_unreachable("Type not integer, floating, or complex");
5748 }
5749 
5750 // Changes the absolute value function to a different type. Preserves whether
5751 // the function is a builtin.
5752 static unsigned changeAbsFunction(unsigned AbsKind,
5753  AbsoluteValueKind ValueKind) {
5754  switch (ValueKind) {
5755  case AVK_Integer:
5756  switch (AbsKind) {
5757  default:
5758  return 0;
5759  case Builtin::BI__builtin_fabsf:
5760  case Builtin::BI__builtin_fabs:
5761  case Builtin::BI__builtin_fabsl:
5762  case Builtin::BI__builtin_cabsf:
5763  case Builtin::BI__builtin_cabs:
5764  case Builtin::BI__builtin_cabsl:
5765  return Builtin::BI__builtin_abs;
5766  case Builtin::BIfabsf:
5767  case Builtin::BIfabs:
5768  case Builtin::BIfabsl:
5769  case Builtin::BIcabsf:
5770  case Builtin::BIcabs:
5771  case Builtin::BIcabsl:
5772  return Builtin::BIabs;
5773  }
5774  case AVK_Floating:
5775  switch (AbsKind) {
5776  default:
5777  return 0;
5778  case Builtin::BI__builtin_abs:
5779  case Builtin::BI__builtin_labs:
5780  case Builtin::BI__builtin_llabs:
5781  case Builtin::BI__builtin_cabsf:
5782  case Builtin::BI__builtin_cabs:
5783  case Builtin::BI__builtin_cabsl:
5784  return Builtin::BI__builtin_fabsf;
5785  case Builtin::BIabs:
5786  case Builtin::BIlabs:
5787  case Builtin::BIllabs:
5788  case Builtin::BIcabsf:
5789  case Builtin::BIcabs:
5790  case Builtin::BIcabsl:
5791  return Builtin::BIfabsf;
5792  }
5793  case AVK_Complex:
5794  switch (AbsKind) {
5795  default:
5796  return 0;
5797  case Builtin::BI__builtin_abs:
5798  case Builtin::BI__builtin_labs:
5799  case Builtin::BI__builtin_llabs:
5800  case Builtin::BI__builtin_fabsf:
5801  case Builtin::BI__builtin_fabs:
5802  case Builtin::BI__builtin_fabsl:
5803  return Builtin::BI__builtin_cabsf;
5804  case Builtin::BIabs:
5805  case Builtin::BIlabs:
5806  case Builtin::BIllabs:
5807  case Builtin::BIfabsf:
5808  case Builtin::BIfabs:
5809  case Builtin::BIfabsl:
5810  return Builtin::BIcabsf;
5811  }
5812  }
5813  llvm_unreachable("Unable to convert function");
5814 }
5815 
5816 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
5817  const IdentifierInfo *FnInfo = FDecl->getIdentifier();
5818  if (!FnInfo)
5819  return 0;
5820 
5821  switch (FDecl->getBuiltinID()) {
5822  default:
5823  return 0;
5824  case Builtin::BI__builtin_abs:
5825  case Builtin::BI__builtin_fabs:
5826  case Builtin::BI__builtin_fabsf:
5827  case Builtin::BI__builtin_fabsl:
5828  case Builtin::BI__builtin_labs:
5829  case Builtin::BI__builtin_llabs:
5830  case Builtin::BI__builtin_cabs:
5831  case Builtin::BI__builtin_cabsf:
5832  case Builtin::BI__builtin_cabsl:
5833  case Builtin::BIabs:
5834  case Builtin::BIlabs:
5835  case Builtin::BIllabs:
5836  case Builtin::BIfabs:
5837  case Builtin::BIfabsf:
5838  case Builtin::BIfabsl:
5839  case Builtin::BIcabs:
5840  case Builtin::BIcabsf:
5841  case Builtin::BIcabsl:
5842  return FDecl->getBuiltinID();
5843  }
5844  llvm_unreachable("Unknown Builtin type");
5845 }
5846 
5847 // If the replacement is valid, emit a note with replacement function.
5848 // Additionally, suggest including the proper header if not already included.
5849 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
5850  unsigned AbsKind, QualType ArgType) {
5851  bool EmitHeaderHint = true;
5852  const char *HeaderName = nullptr;
5853  const char *FunctionName = nullptr;
5854  if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
5855  FunctionName = "std::abs";
5856  if (ArgType->isIntegralOrEnumerationType()) {
5857  HeaderName = "cstdlib";
5858  } else if (ArgType->isRealFloatingType()) {
5859  HeaderName = "cmath";
5860  } else {
5861  llvm_unreachable("Invalid Type");
5862  }
5863 
5864  // Lookup all std::abs
5865  if (NamespaceDecl *Std = S.getStdNamespace()) {
5866  LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
5867  R.suppressDiagnostics();
5868  S.LookupQualifiedName(R, Std);
5869 
5870  for (const auto *I : R) {
5871  const FunctionDecl *FDecl = nullptr;
5872  if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
5873  FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
5874  } else {
5875  FDecl = dyn_cast<FunctionDecl>(I);
5876  }
5877  if (!FDecl)
5878  continue;
5879 
5880  // Found std::abs(), check that they are the right ones.
5881  if (FDecl->getNumParams() != 1)
5882  continue;
5883 
5884  // Check that the parameter type can handle the argument.
5885  QualType ParamType = FDecl->getParamDecl(0)->getType();
5886  if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
5887  S.Context.getTypeSize(ArgType) <=
5888  S.Context.getTypeSize(ParamType)) {
5889  // Found a function, don't need the header hint.
5890  EmitHeaderHint = false;
5891  break;
5892  }
5893  }
5894  }
5895  } else {
5896  FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
5897  HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
5898 
5899  if (HeaderName) {
5900  DeclarationName DN(&S.Context.Idents.get(FunctionName));
5901  LookupResult R(S, DN, Loc, Sema::LookupAnyName);
5902  R.suppressDiagnostics();
5903  S.LookupName(R, S.getCurScope());
5904 
5905  if (R.isSingleResult()) {
5906  FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
5907  if (FD && FD->getBuiltinID() == AbsKind) {
5908  EmitHeaderHint = false;
5909  } else {
5910  return;
5911  }
5912  } else if (!R.empty()) {
5913  return;
5914  }
5915  }
5916  }
5917 
5918  S.Diag(Loc, diag::note_replace_abs_function)
5919  << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
5920 
5921  if (!HeaderName)
5922  return;
5923 
5924  if (!EmitHeaderHint)
5925  return;
5926 
5927  S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
5928  << FunctionName;
5929 }
5930 
5931 static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
5932  if (!FDecl)
5933  return false;
5934 
5935  if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
5936  return false;
5937 
5938  const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
5939 
5940  while (ND && ND->isInlineNamespace()) {
5941  ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
5942  }
5943 
5944  if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
5945  return false;
5946 
5947  if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
5948  return false;
5949 
5950  return true;
5951 }
5952 
5953 // Warn when using the wrong abs() function.
5954 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
5955  const FunctionDecl *FDecl,
5956  IdentifierInfo *FnInfo) {
5957  if (Call->getNumArgs() != 1)
5958  return;
5959 
5960  unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
5961  bool IsStdAbs = IsFunctionStdAbs(FDecl);
5962  if (AbsKind == 0 && !IsStdAbs)
5963  return;
5964 
5965  QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
5966  QualType ParamType = Call->getArg(0)->getType();
5967 
5968  // Unsigned types cannot be negative. Suggest removing the absolute value
5969  // function call.
5970  if (ArgType->isUnsignedIntegerType()) {
5971  const char *FunctionName =
5972  IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
5973  Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
5974  Diag(Call->getExprLoc(), diag::note_remove_abs)
5975  << FunctionName
5976  << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
5977  return;
5978  }
5979 
5980  // Taking the absolute value of a pointer is very suspicious, they probably
5981  // wanted to index into an array, dereference a pointer, call a function, etc.
5982  if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
5983  unsigned DiagType = 0;
5984  if (ArgType->isFunctionType())
5985  DiagType = 1;
5986  else if (ArgType->isArrayType())
5987  DiagType = 2;
5988 
5989  Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
5990  return;
5991  }
5992 
5993  // std::abs has overloads which prevent most of the absolute value problems
5994  // from occurring.
5995  if (IsStdAbs)
5996  return;
5997 
5998  AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
5999  AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
6000 
6001  // The argument and parameter are the same kind. Check if they are the right
6002  // size.
6003  if (ArgValueKind == ParamValueKind) {
6004  if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
6005  return;
6006 
6007  unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
6008  Diag(Call->getExprLoc(), diag::warn_abs_too_small)
6009  << FDecl << ArgType << ParamType;
6010 
6011  if (NewAbsKind == 0)
6012  return;
6013 
6014  emitReplacement(*this, Call->getExprLoc(),
6015  Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
6016  return;
6017  }
6018 
6019  // ArgValueKind != ParamValueKind
6020  // The wrong type of absolute value function was used. Attempt to find the
6021  // proper one.
6022  unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
6023  NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
6024  if (NewAbsKind == 0)
6025  return;
6026 
6027  Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
6028  << FDecl << ParamValueKind << ArgValueKind;
6029 
6030  emitReplacement(*this, Call->getExprLoc(),
6031  Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
6032 }
6033 
6034 //===--- CHECK: Standard memory functions ---------------------------------===//
6035 
6036 /// \brief Takes the expression passed to the size_t parameter of functions
6037 /// such as memcmp, strncat, etc and warns if it's a comparison.
6038 ///
6039 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
6040 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
6041  IdentifierInfo *FnName,
6042  SourceLocation FnLoc,
6043  SourceLocation RParenLoc) {
6044  const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
6045  if (!Size)
6046  return false;
6047 
6048  // if E is binop and op is >, <, >=, <=, ==, &&, ||:
6049  if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
6050  return false;
6051 
6052  SourceRange SizeRange = Size->getSourceRange();
6053  S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
6054  << SizeRange << FnName;
6055  S.Diag(FnLoc, diag::note_memsize_comparison_paren)
6056  << FnName << FixItHint::CreateInsertion(
6057  S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
6058  << FixItHint::CreateRemoval(RParenLoc);
6059  S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
6060  << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
6062  ")");
6063 
6064  return true;
6065 }
6066 
6067 /// \brief Determine whether the given type is or contains a dynamic class type
6068 /// (e.g., whether it has a vtable).
6070  bool &IsContained) {
6071  // Look through array types while ignoring qualifiers.
6072  const Type *Ty = T->getBaseElementTypeUnsafe();
6073  IsContained = false;
6074 
6075  const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
6076  RD = RD ? RD->getDefinition() : nullptr;
6077  if (!RD || RD->isInvalidDecl())
6078  return nullptr;
6079 
6080  if (RD->isDynamicClass())
6081  return RD;
6082 
6083  // Check all the fields. If any bases were dynamic, the class is dynamic.
6084  // It's impossible for a class to transitively contain itself by value, so
6085  // infinite recursion is impossible.
6086  for (auto *FD : RD->fields()) {
6087  bool SubContained;
6088  if (const CXXRecordDecl *ContainedRD =
6089  getContainedDynamicClass(FD->getType(), SubContained)) {
6090  IsContained = true;
6091  return ContainedRD;
6092  }
6093  }
6094 
6095  return nullptr;
6096 }
6097 
6098 /// \brief If E is a sizeof expression, returns its argument expression,
6099 /// otherwise returns NULL.
6100 static const Expr *getSizeOfExprArg(const Expr *E) {
6101  if (const UnaryExprOrTypeTraitExpr *SizeOf =
6102  dyn_cast<UnaryExprOrTypeTraitExpr>(E))
6103  if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
6104  return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
6105 
6106  return nullptr;
6107 }
6108 
6109 /// \brief If E is a sizeof expression, returns its argument type.
6110 static QualType getSizeOfArgType(const Expr *E) {
6111  if (const UnaryExprOrTypeTraitExpr *SizeOf =
6112  dyn_cast<UnaryExprOrTypeTraitExpr>(E))
6113  if (SizeOf->getKind() == clang::UETT_SizeOf)
6114  return SizeOf->getTypeOfArgument();
6115 
6116  return QualType();
6117 }
6118 
6119 /// \brief Check for dangerous or invalid arguments to memset().
6120 ///
6121 /// This issues warnings on known problematic, dangerous or unspecified
6122 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
6123 /// function calls.
6124 ///
6125 /// \param Call The call expression to diagnose.
6126 void Sema::CheckMemaccessArguments(const CallExpr *Call,
6127  unsigned BId,
6128  IdentifierInfo *FnName) {
6129  assert(BId != 0);
6130 
6131  // It is possible to have a non-standard definition of memset. Validate
6132  // we have enough arguments, and if not, abort further checking.
6133  unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
6134  if (Call->getNumArgs() < ExpectedNumArgs)
6135  return;
6136 
6137  unsigned LastArg = (BId == Builtin::BImemset ||
6138  BId == Builtin::BIstrndup ? 1 : 2);
6139  unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
6140  const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
6141 
6142  if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
6143  Call->getLocStart(), Call->getRParenLoc()))
6144  return;
6145 
6146  // We have special checking when the length is a sizeof expression.
6147  QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
6148  const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
6149  llvm::FoldingSetNodeID SizeOfArgID;
6150 
6151  for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
6152  const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
6153  SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
6154 
6155  QualType DestTy = Dest->getType();
6156  QualType PointeeTy;
6157  if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
6158  PointeeTy = DestPtrTy->getPointeeType();
6159 
6160  // Never warn about void type pointers. This can be used to suppress
6161  // false positives.
6162  if (PointeeTy->isVoidType())
6163  continue;
6164 
6165  // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
6166  // actually comparing the expressions for equality. Because computing the
6167  // expression IDs can be expensive, we only do this if the diagnostic is
6168  // enabled.
6169  if (SizeOfArg &&
6170  !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
6171  SizeOfArg->getExprLoc())) {
6172  // We only compute IDs for expressions if the warning is enabled, and
6173  // cache the sizeof arg's ID.
6174  if (SizeOfArgID == llvm::FoldingSetNodeID())
6175  SizeOfArg->Profile(SizeOfArgID, Context, true);
6176  llvm::FoldingSetNodeID DestID;
6177  Dest->Profile(DestID, Context, true);
6178  if (DestID == SizeOfArgID) {
6179  // TODO: For strncpy() and friends, this could suggest sizeof(dst)
6180  // over sizeof(src) as well.
6181  unsigned ActionIdx = 0; // Default is to suggest dereferencing.
6182  StringRef ReadableName = FnName->getName();
6183 
6184  if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
6185  if (UnaryOp->getOpcode() == UO_AddrOf)
6186  ActionIdx = 1; // If its an address-of operator, just remove it.
6187  if (!PointeeTy->isIncompleteType() &&
6188  (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
6189  ActionIdx = 2; // If the pointee's size is sizeof(char),
6190  // suggest an explicit length.
6191 
6192  // If the function is defined as a builtin macro, do not show macro
6193  // expansion.
6194  SourceLocation SL = SizeOfArg->getExprLoc();
6195  SourceRange DSR = Dest->getSourceRange();
6196  SourceRange SSR = SizeOfArg->getSourceRange();
6197  SourceManager &SM = getSourceManager();
6198 
6199  if (SM.isMacroArgExpansion(SL)) {
6200  ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
6201  SL = SM.getSpellingLoc(SL);
6202  DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
6203  SM.getSpellingLoc(DSR.getEnd()));
6204  SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
6205  SM.getSpellingLoc(SSR.getEnd()));
6206  }
6207 
6208  DiagRuntimeBehavior(SL, SizeOfArg,
6209  PDiag(diag::warn_sizeof_pointer_expr_memaccess)
6210  << ReadableName
6211  << PointeeTy
6212  << DestTy
6213  << DSR
6214  << SSR);
6215  DiagRuntimeBehavior(SL, SizeOfArg,
6216  PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
6217  << ActionIdx
6218  << SSR);
6219 
6220  break;
6221  }
6222  }
6223 
6224  // Also check for cases where the sizeof argument is the exact same
6225  // type as the memory argument, and where it points to a user-defined
6226  // record type.
6227  if (SizeOfArgTy != QualType()) {
6228  if (PointeeTy->isRecordType() &&
6229  Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
6230  DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
6231  PDiag(diag::warn_sizeof_pointer_type_memaccess)
6232  << FnName << SizeOfArgTy << ArgIdx
6233  << PointeeTy << Dest->getSourceRange()
6234  << LenExpr->getSourceRange());
6235  break;
6236  }
6237  }
6238  } else if (DestTy->isArrayType()) {
6239  PointeeTy = DestTy;
6240  }
6241 
6242  if (PointeeTy == QualType())
6243  continue;
6244 
6245  // Always complain about dynamic classes.
6246  bool IsContained;
6247  if (const CXXRecordDecl *ContainedRD =
6248  getContainedDynamicClass(PointeeTy, IsContained)) {
6249 
6250  unsigned OperationType = 0;
6251  // "overwritten" if we're warning about the destination for any call
6252  // but memcmp; otherwise a verb appropriate to the call.
6253  if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
6254  if (BId == Builtin::BImemcpy)
6255  OperationType = 1;
6256  else if(BId == Builtin::BImemmove)
6257  OperationType = 2;
6258  else if (BId == Builtin::BImemcmp)
6259  OperationType = 3;
6260  }
6261 
6262  DiagRuntimeBehavior(
6263  Dest->getExprLoc(), Dest,
6264  PDiag(diag::warn_dyn_class_memaccess)
6265  << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
6266  << FnName << IsContained << ContainedRD << OperationType
6267  << Call->getCallee()->getSourceRange());
6268  } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
6269  BId != Builtin::BImemset)
6270  DiagRuntimeBehavior(
6271  Dest->getExprLoc(), Dest,
6272  PDiag(diag::warn_arc_object_memaccess)
6273  << ArgIdx << FnName << PointeeTy
6274  << Call->getCallee()->getSourceRange());
6275  else
6276  continue;
6277 
6278  DiagRuntimeBehavior(
6279  Dest->getExprLoc(), Dest,
6280  PDiag(diag::note_bad_memaccess_silence)
6281  << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
6282  break;
6283  }
6284 }
6285 
6286 // A little helper routine: ignore addition and subtraction of integer literals.
6287 // This intentionally does not ignore all integer constant expressions because
6288 // we don't want to remove sizeof().
6289 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
6290  Ex = Ex->IgnoreParenCasts();
6291 
6292  for (;;) {
6293  const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
6294  if (!BO || !BO->isAdditiveOp())
6295  break;
6296 
6297  const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
6298  const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
6299 
6300  if (isa<IntegerLiteral>(RHS))
6301  Ex = LHS;
6302  else if (isa<IntegerLiteral>(LHS))
6303  Ex = RHS;
6304  else
6305  break;
6306  }
6307 
6308  return Ex;
6309 }
6310 
6312  ASTContext &Context) {
6313  // Only handle constant-sized or VLAs, but not flexible members.
6314  if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
6315  // Only issue the FIXIT for arrays of size > 1.
6316  if (CAT->getSize().getSExtValue() <= 1)
6317  return false;
6318  } else if (!Ty->isVariableArrayType()) {
6319  return false;
6320  }
6321  return true;
6322 }
6323 
6324 // Warn if the user has made the 'size' argument to strlcpy or strlcat
6325 // be the size of the source, instead of the destination.
6326 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
6327  IdentifierInfo *FnName) {
6328 
6329  // Don't crash if the user has the wrong number of arguments
6330  unsigned NumArgs = Call->getNumArgs();
6331  if ((NumArgs != 3) && (NumArgs != 4))
6332  return;
6333 
6334  const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
6335  const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
6336  const Expr *CompareWithSrc = nullptr;
6337 
6338  if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
6339  Call->getLocStart(), Call->getRParenLoc()))
6340  return;
6341 
6342  // Look for 'strlcpy(dst, x, sizeof(x))'
6343  if (const Expr *Ex = getSizeOfExprArg(SizeArg))
6344  CompareWithSrc = Ex;
6345  else {
6346  // Look for 'strlcpy(dst, x, strlen(x))'
6347  if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
6348  if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
6349  SizeCall->getNumArgs() == 1)
6350  CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
6351  }
6352  }
6353 
6354  if (!CompareWithSrc)
6355  return;
6356 
6357  // Determine if the argument to sizeof/strlen is equal to the source
6358  // argument. In principle there's all kinds of things you could do
6359  // here, for instance creating an == expression and evaluating it with
6360  // EvaluateAsBooleanCondition, but this uses a more direct technique:
6361  const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
6362  if (!SrcArgDRE)
6363  return;
6364 
6365  const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
6366  if (!CompareWithSrcDRE ||
6367  SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
6368  return;
6369 
6370  const Expr *OriginalSizeArg = Call->getArg(2);
6371  Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
6372  << OriginalSizeArg->getSourceRange() << FnName;
6373 
6374  // Output a FIXIT hint if the destination is an array (rather than a
6375  // pointer to an array). This could be enhanced to handle some
6376  // pointers if we know the actual size, like if DstArg is 'array+2'
6377  // we could say 'sizeof(array)-2'.
6378  const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
6380  return;
6381 
6382  SmallString<128> sizeString;
6383  llvm::raw_svector_ostream OS(sizeString);
6384  OS << "sizeof(";
6385  DstArg->printPretty(OS, nullptr, getPrintingPolicy());
6386  OS << ")";
6387 
6388  Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
6389  << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
6390  OS.str());
6391 }
6392 
6393 /// Check if two expressions refer to the same declaration.
6394 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
6395  if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
6396  if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
6397  return D1->getDecl() == D2->getDecl();
6398  return false;
6399 }
6400 
6401 static const Expr *getStrlenExprArg(const Expr *E) {
6402  if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
6403  const FunctionDecl *FD = CE->getDirectCallee();
6404  if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
6405  return nullptr;
6406  return CE->getArg(0)->IgnoreParenCasts();
6407  }
6408  return nullptr;
6409 }
6410 
6411 // Warn on anti-patterns as the 'size' argument to strncat.
6412 // The correct size argument should look like following:
6413 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
6414 void Sema::CheckStrncatArguments(const CallExpr *CE,
6415  IdentifierInfo *FnName) {
6416  // Don't crash if the user has the wrong number of arguments.
6417  if (CE->getNumArgs() < 3)
6418  return;
6419  const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
6420  const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
6421  const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
6422 
6423  if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
6424  CE->getRParenLoc()))
6425  return;
6426 
6427  // Identify common expressions, which are wrongly used as the size argument
6428  // to strncat and may lead to buffer overflows.
6429  unsigned PatternType = 0;
6430  if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
6431  // - sizeof(dst)
6432  if (referToTheSameDecl(SizeOfArg, DstArg))
6433  PatternType = 1;
6434  // - sizeof(src)
6435  else if (referToTheSameDecl(SizeOfArg, SrcArg))
6436  PatternType = 2;
6437  } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
6438  if (BE->getOpcode() == BO_Sub) {
6439  const Expr *L = BE->getLHS()->IgnoreParenCasts();
6440  const Expr *R = BE->getRHS()->IgnoreParenCasts();
6441  // - sizeof(dst) - strlen(dst)
6442  if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
6444  PatternType = 1;
6445  // - sizeof(src) - (anything)
6446  else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
6447  PatternType = 2;
6448  }
6449  }
6450 
6451  if (PatternType == 0)
6452  return;
6453 
6454  // Generate the diagnostic.
6455  SourceLocation SL = LenArg->getLocStart();
6456  SourceRange SR = LenArg->getSourceRange();
6457  SourceManager &SM = getSourceManager();
6458 
6459  // If the function is defined as a builtin macro, do not show macro expansion.
6460  if (SM.isMacroArgExpansion(SL)) {
6461  SL = SM.getSpellingLoc(SL);
6462  SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
6463  SM.getSpellingLoc(SR.getEnd()));
6464  }
6465 
6466  // Check if the destination is an array (rather than a pointer to an array).
6467  QualType DstTy = DstArg->getType();
6468  bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
6469  Context);
6470  if (!isKnownSizeArray) {
6471  if (PatternType == 1)
6472  Diag(SL, diag::warn_strncat_wrong_size) << SR;
6473  else
6474  Diag(SL, diag::warn_strncat_src_size) << SR;
6475  return;
6476  }
6477 
6478  if (PatternType == 1)
6479  Diag(SL, diag::warn_strncat_large_size) << SR;
6480  else
6481  Diag(SL, diag::warn_strncat_src_size) << SR;
6482 
6483  SmallString<128> sizeString;
6484  llvm::raw_svector_ostream OS(sizeString);
6485  OS << "sizeof(";
6486  DstArg->printPretty(OS, nullptr, getPrintingPolicy());
6487  OS << ") - ";
6488  OS << "strlen(";
6489  DstArg->printPretty(OS, nullptr, getPrintingPolicy());
6490  OS << ") - 1";
6491 
6492  Diag(SL, diag::note_strncat_wrong_size)
6493  << FixItHint::CreateReplacement(SR, OS.str());
6494 }
6495 
6496 //===--- CHECK: Return Address of Stack Variable --------------------------===//
6497 
6498 static const Expr *EvalVal(const Expr *E,
6499  SmallVectorImpl<const DeclRefExpr *> &refVars,
6500  const Decl *ParentDecl);
6501 static const Expr *EvalAddr(const Expr *E,
6502  SmallVectorImpl<const DeclRefExpr *> &refVars,
6503  const Decl *ParentDecl);
6504 
6505 /// CheckReturnStackAddr - Check if a return statement returns the address
6506 /// of a stack variable.
6507 static void
6508 CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
6509  SourceLocation ReturnLoc) {
6510 
6511  const Expr *stackE = nullptr;
6513 
6514  // Perform checking for returned stack addresses, local blocks,
6515  // label addresses or references to temporaries.
6516  if (lhsType->isPointerType() ||
6517  (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
6518  stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
6519  } else if (lhsType->isReferenceType()) {
6520  stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
6521  }
6522 
6523  if (!stackE)
6524  return; // Nothing suspicious was found.
6525 
6526  // Parameters are initalized in the calling scope, so taking the address
6527  // of a parameter reference doesn't need a warning.
6528  for (auto *DRE : refVars)
6529  if (isa<ParmVarDecl>(DRE->getDecl()))
6530  return;
6531 
6532  SourceLocation diagLoc;
6533  SourceRange diagRange;
6534  if (refVars.empty()) {
6535  diagLoc = stackE->getLocStart();
6536  diagRange = stackE->getSourceRange();
6537  } else {
6538  // We followed through a reference variable. 'stackE' contains the
6539  // problematic expression but we will warn at the return statement pointing
6540  // at the reference variable. We will later display the "trail" of
6541  // reference variables using notes.
6542  diagLoc = refVars[0]->getLocStart();
6543  diagRange = refVars[0]->getSourceRange();
6544  }
6545 
6546  if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
6547  // address of local var
6548  S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
6549  << DR->getDecl()->getDeclName() << diagRange;
6550  } else if (isa<BlockExpr>(stackE)) { // local block.
6551  S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
6552  } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
6553  S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
6554  } else { // local temporary.
6555  // If there is an LValue->RValue conversion, then the value of the
6556  // reference type is used, not the reference.
6557  if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
6558  if (ICE->getCastKind() == CK_LValueToRValue) {
6559  return;
6560  }
6561  }
6562  S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
6563  << lhsType->isReferenceType() << diagRange;
6564  }
6565 
6566  // Display the "trail" of reference variables that we followed until we
6567  // found the problematic expression using notes.
6568  for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
6569  const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
6570  // If this var binds to another reference var, show the range of the next
6571  // var, otherwise the var binds to the problematic expression, in which case
6572  // show the range of the expression.
6573  SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
6574  : stackE->getSourceRange();
6575  S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
6576  << VD->getDeclName() << range;
6577  }
6578 }
6579 
6580 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
6581 /// check if the expression in a return statement evaluates to an address
6582 /// to a location on the stack, a local block, an address of a label, or a
6583 /// reference to local temporary. The recursion is used to traverse the
6584 /// AST of the return expression, with recursion backtracking when we
6585 /// encounter a subexpression that (1) clearly does not lead to one of the
6586 /// above problematic expressions (2) is something we cannot determine leads to
6587 /// a problematic expression based on such local checking.
6588 ///
6589 /// Both EvalAddr and EvalVal follow through reference variables to evaluate
6590 /// the expression that they point to. Such variables are added to the
6591 /// 'refVars' vector so that we know what the reference variable "trail" was.
6592 ///
6593 /// EvalAddr processes expressions that are pointers that are used as
6594 /// references (and not L-values). EvalVal handles all other values.
6595 /// At the base case of the recursion is a check for the above problematic
6596 /// expressions.
6597 ///
6598 /// This implementation handles:
6599 ///
6600 /// * pointer-to-pointer casts
6601 /// * implicit conversions from array references to pointers
6602 /// * taking the address of fields
6603 /// * arbitrary interplay between "&" and "*" operators
6604 /// * pointer arithmetic from an address of a stack variable
6605 /// * taking the address of an array element where the array is on the stack
6606 static const Expr *EvalAddr(const Expr *E,
6607  SmallVectorImpl<const DeclRefExpr *> &refVars,
6608  const Decl *ParentDecl) {
6609  if (E->isTypeDependent())
6610  return nullptr;
6611 
6612  // We should only be called for evaluating pointer expressions.
6613  assert((E->getType()->isAnyPointerType() ||
6614  E->getType()->isBlockPointerType() ||
6615  E->getType()->isObjCQualifiedIdType()) &&
6616  "EvalAddr only works on pointers");
6617 
6618  E = E->IgnoreParens();
6619 
6620  // Our "symbolic interpreter" is just a dispatch off the currently
6621  // viewed AST node. We then recursively traverse the AST by calling
6622  // EvalAddr and EvalVal appropriately.
6623  switch (E->getStmtClass()) {
6624  case Stmt::DeclRefExprClass: {
6625  const DeclRefExpr *DR = cast<DeclRefExpr>(E);
6626 
6627  // If we leave the immediate function, the lifetime isn't about to end.
6629  return nullptr;
6630 
6631  if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
6632  // If this is a reference variable, follow through to the expression that
6633  // it points to.
6634  if (V->hasLocalStorage() &&
6635  V->getType()->isReferenceType() && V->hasInit()) {
6636  // Add the reference variable to the "trail".
6637  refVars.push_back(DR);
6638  return EvalAddr(V->getInit(), refVars, ParentDecl);
6639  }
6640 
6641  return nullptr;
6642  }
6643 
6644  case Stmt::UnaryOperatorClass: {
6645  // The only unary operator that make sense to handle here
6646  // is AddrOf. All others don't make sense as pointers.
6647  const UnaryOperator *U = cast<UnaryOperator>(E);
6648 
6649  if (U->getOpcode() == UO_AddrOf)
6650  return EvalVal(U->getSubExpr(), refVars, ParentDecl);
6651  return nullptr;
6652  }
6653 
6654  case Stmt::BinaryOperatorClass: {
6655  // Handle pointer arithmetic. All other binary operators are not valid
6656  // in this context.
6657  const BinaryOperator *B = cast<BinaryOperator>(E);
6658  BinaryOperatorKind op = B->getOpcode();
6659 
6660  if (op != BO_Add && op != BO_Sub)
6661  return nullptr;
6662 
6663  const Expr *Base = B->getLHS();
6664 
6665  // Determine which argument is the real pointer base. It could be
6666  // the RHS argument instead of the LHS.
6667  if (!Base->getType()->isPointerType())
6668  Base = B->getRHS();
6669 
6670  assert(Base->getType()->isPointerType());
6671  return EvalAddr(Base, refVars, ParentDecl);
6672  }
6673 
6674  // For conditional operators we need to see if either the LHS or RHS are
6675  // valid DeclRefExpr*s. If one of them is valid, we return it.
6676  case Stmt::ConditionalOperatorClass: {
6677  const ConditionalOperator *C = cast<ConditionalOperator>(E);
6678 
6679  // Handle the GNU extension for missing LHS.
6680  // FIXME: That isn't a ConditionalOperator, so doesn't get here.
6681  if (const Expr *LHSExpr = C->getLHS()) {
6682  // In C++, we can have a throw-expression, which has 'void' type.
6683  if (!LHSExpr->getType()->isVoidType())
6684  if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
6685  return LHS;
6686  }
6687 
6688  // In C++, we can have a throw-expression, which has 'void' type.
6689  if (C->getRHS()->getType()->isVoidType())
6690  return nullptr;
6691 
6692  return EvalAddr(C->getRHS(), refVars, ParentDecl);
6693  }
6694 
6695  case Stmt::BlockExprClass:
6696  if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
6697  return E; // local block.
6698  return nullptr;
6699 
6700  case Stmt::AddrLabelExprClass:
6701  return E; // address of label.
6702 
6703  case Stmt::ExprWithCleanupsClass:
6704  return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
6705  ParentDecl);
6706 
6707  // For casts, we need to handle conversions from arrays to
6708  // pointer values, and pointer-to-pointer conversions.
6709  case Stmt::ImplicitCastExprClass:
6710  case Stmt::CStyleCastExprClass:
6711  case Stmt::CXXFunctionalCastExprClass:
6712  case Stmt::ObjCBridgedCastExprClass:
6713  case Stmt::CXXStaticCastExprClass:
6714  case Stmt::CXXDynamicCastExprClass:
6715  case Stmt::CXXConstCastExprClass:
6716  case Stmt::CXXReinterpretCastExprClass: {
6717  const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
6718  switch (cast<CastExpr>(E)->getCastKind()) {
6719  case CK_LValueToRValue:
6720  case CK_NoOp:
6721  case CK_BaseToDerived:
6722  case CK_DerivedToBase:
6723  case CK_UncheckedDerivedToBase:
6724  case CK_Dynamic:
6725  case CK_CPointerToObjCPointerCast:
6726  case CK_BlockPointerToObjCPointerCast:
6727  case CK_AnyPointerToBlockPointerCast:
6728  return EvalAddr(SubExpr, refVars, ParentDecl);
6729 
6730  case CK_ArrayToPointerDecay:
6731  return EvalVal(SubExpr, refVars, ParentDecl);
6732 
6733  case CK_BitCast:
6734  if (SubExpr->getType()->isAnyPointerType() ||
6735  SubExpr->getType()->isBlockPointerType() ||
6736  SubExpr->getType()->isObjCQualifiedIdType())
6737  return EvalAddr(SubExpr, refVars, ParentDecl);
6738  else
6739  return nullptr;
6740 
6741  default:
6742  return nullptr;
6743  }
6744  }
6745 
6746  case Stmt::MaterializeTemporaryExprClass:
6747  if (const Expr *Result =
6748  EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
6749  refVars, ParentDecl))
6750  return Result;
6751  return E;
6752 
6753  // Everything else: we simply don't reason about them.
6754  default:
6755  return nullptr;
6756  }
6757 }
6758 
6759 /// EvalVal - This function is complements EvalAddr in the mutual recursion.
6760 /// See the comments for EvalAddr for more details.
6761 static const Expr *EvalVal(const Expr *E,
6762  SmallVectorImpl<const DeclRefExpr *> &refVars,
6763  const Decl *ParentDecl) {
6764  do {
6765  // We should only be called for evaluating non-pointer expressions, or
6766  // expressions with a pointer type that are not used as references but
6767  // instead
6768  // are l-values (e.g., DeclRefExpr with a pointer type).
6769 
6770  // Our "symbolic interpreter" is just a dispatch off the currently
6771  // viewed AST node. We then recursively traverse the AST by calling
6772  // EvalAddr and EvalVal appropriately.
6773 
6774  E = E->IgnoreParens();
6775  switch (E->getStmtClass()) {
6776  case Stmt::ImplicitCastExprClass: {
6777  const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
6778  if (IE->getValueKind() == VK_LValue) {
6779  E = IE->getSubExpr();
6780  continue;
6781  }
6782  return nullptr;
6783  }
6784 
6785  case Stmt::ExprWithCleanupsClass:
6786  return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
6787  ParentDecl);
6788 
6789  case Stmt::DeclRefExprClass: {
6790  // When we hit a DeclRefExpr we are looking at code that refers to a
6791  // variable's name. If it's not a reference variable we check if it has
6792  // local storage within the function, and if so, return the expression.
6793  const DeclRefExpr *DR = cast<DeclRefExpr>(E);
6794 
6795  // If we leave the immediate function, the lifetime isn't about to end.
6797  return nullptr;
6798 
6799  if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
6800  // Check if it refers to itself, e.g. "int& i = i;".
6801  if (V == ParentDecl)
6802  return DR;
6803 
6804  if (V->hasLocalStorage()) {
6805  if (!V->getType()->isReferenceType())
6806  return DR;
6807 
6808  // Reference variable, follow through to the expression that
6809  // it points to.
6810  if (V->hasInit()) {
6811  // Add the reference variable to the "trail".
6812  refVars.push_back(DR);
6813  return EvalVal(V->getInit(), refVars, V);
6814  }
6815  }
6816  }
6817 
6818  return nullptr;
6819  }
6820 
6821  case Stmt::UnaryOperatorClass: {
6822  // The only unary operator that make sense to handle here
6823  // is Deref. All others don't resolve to a "name." This includes
6824  // handling all sorts of rvalues passed to a unary operator.
6825  const UnaryOperator *U = cast<UnaryOperator>(E);
6826 
6827  if (U->getOpcode() == UO_Deref)
6828  return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
6829 
6830  return nullptr;
6831  }
6832 
6833  case Stmt::ArraySubscriptExprClass: {
6834  // Array subscripts are potential references to data on the stack. We
6835  // retrieve the DeclRefExpr* for the array variable if it indeed
6836  // has local storage.
6837  const auto *ASE = cast<ArraySubscriptExpr>(E);
6838  if (ASE->isTypeDependent())
6839  return nullptr;
6840  return EvalAddr(ASE->getBase(), refVars, ParentDecl);
6841  }
6842 
6843  case Stmt::OMPArraySectionExprClass: {
6844  return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
6845  ParentDecl);
6846  }
6847 
6848  case Stmt::ConditionalOperatorClass: {
6849  // For conditional operators we need to see if either the LHS or RHS are
6850  // non-NULL Expr's. If one is non-NULL, we return it.
6851  const ConditionalOperator *C = cast<ConditionalOperator>(E);
6852 
6853  // Handle the GNU extension for missing LHS.
6854  if (const Expr *LHSExpr = C->getLHS()) {
6855  // In C++, we can have a throw-expression, which has 'void' type.
6856  if (!LHSExpr->getType()->isVoidType())
6857  if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
6858  return LHS;
6859  }
6860 
6861  // In C++, we can have a throw-expression, which has 'void' type.
6862  if (C->getRHS()->getType()->isVoidType())
6863  return nullptr;
6864 
6865  return EvalVal(C->getRHS(), refVars, ParentDecl);
6866  }
6867 
6868  // Accesses to members are potential references to data on the stack.
6869  case Stmt::MemberExprClass: {
6870  const MemberExpr *M = cast<MemberExpr>(E);
6871 
6872  // Check for indirect access. We only want direct field accesses.
6873  if (M->isArrow())
6874  return nullptr;
6875 
6876  // Check whether the member type is itself a reference, in which case
6877  // we're not going to refer to the member, but to what the member refers
6878  // to.
6879  if (M->getMemberDecl()->getType()->isReferenceType())
6880  return nullptr;
6881 
6882  return EvalVal(M->getBase(), refVars, ParentDecl);
6883  }
6884 
6885  case Stmt::MaterializeTemporaryExprClass:
6886  if (const Expr *Result =
6887  EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
6888  refVars, ParentDecl))
6889  return Result;
6890  return E;
6891 
6892  default:
6893  // Check that we don't return or take the address of a reference to a
6894  // temporary. This is only useful in C++.
6895  if (!E->isTypeDependent() && E->isRValue())
6896  return E;
6897 
6898  // Everything else: we simply don't reason about them.
6899  return nullptr;
6900  }
6901  } while (true);
6902 }
6903 
6904 void
6905 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
6906  SourceLocation ReturnLoc,
6907  bool isObjCMethod,
6908  const AttrVec *Attrs,
6909  const FunctionDecl *FD) {
6910  CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
6911 
6912  // Check if the return value is null but should not be.
6913  if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
6914  (!isObjCMethod && isNonNullType(Context, lhsType))) &&
6915  CheckNonNullExpr(*this, RetValExp))
6916  Diag(ReturnLoc, diag::warn_null_ret)
6917  << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
6918 
6919  // C++11 [basic.stc.dynamic.allocation]p4:
6920  // If an allocation function declared with a non-throwing
6921  // exception-specification fails to allocate storage, it shall return
6922  // a null pointer. Any other allocation function that fails to allocate
6923  // storage shall indicate failure only by throwing an exception [...]
6924  if (FD) {
6926  if (Op == OO_New || Op == OO_Array_New) {
6927  const FunctionProtoType *Proto
6928  = FD->getType()->castAs<FunctionProtoType>();
6929  if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
6930  CheckNonNullExpr(*this, RetValExp))
6931  Diag(ReturnLoc, diag::warn_operator_new_returns_null)
6932  << FD << getLangOpts().CPlusPlus11;
6933  }
6934  }
6935 }
6936 
6937 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
6938 
6939 /// Check for comparisons of floating point operands using != and ==.
6940 /// Issue a warning if these are no self-comparisons, as they are not likely
6941 /// to do what the programmer intended.
6942 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
6943  Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
6944  Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
6945 
6946  // Special case: check for x == x (which is OK).
6947  // Do not emit warnings for such cases.
6948  if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
6949  if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
6950  if (DRL->getDecl() == DRR->getDecl())
6951  return;
6952 
6953  // Special case: check for comparisons against literals that can be exactly
6954  // represented by APFloat. In such cases, do not emit a warning. This
6955  // is a heuristic: often comparison against such literals are used to
6956  // detect if a value in a variable has not changed. This clearly can
6957  // lead to false negatives.
6958  if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
6959  if (FLL->isExact())
6960  return;
6961  } else
6962  if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
6963  if (FLR->isExact())
6964  return;
6965 
6966  // Check for comparisons with builtin types.
6967  if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
6968  if (CL->getBuiltinCallee())
6969  return;
6970 
6971  if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
6972  if (CR->getBuiltinCallee())
6973  return;
6974 
6975  // Emit the diagnostic.
6976  Diag(Loc, diag::warn_floatingpoint_eq)
6977  << LHS->getSourceRange() << RHS->getSourceRange();
6978 }
6979 
6980 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
6981 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
6982 
6983 namespace {
6984 
6985 /// Structure recording the 'active' range of an integer-valued
6986 /// expression.
6987 struct IntRange {
6988  /// The number of bits active in the int.
6989  unsigned Width;
6990 
6991  /// True if the int is known not to have negative values.
6992  bool NonNegative;
6993 
6994  IntRange(unsigned Width, bool NonNegative)
6995  : Width(Width), NonNegative(NonNegative)
6996  {}
6997 
6998  /// Returns the range of the bool type.
6999  static IntRange forBoolType() {
7000  return IntRange(1, true);
7001  }
7002 
7003  /// Returns the range of an opaque value of the given integral type.
7004  static IntRange forValueOfType(ASTContext &C, QualType T) {
7005  return forValueOfCanonicalType(C,
7007  }
7008 
7009  /// Returns the range of an opaque value of a canonical integral type.
7010  static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
7011  assert(T->isCanonicalUnqualified());
7012 
7013  if (const VectorType *VT = dyn_cast<VectorType>(T))
7014  T = VT->getElementType().getTypePtr();
7015  if (const ComplexType *CT = dyn_cast<ComplexType>(T))
7016  T = CT->getElementType().getTypePtr();
7017  if (const AtomicType *AT = dyn_cast<AtomicType>(T))
7018  T = AT->getValueType().getTypePtr();
7019 
7020  // For enum types, use the known bit width of the enumerators.
7021  if (const EnumType *ET = dyn_cast<EnumType>(T)) {
7022  EnumDecl *Enum = ET->getDecl();
7023  if (!Enum->isCompleteDefinition())
7024  return IntRange(C.getIntWidth(QualType(T, 0)), false);
7025 
7026  unsigned NumPositive = Enum->getNumPositiveBits();
7027  unsigned NumNegative = Enum->getNumNegativeBits();
7028 
7029  if (NumNegative == 0)
7030  return IntRange(NumPositive, true/*NonNegative*/);
7031  else
7032  return IntRange(std::max(NumPositive + 1, NumNegative),
7033  false/*NonNegative*/);
7034  }
7035 
7036  const BuiltinType *BT = cast<BuiltinType>(T);
7037  assert(BT->isInteger());
7038 
7039  return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
7040  }
7041 
7042  /// Returns the "target" range of a canonical integral type, i.e.
7043  /// the range of values expressible in the type.
7044  ///
7045  /// This matches forValueOfCanonicalType except that enums have the
7046  /// full range of their type, not the range of their enumerators.
7047  static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
7048  assert(T->isCanonicalUnqualified());
7049 
7050  if (const VectorType *VT = dyn_cast<VectorType>(T))
7051  T = VT->getElementType().getTypePtr();
7052  if (const ComplexType *CT = dyn_cast<ComplexType>(T))
7053  T = CT->getElementType().getTypePtr();
7054  if (const AtomicType *AT = dyn_cast<AtomicType>(T))
7055  T = AT->getValueType().getTypePtr();
7056  if (const EnumType *ET = dyn_cast<EnumType>(T))
7057  T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
7058 
7059  const BuiltinType *BT = cast<BuiltinType>(T);
7060  assert(BT->isInteger());
7061 
7062  return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
7063  }
7064 
7065  /// Returns the supremum of two ranges: i.e. their conservative merge.
7066  static IntRange join(IntRange L, IntRange R) {
7067  return IntRange(std::max(L.Width, R.Width),
7068  L.NonNegative && R.NonNegative);
7069  }
7070 
7071  /// Returns the infinum of two ranges: i.e. their aggressive merge.
7072  static IntRange meet(IntRange L, IntRange R) {
7073  return IntRange(std::min(L.Width, R.Width),
7074  L.NonNegative || R.NonNegative);
7075  }
7076 };
7077 
7078 IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
7079  if (value.isSigned() && value.isNegative())
7080  return IntRange(value.getMinSignedBits(), false);
7081 
7082  if (value.getBitWidth() > MaxWidth)
7083  value = value.trunc(MaxWidth);
7084 
7085  // isNonNegative() just checks the sign bit without considering
7086  // signedness.
7087  return IntRange(value.getActiveBits(), true);
7088 }
7089 
7090 IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
7091  unsigned MaxWidth) {
7092  if (result.isInt())
7093  return GetValueRange(C, result.getInt(), MaxWidth);
7094 
7095  if (result.isVector()) {
7096  IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
7097  for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
7098  IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
7099  R = IntRange::join(R, El);
7100  }
7101  return R;
7102  }
7103 
7104  if (result.isComplexInt()) {
7105  IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
7106  IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
7107  return IntRange::join(R, I);
7108  }
7109 
7110  // This can happen with lossless casts to intptr_t of "based" lvalues.
7111  // Assume it might use arbitrary bits.
7112  // FIXME: The only reason we need to pass the type in here is to get
7113  // the sign right on this one case. It would be nice if APValue
7114  // preserved this.
7115  assert(result.isLValue() || result.isAddrLabelDiff());
7116  return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
7117 }
7118 
7119 QualType GetExprType(const Expr *E) {
7120  QualType Ty = E->getType();
7121  if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
7122  Ty = AtomicRHS->getValueType();
7123  return Ty;
7124 }
7125 
7126 /// Pseudo-evaluate the given integer expression, estimating the
7127 /// range of values it might take.
7128 ///
7129 /// \param MaxWidth - the width to which the value will be truncated
7130 IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
7131  E = E->IgnoreParens();
7132 
7133  // Try a full evaluation first.
7134  Expr::EvalResult result;
7135  if (E->EvaluateAsRValue(result, C))
7136  return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
7137 
7138  // I think we only want to look through implicit casts here; if the
7139  // user has an explicit widening cast, we should treat the value as
7140  // being of the new, wider type.
7141  if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
7142  if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
7143  return GetExprRange(C, CE->getSubExpr(), MaxWidth);
7144 
7145  IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
7146 
7147  bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
7148  CE->getCastKind() == CK_BooleanToSignedIntegral;
7149 
7150  // Assume that non-integer casts can span the full range of the type.
7151  if (!isIntegerCast)
7152  return OutputTypeRange;
7153 
7154  IntRange SubRange
7155  = GetExprRange(C, CE->getSubExpr(),
7156  std::min(MaxWidth, OutputTypeRange.Width));
7157 
7158  // Bail out if the subexpr's range is as wide as the cast type.
7159  if (SubRange.Width >= OutputTypeRange.Width)
7160  return OutputTypeRange;
7161 
7162  // Otherwise, we take the smaller width, and we're non-negative if
7163  // either the output type or the subexpr is.
7164  return IntRange(SubRange.Width,
7165  SubRange.NonNegative || OutputTypeRange.NonNegative);
7166  }
7167 
7168  if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
7169  // If we can fold the condition, just take that operand.
7170  bool CondResult;
7171  if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
7172  return GetExprRange(C, CondResult ? CO->getTrueExpr()
7173  : CO->getFalseExpr(),
7174  MaxWidth);
7175 
7176  // Otherwise, conservatively merge.
7177  IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
7178  IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
7179  return IntRange::join(L, R);
7180  }
7181 
7182  if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
7183  switch (BO->getOpcode()) {
7184 
7185  // Boolean-valued operations are single-bit and positive.
7186  case BO_LAnd:
7187  case BO_LOr:
7188  case BO_LT:
7189  case BO_GT:
7190  case BO_LE:
7191  case BO_GE:
7192  case BO_EQ:
7193  case BO_NE:
7194  return IntRange::forBoolType();
7195 
7196  // The type of the assignments is the type of the LHS, so the RHS
7197  // is not necessarily the same type.
7198  case BO_MulAssign:
7199  case BO_DivAssign:
7200  case BO_RemAssign:
7201  case BO_AddAssign:
7202  case BO_SubAssign:
7203  case BO_XorAssign:
7204  case BO_OrAssign:
7205  // TODO: bitfields?
7206  return IntRange::forValueOfType(C, GetExprType(E));
7207 
7208  // Simple assignments just pass through the RHS, which will have
7209  // been coerced to the LHS type.
7210  case BO_Assign:
7211  // TODO: bitfields?
7212  return GetExprRange(C, BO->getRHS(), MaxWidth);
7213 
7214  // Operations with opaque sources are black-listed.
7215  case BO_PtrMemD:
7216  case BO_PtrMemI:
7217  return IntRange::forValueOfType(C, GetExprType(E));
7218 
7219  // Bitwise-and uses the *infinum* of the two source ranges.
7220  case BO_And:
7221  case BO_AndAssign:
7222  return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
7223  GetExprRange(C, BO->getRHS(), MaxWidth));
7224 
7225  // Left shift gets black-listed based on a judgement call.
7226  case BO_Shl:
7227  // ...except that we want to treat '1 << (blah)' as logically
7228  // positive. It's an important idiom.
7229  if (IntegerLiteral *I
7230  = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
7231  if (I->getValue() == 1) {
7232  IntRange R = IntRange::forValueOfType(C, GetExprType(E));
7233  return IntRange(R.Width, /*NonNegative*/ true);
7234  }
7235  }
7236  // fallthrough
7237 
7238  case BO_ShlAssign:
7239  return IntRange::forValueOfType(C, GetExprType(E));
7240 
7241  // Right shift by a constant can narrow its left argument.
7242  case BO_Shr:
7243  case BO_ShrAssign: {
7244  IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
7245 
7246  // If the shift amount is a positive constant, drop the width by
7247  // that much.
7248  llvm::APSInt shift;
7249  if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
7250  shift.isNonNegative()) {
7251  unsigned zext = shift.getZExtValue();
7252  if (zext >= L.Width)
7253  L.Width = (L.NonNegative ? 0 : 1);
7254  else
7255  L.Width -= zext;
7256  }
7257 
7258  return L;
7259  }
7260 
7261  // Comma acts as its right operand.
7262  case BO_Comma:
7263  return GetExprRange(C, BO->getRHS(), MaxWidth);
7264 
7265  // Black-list pointer subtractions.
7266  case BO_Sub:
7267  if (BO->getLHS()->getType()->isPointerType())
7268  return IntRange::forValueOfType(C, GetExprType(E));
7269  break;
7270 
7271  // The width of a division result is mostly determined by the size
7272  // of the LHS.
7273  case BO_Div: {
7274  // Don't 'pre-truncate' the operands.
7275  unsigned opWidth = C.getIntWidth(GetExprType(E));
7276  IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
7277 
7278  // If the divisor is constant, use that.
7279  llvm::APSInt divisor;
7280  if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
7281  unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
7282  if (log2 >= L.Width)
7283  L.Width = (L.NonNegative ? 0 : 1);
7284  else
7285  L.Width = std::min(L.Width - log2, MaxWidth);
7286  return L;
7287  }
7288 
7289  // Otherwise, just use the LHS's width.
7290  IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
7291  return IntRange(L.Width, L.NonNegative && R.NonNegative);
7292  }
7293 
7294  // The result of a remainder can't be larger than the result of
7295  // either side.
7296  case BO_Rem: {
7297  // Don't 'pre-truncate' the operands.
7298  unsigned opWidth = C.getIntWidth(GetExprType(E));
7299  IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
7300  IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
7301 
7302  IntRange meet = IntRange::meet(L, R);
7303  meet.Width = std::min(meet.Width, MaxWidth);
7304  return meet;
7305  }
7306 
7307  // The default behavior is okay for these.
7308  case BO_Mul:
7309  case BO_Add:
7310  case BO_Xor:
7311  case BO_Or:
7312  break;
7313  }
7314 
7315  // The default case is to treat the operation as if it were closed
7316  // on the narrowest type that encompasses both operands.
7317  IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
7318  IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
7319  return IntRange::join(L, R);
7320  }
7321 
7322  if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
7323  switch (UO->getOpcode()) {
7324  // Boolean-valued operations are white-listed.
7325  case UO_LNot:
7326  return IntRange::forBoolType();
7327 
7328  // Operations with opaque sources are black-listed.
7329  case UO_Deref:
7330  case UO_AddrOf: // should be impossible
7331  return IntRange::forValueOfType(C, GetExprType(E));
7332 
7333  default:
7334  return GetExprRange(C, UO->getSubExpr(), MaxWidth);
7335  }
7336  }
7337 
7338  if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
7339  return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
7340 
7341  if (const auto *BitField = E->getSourceBitField())
7342  return IntRange(BitField->getBitWidthValue(C),
7343  BitField->getType()->isUnsignedIntegerOrEnumerationType());
7344 
7345  return IntRange::forValueOfType(C, GetExprType(E));
7346 }
7347 
7348 IntRange GetExprRange(ASTContext &C, const Expr *E) {
7349  return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
7350 }
7351 
7352 /// Checks whether the given value, which currently has the given
7353 /// source semantics, has the same value when coerced through the
7354 /// target semantics.
7355 bool IsSameFloatAfterCast(const llvm::APFloat &value,
7356  const llvm::fltSemantics &Src,
7357  const llvm::fltSemantics &Tgt) {
7358  llvm::APFloat truncated = value;
7359 
7360  bool ignored;
7361  truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
7362  truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
7363 
7364  return truncated.bitwiseIsEqual(value);
7365 }
7366 
7367 /// Checks whether the given value, which currently has the given
7368 /// source semantics, has the same value when coerced through the
7369 /// target semantics.
7370 ///
7371 /// The value might be a vector of floats (or a complex number).
7372 bool IsSameFloatAfterCast(const APValue &value,
7373  const llvm::fltSemantics &Src,
7374  const llvm::fltSemantics &Tgt) {
7375  if (value.isFloat())
7376  return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
7377 
7378  if (value.isVector()) {
7379  for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
7380  if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
7381  return false;
7382  return true;
7383  }
7384 
7385  assert(value.isComplexFloat());
7386  return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
7387  IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
7388 }
7389 
7390 void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
7391 
7392 bool IsZero(Sema &S, Expr *E) {
7393  // Suppress cases where we are comparing against an enum constant.
7394  if (const DeclRefExpr *DR =
7395  dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
7396  if (isa<EnumConstantDecl>(DR->getDecl()))
7397  return false;
7398 
7399  // Suppress cases where the '0' value is expanded from a macro.
7400  if (E->getLocStart().isMacroID())
7401  return false;
7402 
7403  llvm::APSInt Value;
7404  return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
7405 }
7406 
7407 bool HasEnumType(Expr *E) {
7408  // Strip off implicit integral promotions.
7409  while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
7410  if (ICE->getCastKind() != CK_IntegralCast &&
7411  ICE->getCastKind() != CK_NoOp)
7412  break;
7413  E = ICE->getSubExpr();
7414  }
7415 
7416  return E->getType()->isEnumeralType();
7417 }
7418 
7419 void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
7420  // Disable warning in template instantiations.
7421  if (!S.ActiveTemplateInstantiations.empty())
7422  return;
7423 
7424  BinaryOperatorKind op = E->getOpcode();
7425  if (E->isValueDependent())
7426  return;
7427 
7428  if (op == BO_LT && IsZero(S, E->getRHS())) {
7429  S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
7430  << "< 0" << "false" << HasEnumType(E->getLHS())
7431  << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
7432  } else if (op == BO_GE && IsZero(S, E->getRHS())) {
7433  S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
7434  << ">= 0" << "true" << HasEnumType(E->getLHS())
7435  << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
7436  } else if (op == BO_GT && IsZero(S, E->getLHS())) {
7437  S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
7438  << "0 >" << "false" << HasEnumType(E->getRHS())
7439  << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
7440  } else if (op == BO_LE && IsZero(S, E->getLHS())) {
7441  S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
7442  << "0 <=" << "true" << HasEnumType(E->getRHS())
7443  << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
7444  }
7445 }
7446 
7447 void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E, Expr *Constant,
7448  Expr *Other, const llvm::APSInt &Value,
7449  bool RhsConstant) {
7450  // Disable warning in template instantiations.
7451  if (!S.ActiveTemplateInstantiations.empty())
7452  return;
7453 
7454  // TODO: Investigate using GetExprRange() to get tighter bounds
7455  // on the bit ranges.
7456  QualType OtherT = Other->getType();
7457  if (const auto *AT = OtherT->getAs<AtomicType>())
7458  OtherT = AT->getValueType();
7459  IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
7460  unsigned OtherWidth = OtherRange.Width;
7461 
7462  bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
7463 
7464  // 0 values are handled later by CheckTrivialUnsignedComparison().
7465  if ((Value == 0) && (!OtherIsBooleanType))
7466  return;
7467 
7468  BinaryOperatorKind op = E->getOpcode();
7469  bool IsTrue = true;
7470 
7471  // Used for diagnostic printout.
7472  enum {
7473  LiteralConstant = 0,
7474  CXXBoolLiteralTrue,
7475  CXXBoolLiteralFalse
7476  } LiteralOrBoolConstant = LiteralConstant;
7477 
7478  if (!OtherIsBooleanType) {
7479  QualType ConstantT = Constant->getType();
7480  QualType CommonT = E->getLHS()->getType();
7481 
7482  if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
7483  return;
7484  assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
7485  "comparison with non-integer type");
7486 
7487  bool ConstantSigned = ConstantT->isSignedIntegerType();
7488  bool CommonSigned = CommonT->isSignedIntegerType();
7489 
7490  bool EqualityOnly = false;
7491 
7492  if (CommonSigned) {
7493  // The common type is signed, therefore no signed to unsigned conversion.
7494  if (!OtherRange.NonNegative) {
7495  // Check that the constant is representable in type OtherT.
7496  if (ConstantSigned) {
7497  if (OtherWidth >= Value.getMinSignedBits())
7498  return;
7499  } else { // !ConstantSigned
7500  if (OtherWidth >= Value.getActiveBits() + 1)
7501  return;
7502  }
7503  } else { // !OtherSigned
7504  // Check that the constant is representable in type OtherT.
7505  // Negative values are out of range.
7506  if (ConstantSigned) {
7507  if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
7508  return;
7509  } else { // !ConstantSigned
7510  if (OtherWidth >= Value.getActiveBits())
7511  return;
7512  }
7513  }
7514  } else { // !CommonSigned
7515  if (OtherRange.NonNegative) {
7516  if (OtherWidth >= Value.getActiveBits())
7517  return;
7518  } else { // OtherSigned
7519  assert(!ConstantSigned &&
7520  "Two signed types converted to unsigned types.");
7521  // Check to see if the constant is representable in OtherT.
7522  if (OtherWidth > Value.getActiveBits())
7523  return;
7524  // Check to see if the constant is equivalent to a negative value
7525  // cast to CommonT.
7526  if (S.Context.getIntWidth(ConstantT) ==
7527  S.Context.getIntWidth(CommonT) &&
7528  Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
7529  return;
7530  // The constant value rests between values that OtherT can represent
7531  // after conversion. Relational comparison still works, but equality
7532  // comparisons will be tautological.
7533  EqualityOnly = true;
7534  }
7535  }
7536 
7537  bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
7538 
7539  if (op == BO_EQ || op == BO_NE) {
7540  IsTrue = op == BO_NE;
7541  } else if (EqualityOnly) {
7542  return;
7543  } else if (RhsConstant) {
7544  if (op == BO_GT || op == BO_GE)
7545  IsTrue = !PositiveConstant;
7546  else // op == BO_LT || op == BO_LE
7547  IsTrue = PositiveConstant;
7548  } else {
7549  if (op == BO_LT || op == BO_LE)
7550  IsTrue = !PositiveConstant;
7551  else // op == BO_GT || op == BO_GE
7552  IsTrue = PositiveConstant;
7553  }
7554  } else {
7555  // Other isKnownToHaveBooleanValue
7556  enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
7557  enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
7558  enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
7559 
7560  static const struct LinkedConditions {
7561  CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
7562  CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
7563  CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
7564  CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
7565  CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
7566  CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
7567 
7568  } TruthTable = {
7569  // Constant on LHS. | Constant on RHS. |
7570  // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
7571  { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
7572  { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
7573  { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
7574  { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
7575  { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
7576  { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
7577  };
7578 
7579  bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
7580 
7581  enum ConstantValue ConstVal = Zero;
7582  if (Value.isUnsigned() || Value.isNonNegative()) {
7583  if (Value == 0) {
7584  LiteralOrBoolConstant =
7585  ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
7586  ConstVal = Zero;
7587  } else if (Value == 1) {
7588  LiteralOrBoolConstant =
7589  ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
7590  ConstVal = One;
7591  } else {
7592  LiteralOrBoolConstant = LiteralConstant;
7593  ConstVal = GT_One;
7594  }
7595  } else {
7596  ConstVal = LT_Zero;
7597  }
7598 
7599  CompareBoolWithConstantResult CmpRes;
7600 
7601  switch (op) {
7602  case BO_LT:
7603  CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
7604  break;
7605  case BO_GT:
7606  CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
7607  break;
7608  case BO_LE:
7609  CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
7610  break;
7611  case BO_GE:
7612  CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
7613  break;
7614  case BO_EQ:
7615  CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
7616  break;
7617  case BO_NE:
7618  CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
7619  break;
7620  default:
7621  CmpRes = Unkwn;
7622  break;
7623  }
7624 
7625  if (CmpRes == AFals) {
7626  IsTrue = false;
7627  } else if (CmpRes == ATrue) {
7628  IsTrue = true;
7629  } else {
7630  return;
7631  }
7632  }
7633 
7634  // If this is a comparison to an enum constant, include that
7635  // constant in the diagnostic.
7636  const EnumConstantDecl *ED = nullptr;
7637  if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
7638  ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
7639 
7640  SmallString<64> PrettySourceValue;
7641  llvm::raw_svector_ostream OS(PrettySourceValue);
7642  if (ED)
7643  OS << '\'' << *ED << "' (" << Value << ")";
7644  else
7645  OS << Value;
7646 
7648  E->getOperatorLoc(), E,
7649  S.PDiag(diag::warn_out_of_range_compare)
7650  << OS.str() << LiteralOrBoolConstant
7651  << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
7652  << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
7653 }
7654 
7655 /// Analyze the operands of the given comparison. Implements the
7656 /// fallback case from AnalyzeComparison.
7657 void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
7658  AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
7659  AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
7660 }
7661 
7662 /// \brief Implements -Wsign-compare.
7663 ///
7664 /// \param E the binary operator to check for warnings
7665 void AnalyzeComparison(Sema &S, BinaryOperator *E) {
7666  // The type the comparison is being performed in.
7667  QualType T = E->getLHS()->getType();
7668 
7669  // Only analyze comparison operators where both sides have been converted to
7670  // the same type.
7671  if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
7672  return AnalyzeImpConvsInComparison(S, E);
7673 
7674  // Don't analyze value-dependent comparisons directly.
7675  if (E->isValueDependent())
7676  return AnalyzeImpConvsInComparison(S, E);
7677 
7678  Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
7679  Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
7680 
7681  bool IsComparisonConstant = false;
7682 
7683  // Check whether an integer constant comparison results in a value
7684  // of 'true' or 'false'.
7685  if (T->isIntegralType(S.Context)) {
7686  llvm::APSInt RHSValue;
7687  bool IsRHSIntegralLiteral =
7688  RHS->isIntegerConstantExpr(RHSValue, S.Context);
7689  llvm::APSInt LHSValue;
7690  bool IsLHSIntegralLiteral =
7691  LHS->isIntegerConstantExpr(LHSValue, S.Context);
7692  if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
7693  DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
7694  else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
7695  DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
7696  else
7697  IsComparisonConstant =
7698  (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
7699  } else if (!T->hasUnsignedIntegerRepresentation())
7700  IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
7701 
7702  // We don't do anything special if this isn't an unsigned integral
7703  // comparison: we're only interested in integral comparisons, and
7704  // signed comparisons only happen in cases we don't care to warn about.
7705  //
7706  // We also don't care about value-dependent expressions or expressions
7707  // whose result is a constant.
7708  if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
7709  return AnalyzeImpConvsInComparison(S, E);
7710 
7711  // Check to see if one of the (unmodified) operands is of different
7712  // signedness.
7713  Expr *signedOperand, *unsignedOperand;
7714  if (LHS->getType()->hasSignedIntegerRepresentation()) {
7715  assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
7716  "unsigned comparison between two signed integer expressions?");
7717  signedOperand = LHS;
7718  unsignedOperand = RHS;
7719  } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
7720  signedOperand = RHS;
7721  unsignedOperand = LHS;
7722  } else {
7723  CheckTrivialUnsignedComparison(S, E);
7724  return AnalyzeImpConvsInComparison(S, E);
7725  }
7726 
7727  // Otherwise, calculate the effective range of the signed operand.
7728  IntRange signedRange = GetExprRange(S.Context, signedOperand);
7729 
7730  // Go ahead and analyze implicit conversions in the operands. Note
7731  // that we skip the implicit conversions on both sides.
7732  AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
7733  AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
7734 
7735  // If the signed range is non-negative, -Wsign-compare won't fire,
7736  // but we should still check for comparisons which are always true
7737  // or false.
7738  if (signedRange.NonNegative)
7739  return CheckTrivialUnsignedComparison(S, E);
7740 
7741  // For (in)equality comparisons, if the unsigned operand is a
7742  // constant which cannot collide with a overflowed signed operand,
7743  // then reinterpreting the signed operand as unsigned will not
7744  // change the result of the comparison.
7745  if (E->isEqualityOp()) {
7746  unsigned comparisonWidth = S.Context.getIntWidth(T);
7747  IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
7748 
7749  // We should never be unable to prove that the unsigned operand is
7750  // non-negative.
7751  assert(unsignedRange.NonNegative && "unsigned range includes negative?");
7752 
7753  if (unsignedRange.Width < comparisonWidth)
7754  return;
7755  }
7756 
7758  S.PDiag(diag::warn_mixed_sign_comparison)
7759  << LHS->getType() << RHS->getType()
7760  << LHS->getSourceRange() << RHS->getSourceRange());
7761 }
7762 
7763 /// Analyzes an attempt to assign the given value to a bitfield.
7764 ///
7765 /// Returns true if there was something fishy about the attempt.
7766 bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
7767  SourceLocation InitLoc) {
7768  assert(Bitfield->isBitField());
7769  if (Bitfield->isInvalidDecl())
7770  return false;
7771 
7772  // White-list bool bitfields.
7773  if (Bitfield->getType()->isBooleanType())
7774  return false;
7775 
7776  // Ignore value- or type-dependent expressions.
7777  if (Bitfield->getBitWidth()->isValueDependent() ||
7778  Bitfield->getBitWidth()->isTypeDependent() ||
7779  Init->isValueDependent() ||
7780  Init->isTypeDependent())
7781  return false;
7782 
7783  Expr *OriginalInit = Init->IgnoreParenImpCasts();
7784 
7785  llvm::APSInt Value;
7786  if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
7787  return false;
7788 
7789  unsigned OriginalWidth = Value.getBitWidth();
7790  unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
7791 
7792  if (Value.isSigned() && Value.isNegative())
7793  if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
7794  if (UO->getOpcode() == UO_Minus)
7795  if (isa<IntegerLiteral>(UO->getSubExpr()))
7796  OriginalWidth = Value.getMinSignedBits();
7797 
7798  if (OriginalWidth <= FieldWidth)
7799  return false;
7800 
7801  // Compute the value which the bitfield will contain.
7802  llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
7803  TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
7804 
7805  // Check whether the stored value is equal to the original value.
7806  TruncatedValue = TruncatedValue.extend(OriginalWidth);
7807  if (llvm::APSInt::isSameValue(Value, TruncatedValue))
7808  return false;
7809 
7810  // Special-case bitfields of width 1: booleans are naturally 0/1, and
7811  // therefore don't strictly fit into a signed bitfield of width 1.
7812  if (FieldWidth == 1 && Value == 1)
7813  return false;
7814 
7815  std::string PrettyValue = Value.toString(10);
7816  std::string PrettyTrunc = TruncatedValue.toString(10);
7817 
7818  S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
7819  << PrettyValue << PrettyTrunc << OriginalInit->getType()
7820  << Init->getSourceRange();
7821 
7822  return true;
7823 }
7824 
7825 /// Analyze the given simple or compound assignment for warning-worthy
7826 /// operations.
7827 void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
7828  // Just recurse on the LHS.
7829  AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
7830 
7831  // We want to recurse on the RHS as normal unless we're assigning to
7832  // a bitfield.
7833  if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
7834  if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
7835  E->getOperatorLoc())) {
7836  // Recurse, ignoring any implicit conversions on the RHS.
7837  return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
7838  E->getOperatorLoc());
7839  }
7840  }
7841 
7842  AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
7843 }
7844 
7845 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
7846 void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
7847  SourceLocation CContext, unsigned diag,
7848  bool pruneControlFlow = false) {
7849  if (pruneControlFlow) {
7851  S.PDiag(diag)
7852  << SourceType << T << E->getSourceRange()
7853  << SourceRange(CContext));
7854  return;
7855  }
7856  S.Diag(E->getExprLoc(), diag)
7857  << SourceType << T << E->getSourceRange() << SourceRange(CContext);
7858 }
7859 
7860 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
7861 void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
7862  unsigned diag, bool pruneControlFlow = false) {
7863  DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
7864 }
7865 
7866 
7867 /// Diagnose an implicit cast from a floating point value to an integer value.
7868 void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
7869 
7870  SourceLocation CContext) {
7871  const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
7872  const bool PruneWarnings = !S.ActiveTemplateInstantiations.empty();
7873 
7874  Expr *InnerE = E->IgnoreParenImpCasts();
7875  // We also want to warn on, e.g., "int i = -1.234"
7876  if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
7877  if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
7878  InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
7879 
7880  const bool IsLiteral =
7881  isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
7882 
7883  llvm::APFloat Value(0.0);
7884  bool IsConstant =
7886  if (!IsConstant) {
7887  return DiagnoseImpCast(S, E, T, CContext,
7888  diag::warn_impcast_float_integer, PruneWarnings);
7889  }
7890 
7891  bool isExact = false;
7892 
7893  llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
7895  if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero,
7896  &isExact) == llvm::APFloat::opOK &&
7897  isExact) {
7898  if (IsLiteral) return;
7899  return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
7900  PruneWarnings);
7901  }
7902 
7903  unsigned DiagID = 0;
7904  if (IsLiteral) {
7905  // Warn on floating point literal to integer.
7906  DiagID = diag::warn_impcast_literal_float_to_integer;
7907  } else if (IntegerValue == 0) {
7908  if (Value.isZero()) { // Skip -0.0 to 0 conversion.
7909  return DiagnoseImpCast(S, E, T, CContext,
7910  diag::warn_impcast_float_integer, PruneWarnings);
7911  }
7912  // Warn on non-zero to zero conversion.
7913  DiagID = diag::warn_impcast_float_to_integer_zero;
7914  } else {
7915  if (IntegerValue.isUnsigned()) {
7916  if (!IntegerValue.isMaxValue()) {
7917  return DiagnoseImpCast(S, E, T, CContext,
7918  diag::warn_impcast_float_integer, PruneWarnings);
7919  }
7920  } else { // IntegerValue.isSigned()
7921  if (!IntegerValue.isMaxSignedValue() &&
7922  !IntegerValue.isMinSignedValue()) {
7923  return DiagnoseImpCast(S, E, T, CContext,
7924  diag::warn_impcast_float_integer, PruneWarnings);
7925  }
7926  }
7927  // Warn on evaluatable floating point expression to integer conversion.
7928  DiagID = diag::warn_impcast_float_to_integer;
7929  }
7930 
7931  // FIXME: Force the precision of the source value down so we don't print
7932  // digits which are usually useless (we don't really care here if we
7933  // truncate a digit by accident in edge cases). Ideally, APFloat::toString
7934  // would automatically print the shortest representation, but it's a bit
7935  // tricky to implement.
7936  SmallString<16> PrettySourceValue;
7937  unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
7938  precision = (precision * 59 + 195) / 196;
7939  Value.toString(PrettySourceValue, precision);
7940 
7941  SmallString<16> PrettyTargetValue;
7942  if (IsBool)
7943  PrettyTargetValue = Value.isZero() ? "false" : "true";
7944  else
7945  IntegerValue.toString(PrettyTargetValue);
7946 
7947  if (PruneWarnings) {
7949  S.PDiag(DiagID)
7950  << E->getType() << T.getUnqualifiedType()
7951  << PrettySourceValue << PrettyTargetValue
7952  << E->getSourceRange() << SourceRange(CContext));
7953  } else {
7954  S.Diag(E->getExprLoc(), DiagID)
7955  << E->getType() << T.getUnqualifiedType() << PrettySourceValue
7956  << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
7957  }
7958 }
7959 
7960 std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
7961  if (!Range.Width) return "0";
7962 
7963  llvm::APSInt ValueInRange = Value;
7964  ValueInRange.setIsSigned(!Range.NonNegative);
7965  ValueInRange = ValueInRange.trunc(Range.Width);
7966  return ValueInRange.toString(10);
7967 }
7968 
7969 bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
7970  if (!isa<ImplicitCastExpr>(Ex))
7971  return false;
7972 
7973  Expr *InnerE = Ex->IgnoreParenImpCasts();
7974  const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
7975  const Type *Source =
7976  S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
7977  if (Target->isDependentType())
7978  return false;
7979 
7980  const BuiltinType *FloatCandidateBT =
7981  dyn_cast<BuiltinType>(ToBool ? Source : Target);
7982  const Type *BoolCandidateType = ToBool ? Target : Source;
7983 
7984  return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
7985  FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
7986 }
7987 
7988 void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
7989  SourceLocation CC) {
7990  unsigned NumArgs = TheCall->getNumArgs();
7991  for (unsigned i = 0; i < NumArgs; ++i) {
7992  Expr *CurrA = TheCall->getArg(i);
7993  if (!IsImplicitBoolFloatConversion(S, CurrA, true))
7994  continue;
7995 
7996  bool IsSwapped = ((i > 0) &&
7997  IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
7998  IsSwapped |= ((i < (NumArgs - 1)) &&
7999  IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
8000  if (IsSwapped) {
8001  // Warn on this floating-point to bool conversion.
8002  DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
8003  CurrA->getType(), CC,
8004  diag::warn_impcast_floating_point_to_bool);
8005  }
8006  }
8007 }
8008 
8009 void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) {
8010  if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
8011  E->getExprLoc()))
8012  return;
8013 
8014  // Don't warn on functions which have return type nullptr_t.
8015  if (isa<CallExpr>(E))
8016  return;
8017 
8018  // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
8019  const Expr::NullPointerConstantKind NullKind =
8021  if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
8022  return;
8023 
8024  // Return if target type is a safe conversion.
8025  if (T->isAnyPointerType() || T->isBlockPointerType() ||
8026  T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
8027  return;
8028 
8029  SourceLocation Loc = E->getSourceRange().getBegin();
8030 
8031  // Venture through the macro stacks to get to the source of macro arguments.
8032  // The new location is a better location than the complete location that was
8033  // passed in.
8034  while (S.SourceMgr.isMacroArgExpansion(Loc))
8036 
8037  while (S.SourceMgr.isMacroArgExpansion(CC))
8039 
8040  // __null is usually wrapped in a macro. Go up a macro if that is the case.
8041  if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
8042  StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
8043  Loc, S.SourceMgr, S.getLangOpts());
8044  if (MacroName == "NULL")
8045  Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
8046  }
8047 
8048  // Only warn if the null and context location are in the same macro expansion.
8049  if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
8050  return;
8051 
8052  S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
8053  << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
8055  S.getFixItZeroLiteralForType(T, Loc));
8056 }
8057 
8058 void checkObjCArrayLiteral(Sema &S, QualType TargetType,
8059  ObjCArrayLiteral *ArrayLiteral);
8060 void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
8061  ObjCDictionaryLiteral *DictionaryLiteral);
8062 
8063 /// Check a single element within a collection literal against the
8064 /// target element type.
8065 void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType,
8066  Expr *Element, unsigned ElementKind) {
8067  // Skip a bitcast to 'id' or qualified 'id'.
8068  if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
8069  if (ICE->getCastKind() == CK_BitCast &&
8070  ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
8071  Element = ICE->getSubExpr();
8072  }
8073 
8074  QualType ElementType = Element->getType();
8075  ExprResult ElementResult(Element);
8076  if (ElementType->getAs<ObjCObjectPointerType>() &&
8077  S.CheckSingleAssignmentConstraints(TargetElementType,
8078  ElementResult,
8079  false, false)
8080  != Sema::Compatible) {
8081  S.Diag(Element->getLocStart(),
8082  diag::warn_objc_collection_literal_element)
8083  << ElementType << ElementKind << TargetElementType
8084  << Element->getSourceRange();
8085  }
8086 
8087  if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
8088  checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
8089  else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
8090  checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
8091 }
8092 
8093 /// Check an Objective-C array literal being converted to the given
8094 /// target type.
8095 void checkObjCArrayLiteral(Sema &S, QualType TargetType,
8096  ObjCArrayLiteral *ArrayLiteral) {
8097  if (!S.NSArrayDecl)
8098  return;
8099 
8100  const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
8101  if (!TargetObjCPtr)
8102  return;
8103 
8104  if (TargetObjCPtr->isUnspecialized() ||
8105  TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
8106  != S.NSArrayDecl->getCanonicalDecl())
8107  return;
8108 
8109  auto TypeArgs = TargetObjCPtr->getTypeArgs();
8110  if (TypeArgs.size() != 1)
8111  return;
8112 
8113  QualType TargetElementType = TypeArgs[0];
8114  for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
8115  checkObjCCollectionLiteralElement(S, TargetElementType,
8116  ArrayLiteral->getElement(I),
8117  0);
8118  }
8119 }
8120 
8121 /// Check an Objective-C dictionary literal being converted to the given
8122 /// target type.
8123 void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
8124  ObjCDictionaryLiteral *DictionaryLiteral) {
8125  if (!S.NSDictionaryDecl)
8126  return;
8127 
8128  const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
8129  if (!TargetObjCPtr)
8130  return;
8131 
8132  if (TargetObjCPtr->isUnspecialized() ||
8133  TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
8135  return;
8136 
8137  auto TypeArgs = TargetObjCPtr->getTypeArgs();
8138  if (TypeArgs.size() != 2)
8139  return;
8140 
8141  QualType TargetKeyType = TypeArgs[0];
8142  QualType TargetObjectType = TypeArgs[1];
8143  for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
8144  auto Element = DictionaryLiteral->getKeyValueElement(I);
8145  checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
8146  checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
8147  }
8148 }
8149 
8150 // Helper function to filter out cases for constant width constant conversion.
8151 // Don't warn on char array initialization or for non-decimal values.
8152 bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
8153  SourceLocation CC) {
8154  // If initializing from a constant, and the constant starts with '0',
8155  // then it is a binary, octal, or hexadecimal. Allow these constants
8156  // to fill all the bits, even if there is a sign change.
8157  if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
8158  const char FirstLiteralCharacter =
8159  S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
8160  if (FirstLiteralCharacter == '0')
8161  return false;
8162  }
8163 
8164  // If the CC location points to a '{', and the type is char, then assume
8165  // assume it is an array initialization.
8166  if (CC.isValid() && T->isCharType()) {
8167  const char FirstContextCharacter =
8169  if (FirstContextCharacter == '{')
8170  return false;
8171  }
8172 
8173  return true;
8174 }
8175 
8176 void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
8177  SourceLocation CC, bool *ICContext = nullptr) {
8178  if (E->isTypeDependent() || E->isValueDependent()) return;
8179 
8180  const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
8181  const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
8182  if (Source == Target) return;
8183  if (Target->isDependentType()) return;
8184 
8185  // If the conversion context location is invalid don't complain. We also
8186  // don't want to emit a warning if the issue occurs from the expansion of
8187  // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
8188  // delay this check as long as possible. Once we detect we are in that
8189  // scenario, we just return.
8190  if (CC.isInvalid())
8191  return;
8192 
8193  // Diagnose implicit casts to bool.
8194  if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
8195  if (isa<StringLiteral>(E))
8196  // Warn on string literal to bool. Checks for string literals in logical
8197  // and expressions, for instance, assert(0 && "error here"), are
8198  // prevented by a check in AnalyzeImplicitConversions().
8199  return DiagnoseImpCast(S, E, T, CC,
8200  diag::warn_impcast_string_literal_to_bool);
8201  if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
8202  isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
8203  // This covers the literal expressions that evaluate to Objective-C
8204  // objects.
8205  return DiagnoseImpCast(S, E, T, CC,
8206  diag::warn_impcast_objective_c_literal_to_bool);
8207  }
8208  if (Source->isPointerType() || Source->canDecayToPointerType()) {
8209  // Warn on pointer to bool conversion that is always true.
8210  S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
8211  SourceRange(CC));
8212  }
8213  }
8214 
8215  // Check implicit casts from Objective-C collection literals to specialized
8216  // collection types, e.g., NSArray<NSString *> *.
8217  if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
8218  checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
8219  else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
8220  checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
8221 
8222  // Strip vector types.
8223  if (isa<VectorType>(Source)) {
8224  if (!isa<VectorType>(Target)) {
8225  if (S.SourceMgr.isInSystemMacro(CC))
8226  return;
8227  return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
8228  }
8229 
8230  // If the vector cast is cast between two vectors of the same size, it is
8231  // a bitcast, not a conversion.
8232  if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
8233  return;
8234 
8235  Source = cast<VectorType>(Source)->getElementType().getTypePtr();
8236  Target = cast<VectorType>(Target)->getElementType().getTypePtr();
8237  }
8238  if (auto VecTy = dyn_cast<VectorType>(Target))
8239  Target = VecTy->getElementType().getTypePtr();
8240 
8241  // Strip complex types.
8242  if (isa<ComplexType>(Source)) {
8243  if (!isa<ComplexType>(Target)) {
8244  if (S.SourceMgr.isInSystemMacro(CC))
8245  return;
8246 
8247  return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
8248  }
8249 
8250  Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
8251  Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
8252  }
8253 
8254  const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
8255  const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
8256 
8257  // If the source is floating point...
8258  if (SourceBT && SourceBT->isFloatingPoint()) {
8259  // ...and the target is floating point...
8260  if (TargetBT && TargetBT->isFloatingPoint()) {
8261  // ...then warn if we're dropping FP rank.
8262 
8263  // Builtin FP kinds are ordered by increasing FP rank.
8264  if (SourceBT->getKind() > TargetBT->getKind()) {
8265  // Don't warn about float constants that are precisely
8266  // representable in the target type.
8267  Expr::EvalResult result;
8268  if (E->EvaluateAsRValue(result, S.Context)) {
8269  // Value might be a float, a float vector, or a float complex.
8270  if (IsSameFloatAfterCast(result.Val,
8271  S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
8272  S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
8273  return;
8274  }
8275 
8276  if (S.SourceMgr.isInSystemMacro(CC))
8277  return;
8278 
8279  DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
8280  }
8281  // ... or possibly if we're increasing rank, too
8282  else if (TargetBT->getKind() > SourceBT->getKind()) {
8283  if (S.SourceMgr.isInSystemMacro(CC))
8284  return;
8285 
8286  DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
8287  }
8288  return;
8289  }
8290 
8291  // If the target is integral, always warn.
8292  if (TargetBT && TargetBT->isInteger()) {
8293  if (S.SourceMgr.isInSystemMacro(CC))
8294  return;
8295 
8296  DiagnoseFloatingImpCast(S, E, T, CC);
8297  }
8298 
8299  // Detect the case where a call result is converted from floating-point to
8300  // to bool, and the final argument to the call is converted from bool, to
8301  // discover this typo:
8302  //
8303  // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
8304  //
8305  // FIXME: This is an incredibly special case; is there some more general
8306  // way to detect this class of misplaced-parentheses bug?
8307  if (Target->isBooleanType() && isa<CallExpr>(E)) {
8308  // Check last argument of function call to see if it is an
8309  // implicit cast from a type matching the type the result
8310  // is being cast to.
8311  CallExpr *CEx = cast<CallExpr>(E);
8312  if (unsigned NumArgs = CEx->getNumArgs()) {
8313  Expr *LastA = CEx->getArg(NumArgs - 1);
8314  Expr *InnerE = LastA->IgnoreParenImpCasts();
8315  if (isa<ImplicitCastExpr>(LastA) &&
8316  InnerE->getType()->isBooleanType()) {
8317  // Warn on this floating-point to bool conversion
8318  DiagnoseImpCast(S, E, T, CC,
8319  diag::warn_impcast_floating_point_to_bool);
8320  }
8321  }
8322  }
8323  return;
8324  }
8325 
8326  DiagnoseNullConversion(S, E, T, CC);
8327 
8328  if (!Source->isIntegerType() || !Target->isIntegerType())
8329  return;
8330 
8331  // TODO: remove this early return once the false positives for constant->bool
8332  // in templates, macros, etc, are reduced or removed.
8333  if (Target->isSpecificBuiltinType(BuiltinType::Bool))
8334  return;
8335 
8336  IntRange SourceRange = GetExprRange(S.Context, E);
8337  IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
8338 
8339  if (SourceRange.Width > TargetRange.Width) {
8340  // If the source is a constant, use a default-on diagnostic.
8341  // TODO: this should happen for bitfield stores, too.
8342  llvm::APSInt Value(32);
8343  if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
8344  if (S.SourceMgr.isInSystemMacro(CC))
8345  return;
8346 
8347  std::string PrettySourceValue = Value.toString(10);
8348  std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
8349 
8351  S.PDiag(diag::warn_impcast_integer_precision_constant)
8352  << PrettySourceValue << PrettyTargetValue
8353  << E->getType() << T << E->getSourceRange()
8354  << clang::SourceRange(CC));
8355  return;
8356  }
8357 
8358  // People want to build with -Wshorten-64-to-32 and not -Wconversion.
8359  if (S.SourceMgr.isInSystemMacro(CC))
8360  return;
8361 
8362  if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
8363  return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
8364  /* pruneControlFlow */ true);
8365  return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
8366  }
8367 
8368  if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
8369  SourceRange.NonNegative && Source->isSignedIntegerType()) {
8370  // Warn when doing a signed to signed conversion, warn if the positive
8371  // source value is exactly the width of the target type, which will
8372  // cause a negative value to be stored.
8373 
8374  llvm::APSInt Value;
8375  if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
8376  !S.SourceMgr.isInSystemMacro(CC)) {
8377  if (isSameWidthConstantConversion(S, E, T, CC)) {
8378  std::string PrettySourceValue = Value.toString(10);
8379  std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
8380 
8382  E->getExprLoc(), E,
8383  S.PDiag(diag::warn_impcast_integer_precision_constant)
8384  << PrettySourceValue << PrettyTargetValue << E->getType() << T
8385  << E->getSourceRange() << clang::SourceRange(CC));
8386  return;
8387  }
8388  }
8389 
8390  // Fall through for non-constants to give a sign conversion warning.
8391  }
8392 
8393  if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
8394  (!TargetRange.NonNegative && SourceRange.NonNegative &&
8395  SourceRange.Width == TargetRange.Width)) {
8396  if (S.SourceMgr.isInSystemMacro(CC))
8397  return;
8398 
8399  unsigned DiagID = diag::warn_impcast_integer_sign;
8400 
8401  // Traditionally, gcc has warned about this under -Wsign-compare.
8402  // We also want to warn about it in -Wconversion.
8403  // So if -Wconversion is off, use a completely identical diagnostic
8404  // in the sign-compare group.
8405  // The conditional-checking code will
8406  if (ICContext) {
8407  DiagID = diag::warn_impcast_integer_sign_conditional;
8408  *ICContext = true;
8409  }
8410 
8411  return DiagnoseImpCast(S, E, T, CC, DiagID);
8412  }
8413 
8414  // Diagnose conversions between different enumeration types.
8415  // In C, we pretend that the type of an EnumConstantDecl is its enumeration
8416  // type, to give us better diagnostics.
8417  QualType SourceType = E->getType();
8418  if (!S.getLangOpts().CPlusPlus) {
8419  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
8420  if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
8421  EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
8422  SourceType = S.Context.getTypeDeclType(Enum);
8423  Source = S.Context.getCanonicalType(SourceType).getTypePtr();
8424  }
8425  }
8426 
8427  if (const EnumType *SourceEnum = Source->getAs<EnumType>())
8428  if (const EnumType *TargetEnum = Target->getAs<EnumType>())
8429  if (SourceEnum->getDecl()->hasNameForLinkage() &&
8430  TargetEnum->getDecl()->hasNameForLinkage() &&
8431  SourceEnum != TargetEnum) {
8432  if (S.SourceMgr.isInSystemMacro(CC))
8433  return;
8434 
8435  return DiagnoseImpCast(S, E, SourceType, T, CC,
8436  diag::warn_impcast_different_enum_types);
8437  }
8438 }
8439 
8440 void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
8441  SourceLocation CC, QualType T);
8442 
8443 void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
8444  SourceLocation CC, bool &ICContext) {
8445  E = E->IgnoreParenImpCasts();
8446 
8447  if (isa<ConditionalOperator>(E))
8448  return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
8449 
8450  AnalyzeImplicitConversions(S, E, CC);
8451  if (E->getType() != T)
8452  return CheckImplicitConversion(S, E, T, CC, &ICContext);
8453 }
8454 
8455 void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
8456  SourceLocation CC, QualType T) {
8457  AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
8458 
8459  bool Suspicious = false;
8460  CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
8461  CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
8462 
8463  // If -Wconversion would have warned about either of the candidates
8464  // for a signedness conversion to the context type...
8465  if (!Suspicious) return;
8466 
8467  // ...but it's currently ignored...
8468  if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
8469  return;
8470 
8471  // ...then check whether it would have warned about either of the
8472  // candidates for a signedness conversion to the condition type.
8473  if (E->getType() == T) return;
8474 
8475  Suspicious = false;
8476  CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
8477  E->getType(), CC, &Suspicious);
8478  if (!Suspicious)
8479  CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
8480  E->getType(), CC, &Suspicious);
8481 }
8482 
8483 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
8484 /// Input argument E is a logical expression.
8485 void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
8486  if (S.getLangOpts().Bool)
8487  return;
8488  CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
8489 }
8490 
8491 /// AnalyzeImplicitConversions - Find and report any interesting
8492 /// implicit conversions in the given expression. There are a couple
8493 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
8494 void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
8495  QualType T = OrigE->getType();
8496  Expr *E = OrigE->IgnoreParenImpCasts();
8497 
8498  if (E->isTypeDependent() || E->isValueDependent())
8499  return;
8500 
8501  // For conditional operators, we analyze the arguments as if they
8502  // were being fed directly into the output.
8503  if (isa<ConditionalOperator>(E)) {
8504  ConditionalOperator *CO = cast<ConditionalOperator>(E);
8505  CheckConditionalOperator(S, CO, CC, T);
8506  return;
8507  }
8508 
8509  // Check implicit argument conversions for function calls.
8510  if (CallExpr *Call = dyn_cast<CallExpr>(E))
8511  CheckImplicitArgumentConversions(S, Call, CC);
8512 
8513  // Go ahead and check any implicit conversions we might have skipped.
8514  // The non-canonical typecheck is just an optimization;
8515  // CheckImplicitConversion will filter out dead implicit conversions.
8516  if (E->getType() != T)
8517  CheckImplicitConversion(S, E, T, CC);
8518 
8519  // Now continue drilling into this expression.
8520 
8521  if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
8522  // The bound subexpressions in a PseudoObjectExpr are not reachable
8523  // as transitive children.
8524  // FIXME: Use a more uniform representation for this.
8525  for (auto *SE : POE->semantics())
8526  if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
8527  AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
8528  }
8529 
8530  // Skip past explicit casts.
8531  if (isa<ExplicitCastExpr>(E)) {
8532  E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
8533  return AnalyzeImplicitConversions(S, E, CC);
8534  }
8535 
8536  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
8537  // Do a somewhat different check with comparison operators.
8538  if (BO->isComparisonOp())
8539  return AnalyzeComparison(S, BO);
8540 
8541  // And with simple assignments.
8542  if (BO->getOpcode() == BO_Assign)
8543  return AnalyzeAssignment(S, BO);
8544  }
8545 
8546  // These break the otherwise-useful invariant below. Fortunately,
8547  // we don't really need to recurse into them, because any internal
8548  // expressions should have been analyzed already when they were
8549  // built into statements.
8550  if (isa<StmtExpr>(E)) return;
8551 
8552  // Don't descend into unevaluated contexts.
8553  if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
8554 
8555  // Now just recurse over the expression's children.
8556  CC = E->getExprLoc();
8557  BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
8558  bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
8559  for (Stmt *SubStmt : E->children()) {
8560  Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
8561  if (!ChildExpr)
8562  continue;
8563 
8564  if (IsLogicalAndOperator &&
8565  isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
8566  // Ignore checking string literals that are in logical and operators.
8567  // This is a common pattern for asserts.
8568  continue;
8569  AnalyzeImplicitConversions(S, ChildExpr, CC);
8570  }
8571 
8572  if (BO && BO->isLogicalOp()) {
8573  Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
8574  if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
8575  ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
8576 
8577  SubExpr = BO->getRHS()->IgnoreParenImpCasts();
8578  if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
8579  ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
8580  }
8581 
8582  if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
8583  if (U->getOpcode() == UO_LNot)
8584  ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
8585 }
8586 
8587 } // end anonymous namespace
8588 
8590  unsigned Start, unsigned End) {
8591  bool IllegalParams = false;
8592  for (unsigned I = Start; I <= End; ++I) {
8593  QualType Ty = TheCall->getArg(I)->getType();
8594  // Taking into account implicit conversions,
8595  // allow any integer within 32 bits range
8596  if (!Ty->isIntegerType() ||
8597  S.Context.getTypeSizeInChars(Ty).getQuantity() > 4) {
8598  S.Diag(TheCall->getArg(I)->getLocStart(),
8599  diag::err_opencl_enqueue_kernel_invalid_local_size_type);
8600  IllegalParams = true;
8601  }
8602  // Potentially emit standard warnings for implicit conversions if enabled
8603  // using -Wconversion.
8604  CheckImplicitConversion(S, TheCall->getArg(I), S.Context.UnsignedIntTy,
8605  TheCall->getArg(I)->getLocStart());
8606  }
8607  return IllegalParams;
8608 }
8609 
8610 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
8611 // Returns true when emitting a warning about taking the address of a reference.
8612 static bool CheckForReference(Sema &SemaRef, const Expr *E,
8613  const PartialDiagnostic &PD) {
8614  E = E->IgnoreParenImpCasts();
8615 
8616  const FunctionDecl *FD = nullptr;
8617 
8618  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
8619  if (!DRE->getDecl()->getType()->isReferenceType())
8620  return false;
8621  } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
8622  if (!M->getMemberDecl()->getType()->isReferenceType())
8623  return false;
8624  } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
8625  if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
8626  return false;
8627  FD = Call->getDirectCallee();
8628  } else {
8629  return false;
8630  }
8631 
8632  SemaRef.Diag(E->getExprLoc(), PD);
8633 
8634  // If possible, point to location of function.
8635  if (FD) {
8636  SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
8637  }
8638 
8639  return true;
8640 }
8641 
8642 // Returns true if the SourceLocation is expanded from any macro body.
8643 // Returns false if the SourceLocation is invalid, is from not in a macro
8644 // expansion, or is from expanded from a top-level macro argument.
8645 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
8646  if (Loc.isInvalid())
8647  return false;
8648 
8649  while (Loc.isMacroID()) {
8650  if (SM.isMacroBodyExpansion(Loc))
8651  return true;
8652  Loc = SM.getImmediateMacroCallerLoc(Loc);
8653  }
8654 
8655  return false;
8656 }
8657 
8658 /// \brief Diagnose pointers that are always non-null.
8659 /// \param E the expression containing the pointer
8660 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
8661 /// compared to a null pointer
8662 /// \param IsEqual True when the comparison is equal to a null pointer
8663 /// \param Range Extra SourceRange to highlight in the diagnostic
8666  bool IsEqual, SourceRange Range) {
8667  if (!E)
8668  return;
8669 
8670  // Don't warn inside macros.
8671  if (E->getExprLoc().isMacroID()) {
8672  const SourceManager &SM = getSourceManager();
8673  if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
8674  IsInAnyMacroBody(SM, Range.getBegin()))
8675  return;
8676  }
8677  E = E->IgnoreImpCasts();
8678 
8679  const bool IsCompare = NullKind != Expr::NPCK_NotNull;
8680 
8681  if (isa<CXXThisExpr>(E)) {
8682  unsigned DiagID = IsCompare ? diag::warn_this_null_compare
8683  : diag::warn_this_bool_conversion;
8684  Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
8685  return;
8686  }
8687 
8688  bool IsAddressOf = false;
8689 
8690  if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
8691  if (UO->getOpcode() != UO_AddrOf)
8692  return;
8693  IsAddressOf = true;
8694  E = UO->getSubExpr();
8695  }
8696 
8697  if (IsAddressOf) {
8698  unsigned DiagID = IsCompare
8699  ? diag::warn_address_of_reference_null_compare
8700  : diag::warn_address_of_reference_bool_conversion;
8701  PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
8702  << IsEqual;
8703  if (CheckForReference(*this, E, PD)) {
8704  return;
8705  }
8706  }
8707 
8708  auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
8709  bool IsParam = isa<NonNullAttr>(NonnullAttr);
8710  std::string Str;
8711  llvm::raw_string_ostream S(Str);
8712  E->printPretty(S, nullptr, getPrintingPolicy());
8713  unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
8714  : diag::warn_cast_nonnull_to_bool;
8715  Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
8716  << E->getSourceRange() << Range << IsEqual;
8717  Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
8718  };
8719 
8720  // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
8721  if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
8722  if (auto *Callee = Call->getDirectCallee()) {
8723  if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
8724  ComplainAboutNonnullParamOrCall(A);
8725  return;
8726  }
8727  }
8728  }
8729 
8730  // Expect to find a single Decl. Skip anything more complicated.
8731  ValueDecl *D = nullptr;
8732  if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
8733  D = R->getDecl();
8734  } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
8735  D = M->getMemberDecl();
8736  }
8737 
8738  // Weak Decls can be null.
8739  if (!D || D->isWeak())
8740  return;
8741 
8742  // Check for parameter decl with nonnull attribute
8743  if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
8744  if (getCurFunction() &&
8745  !getCurFunction()->ModifiedNonNullParams.count(PV)) {
8746  if (const Attr *A = PV->getAttr<NonNullAttr>()) {
8747  ComplainAboutNonnullParamOrCall(A);
8748  return;
8749  }
8750 
8751  if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
8752  auto ParamIter = llvm::find(FD->parameters(), PV);
8753  assert(ParamIter != FD->param_end());
8754  unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
8755 
8756  for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
8757  if (!NonNull->args_size()) {
8758  ComplainAboutNonnullParamOrCall(NonNull);
8759  return;
8760  }
8761 
8762  for (unsigned ArgNo : NonNull->args()) {
8763  if (ArgNo == ParamNo) {
8764  ComplainAboutNonnullParamOrCall(NonNull);
8765  return;
8766  }
8767  }
8768  }
8769  }
8770  }
8771  }
8772 
8773  QualType T = D->getType();
8774  const bool IsArray = T->isArrayType();
8775  const bool IsFunction = T->isFunctionType();
8776 
8777  // Address of function is used to silence the function warning.
8778  if (IsAddressOf && IsFunction) {
8779  return;
8780  }
8781 
8782  // Found nothing.
8783  if (!IsAddressOf && !IsFunction && !IsArray)
8784  return;
8785 
8786  // Pretty print the expression for the diagnostic.
8787  std::string Str;
8788  llvm::raw_string_ostream S(Str);
8789  E->printPretty(S, nullptr, getPrintingPolicy());
8790 
8791  unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
8792  : diag::warn_impcast_pointer_to_bool;
8793  enum {
8794  AddressOf,
8795  FunctionPointer,
8796  ArrayPointer
8797  } DiagType;
8798  if (IsAddressOf)
8799  DiagType = AddressOf;
8800  else if (IsFunction)
8801  DiagType = FunctionPointer;
8802  else if (IsArray)
8803  DiagType = ArrayPointer;
8804  else
8805  llvm_unreachable("Could not determine diagnostic.");
8806  Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
8807  << Range << IsEqual;
8808 
8809  if (!IsFunction)
8810  return;
8811 
8812  // Suggest '&' to silence the function warning.
8813  Diag(E->getExprLoc(), diag::note_function_warning_silence)
8814  << FixItHint::CreateInsertion(E->getLocStart(), "&");
8815 
8816  // Check to see if '()' fixit should be emitted.
8817  QualType ReturnType;
8818  UnresolvedSet<4> NonTemplateOverloads;
8819  tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
8820  if (ReturnType.isNull())
8821  return;
8822 
8823  if (IsCompare) {
8824  // There are two cases here. If there is null constant, the only suggest
8825  // for a pointer return type. If the null is 0, then suggest if the return
8826  // type is a pointer or an integer type.
8827  if (!ReturnType->isPointerType()) {
8828  if (NullKind == Expr::NPCK_ZeroExpression ||
8829  NullKind == Expr::NPCK_ZeroLiteral) {
8830  if (!ReturnType->isIntegerType())
8831  return;
8832  } else {
8833  return;
8834  }
8835  }
8836  } else { // !IsCompare
8837  // For function to bool, only suggest if the function pointer has bool
8838  // return type.
8839  if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
8840  return;
8841  }
8842  Diag(E->getExprLoc(), diag::note_function_to_function_call)
8843  << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
8844 }
8845 
8846 /// Diagnoses "dangerous" implicit conversions within the given
8847 /// expression (which is a full expression). Implements -Wconversion
8848 /// and -Wsign-compare.
8849 ///
8850 /// \param CC the "context" location of the implicit conversion, i.e.
8851 /// the most location of the syntactic entity requiring the implicit
8852 /// conversion
8853 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
8854  // Don't diagnose in unevaluated contexts.
8855  if (isUnevaluatedContext())
8856  return;
8857 
8858  // Don't diagnose for value- or type-dependent expressions.
8859  if (E->isTypeDependent() || E->isValueDependent())
8860  return;
8861 
8862  // Check for array bounds violations in cases where the check isn't triggered
8863  // elsewhere for other Expr types (like BinaryOperators), e.g. when an
8864  // ArraySubscriptExpr is on the RHS of a variable initialization.
8865  CheckArrayAccess(E);
8866 
8867  // This is not the right CC for (e.g.) a variable initialization.
8868  AnalyzeImplicitConversions(*this, E, CC);
8869 }
8870 
8871 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
8872 /// Input argument E is a logical expression.
8873 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
8874  ::CheckBoolLikeConversion(*this, E, CC);
8875 }
8876 
8877 /// Diagnose when expression is an integer constant expression and its evaluation
8878 /// results in integer overflow
8879 void Sema::CheckForIntOverflow (Expr *E) {
8880  // Use a work list to deal with nested struct initializers.
8881  SmallVector<Expr *, 2> Exprs(1, E);
8882 
8883  do {
8884  Expr *E = Exprs.pop_back_val();
8885 
8886  if (isa<BinaryOperator>(E->IgnoreParenCasts())) {
8887  E->IgnoreParenCasts()->EvaluateForOverflow(Context);
8888  continue;
8889  }
8890 
8891  if (auto InitList = dyn_cast<InitListExpr>(E))
8892  Exprs.append(InitList->inits().begin(), InitList->inits().end());
8893  } while (!Exprs.empty());
8894 }
8895 
8896 namespace {
8897 /// \brief Visitor for expressions which looks for unsequenced operations on the
8898 /// same object.
8899 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
8901 
8902  /// \brief A tree of sequenced regions within an expression. Two regions are
8903  /// unsequenced if one is an ancestor or a descendent of the other. When we
8904  /// finish processing an expression with sequencing, such as a comma
8905  /// expression, we fold its tree nodes into its parent, since they are
8906  /// unsequenced with respect to nodes we will visit later.
8907  class SequenceTree {
8908  struct Value {
8909  explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
8910  unsigned Parent : 31;
8911  unsigned Merged : 1;
8912  };
8913  SmallVector<Value, 8> Values;
8914 
8915  public:
8916  /// \brief A region within an expression which may be sequenced with respect
8917  /// to some other region.
8918  class Seq {
8919  explicit Seq(unsigned N) : Index(N) {}
8920  unsigned Index;
8921  friend class SequenceTree;
8922  public:
8923  Seq() : Index(0) {}
8924  };
8925 
8926  SequenceTree() { Values.push_back(Value(0)); }
8927  Seq root() const { return Seq(0); }
8928 
8929  /// \brief Create a new sequence of operations, which is an unsequenced
8930  /// subset of \p Parent. This sequence of operations is sequenced with
8931  /// respect to other children of \p Parent.
8932  Seq allocate(Seq Parent) {
8933  Values.push_back(Value(Parent.Index));
8934  return Seq(Values.size() - 1);
8935  }
8936 
8937  /// \brief Merge a sequence of operations into its parent.
8938  void merge(Seq S) {
8939  Values[S.Index].Merged = true;
8940  }
8941 
8942  /// \brief Determine whether two operations are unsequenced. This operation
8943  /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
8944  /// should have been merged into its parent as appropriate.
8945  bool isUnsequenced(Seq Cur, Seq Old) {
8946  unsigned C = representative(Cur.Index);
8947  unsigned Target = representative(Old.Index);
8948  while (C >= Target) {
8949  if (C == Target)
8950  return true;
8951  C = Values[C].Parent;
8952  }
8953  return false;
8954  }
8955 
8956  private:
8957  /// \brief Pick a representative for a sequence.
8958  unsigned representative(unsigned K) {
8959  if (Values[K].Merged)
8960  // Perform path compression as we go.
8961  return Values[K].Parent = representative(Values[K].Parent);
8962  return K;
8963  }
8964  };
8965 
8966  /// An object for which we can track unsequenced uses.
8967  typedef NamedDecl *Object;
8968 
8969  /// Different flavors of object usage which we track. We only track the
8970  /// least-sequenced usage of each kind.
8971  enum UsageKind {
8972  /// A read of an object. Multiple unsequenced reads are OK.
8973  UK_Use,
8974  /// A modification of an object which is sequenced before the value
8975  /// computation of the expression, such as ++n in C++.
8976  UK_ModAsValue,
8977  /// A modification of an object which is not sequenced before the value
8978  /// computation of the expression, such as n++.
8979  UK_ModAsSideEffect,
8980 
8981  UK_Count = UK_ModAsSideEffect + 1
8982  };
8983 
8984  struct Usage {
8985  Usage() : Use(nullptr), Seq() {}
8986  Expr *Use;
8987  SequenceTree::Seq Seq;
8988  };
8989 
8990  struct UsageInfo {
8991  UsageInfo() : Diagnosed(false) {}
8992  Usage Uses[UK_Count];
8993  /// Have we issued a diagnostic for this variable already?
8994  bool Diagnosed;
8995  };
8996  typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
8997 
8998  Sema &SemaRef;
8999  /// Sequenced regions within the expression.
9000  SequenceTree Tree;
9001  /// Declaration modifications and references which we have seen.
9002  UsageInfoMap UsageMap;
9003  /// The region we are currently within.
9004  SequenceTree::Seq Region;
9005  /// Filled in with declarations which were modified as a side-effect
9006  /// (that is, post-increment operations).
9007  SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
9008  /// Expressions to check later. We defer checking these to reduce
9009  /// stack usage.
9010  SmallVectorImpl<Expr *> &WorkList;
9011 
9012  /// RAII object wrapping the visitation of a sequenced subexpression of an
9013  /// expression. At the end of this process, the side-effects of the evaluation
9014  /// become sequenced with respect to the value computation of the result, so
9015  /// we downgrade any UK_ModAsSideEffect within the evaluation to
9016  /// UK_ModAsValue.
9017  struct SequencedSubexpression {
9018  SequencedSubexpression(SequenceChecker &Self)
9019  : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
9020  Self.ModAsSideEffect = &ModAsSideEffect;
9021  }
9022  ~SequencedSubexpression() {
9023  for (auto &M : llvm::reverse(ModAsSideEffect)) {
9024  UsageInfo &U = Self.UsageMap[M.first];
9025  auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
9026  Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
9027  SideEffectUsage = M.second;
9028  }
9029  Self.ModAsSideEffect = OldModAsSideEffect;
9030  }
9031 
9032  SequenceChecker &Self;
9033  SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
9034  SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
9035  };
9036 
9037  /// RAII object wrapping the visitation of a subexpression which we might
9038  /// choose to evaluate as a constant. If any subexpression is evaluated and
9039  /// found to be non-constant, this allows us to suppress the evaluation of
9040  /// the outer expression.
9041  class EvaluationTracker {
9042  public:
9043  EvaluationTracker(SequenceChecker &Self)
9044  : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
9045  Self.EvalTracker = this;
9046  }
9047  ~EvaluationTracker() {
9048  Self.EvalTracker = Prev;
9049  if (Prev)
9050  Prev->EvalOK &= EvalOK;
9051  }
9052 
9053  bool evaluate(const Expr *E, bool &Result) {
9054  if (!EvalOK || E->isValueDependent())
9055  return false;
9056  EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
9057  return EvalOK;
9058  }
9059 
9060  private:
9061  SequenceChecker &Self;
9062  EvaluationTracker *Prev;
9063  bool EvalOK;
9064  } *EvalTracker;
9065 
9066  /// \brief Find the object which is produced by the specified expression,
9067  /// if any.
9068  Object getObject(Expr *E, bool Mod) const {
9069  E = E->IgnoreParenCasts();
9070  if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
9071  if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
9072  return getObject(UO->getSubExpr(), Mod);
9073  } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9074  if (BO->getOpcode() == BO_Comma)
9075  return getObject(BO->getRHS(), Mod);
9076  if (Mod && BO->isAssignmentOp())
9077  return getObject(BO->getLHS(), Mod);
9078  } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
9079  // FIXME: Check for more interesting cases, like "x.n = ++x.n".
9080  if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
9081  return ME->getMemberDecl();
9082  } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9083  // FIXME: If this is a reference, map through to its value.
9084  return DRE->getDecl();
9085  return nullptr;
9086  }
9087 
9088  /// \brief Note that an object was modified or used by an expression.
9089  void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
9090  Usage &U = UI.Uses[UK];
9091  if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
9092  if (UK == UK_ModAsSideEffect && ModAsSideEffect)
9093  ModAsSideEffect->push_back(std::make_pair(O, U));
9094  U.Use = Ref;
9095  U.Seq = Region;
9096  }
9097  }
9098  /// \brief Check whether a modification or use conflicts with a prior usage.
9099  void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
9100  bool IsModMod) {
9101  if (UI.Diagnosed)
9102  return;
9103 
9104  const Usage &U = UI.Uses[OtherKind];
9105  if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
9106  return;
9107 
9108  Expr *Mod = U.Use;
9109  Expr *ModOrUse = Ref;
9110  if (OtherKind == UK_Use)
9111  std::swap(Mod, ModOrUse);
9112 
9113  SemaRef.Diag(Mod->getExprLoc(),
9114  IsModMod ? diag::warn_unsequenced_mod_mod
9115  : diag::warn_unsequenced_mod_use)
9116  << O << SourceRange(ModOrUse->getExprLoc());
9117  UI.Diagnosed = true;
9118  }
9119 
9120  void notePreUse(Object O, Expr *Use) {
9121  UsageInfo &U = UsageMap[O];
9122  // Uses conflict with other modifications.
9123  checkUsage(O, U, Use, UK_ModAsValue, false);
9124  }
9125  void notePostUse(Object O, Expr *Use) {
9126  UsageInfo &U = UsageMap[O];
9127  checkUsage(O, U, Use, UK_ModAsSideEffect, false);
9128  addUsage(U, O, Use, UK_Use);
9129  }
9130 
9131  void notePreMod(Object O, Expr *Mod) {
9132  UsageInfo &U = UsageMap[O];
9133  // Modifications conflict with other modifications and with uses.
9134  checkUsage(O, U, Mod, UK_ModAsValue, true);
9135  checkUsage(O, U, Mod, UK_Use, false);
9136  }
9137  void notePostMod(Object O, Expr *Use, UsageKind UK) {
9138  UsageInfo &U = UsageMap[O];
9139  checkUsage(O, U, Use, UK_ModAsSideEffect, true);
9140  addUsage(U, O, Use, UK);
9141  }
9142 
9143 public:
9144  SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
9145  : Base(S.Context), SemaRef(S), Region(Tree.root()),
9146  ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
9147  Visit(E);
9148  }
9149 
9150  void VisitStmt(Stmt *S) {
9151  // Skip all statements which aren't expressions for now.
9152  }
9153 
9154  void VisitExpr(Expr *E) {
9155  // By default, just recurse to evaluated subexpressions.
9156  Base::VisitStmt(E);
9157  }
9158 
9159  void VisitCastExpr(CastExpr *E) {
9160  Object O = Object();
9161  if (E->getCastKind() == CK_LValueToRValue)
9162  O = getObject(E->getSubExpr(), false);
9163 
9164  if (O)
9165  notePreUse(O, E);
9166  VisitExpr(E);
9167  if (O)
9168  notePostUse(O, E);
9169  }
9170 
9171  void VisitBinComma(BinaryOperator *BO) {
9172  // C++11 [expr.comma]p1:
9173  // Every value computation and side effect associated with the left
9174  // expression is sequenced before every value computation and side
9175  // effect associated with the right expression.
9176  SequenceTree::Seq LHS = Tree.allocate(Region);
9177  SequenceTree::Seq RHS = Tree.allocate(Region);
9178  SequenceTree::Seq OldRegion = Region;
9179 
9180  {
9181  SequencedSubexpression SeqLHS(*this);
9182  Region = LHS;
9183  Visit(BO->getLHS());
9184  }
9185 
9186  Region = RHS;
9187  Visit(BO->getRHS());
9188 
9189  Region = OldRegion;
9190 
9191  // Forget that LHS and RHS are sequenced. They are both unsequenced
9192  // with respect to other stuff.
9193  Tree.merge(LHS);
9194  Tree.merge(RHS);
9195  }
9196 
9197  void VisitBinAssign(BinaryOperator *BO) {
9198  // The modification is sequenced after the value computation of the LHS
9199  // and RHS, so check it before inspecting the operands and update the
9200  // map afterwards.
9201  Object O = getObject(BO->getLHS(), true);
9202  if (!O)
9203  return VisitExpr(BO);
9204 
9205  notePreMod(O, BO);
9206 
9207  // C++11 [expr.ass]p7:
9208  // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
9209  // only once.
9210  //
9211  // Therefore, for a compound assignment operator, O is considered used
9212  // everywhere except within the evaluation of E1 itself.
9213  if (isa<CompoundAssignOperator>(BO))
9214  notePreUse(O, BO);
9215 
9216  Visit(BO->getLHS());
9217 
9218  if (isa<CompoundAssignOperator>(BO))
9219  notePostUse(O, BO);
9220 
9221  Visit(BO->getRHS());
9222 
9223  // C++11 [expr.ass]p1:
9224  // the assignment is sequenced [...] before the value computation of the
9225  // assignment expression.
9226  // C11 6.5.16/3 has no such rule.
9227  notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
9228  : UK_ModAsSideEffect);
9229  }
9230 
9231  void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
9232  VisitBinAssign(CAO);
9233  }
9234 
9235  void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
9236  void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
9237  void VisitUnaryPreIncDec(UnaryOperator *UO) {
9238  Object O = getObject(UO->getSubExpr(), true);
9239  if (!O)
9240  return VisitExpr(UO);
9241 
9242  notePreMod(O, UO);
9243  Visit(UO->getSubExpr());
9244  // C++11 [expr.pre.incr]p1:
9245  // the expression ++x is equivalent to x+=1
9246  notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
9247  : UK_ModAsSideEffect);
9248  }
9249 
9250  void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
9251  void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
9252  void VisitUnaryPostIncDec(UnaryOperator *UO) {
9253  Object O = getObject(UO->getSubExpr(), true);
9254  if (!O)
9255  return VisitExpr(UO);
9256 
9257  notePreMod(O, UO);
9258  Visit(UO->getSubExpr());
9259  notePostMod(O, UO, UK_ModAsSideEffect);
9260  }
9261 
9262  /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
9263  void VisitBinLOr(BinaryOperator *BO) {
9264  // The side-effects of the LHS of an '&&' are sequenced before the
9265  // value computation of the RHS, and hence before the value computation
9266  // of the '&&' itself, unless the LHS evaluates to zero. We treat them
9267  // as if they were unconditionally sequenced.
9268  EvaluationTracker Eval(*this);
9269  {
9270  SequencedSubexpression Sequenced(*this);
9271  Visit(BO->getLHS());
9272  }
9273 
9274  bool Result;
9275  if (Eval.evaluate(BO->getLHS(), Result)) {
9276  if (!Result)
9277  Visit(BO->getRHS());
9278  } else {
9279  // Check for unsequenced operations in the RHS, treating it as an
9280  // entirely separate evaluation.
9281  //
9282  // FIXME: If there are operations in the RHS which are unsequenced
9283  // with respect to operations outside the RHS, and those operations
9284  // are unconditionally evaluated, diagnose them.
9285  WorkList.push_back(BO->getRHS());
9286  }
9287  }
9288  void VisitBinLAnd(BinaryOperator *BO) {
9289  EvaluationTracker Eval(*this);
9290  {
9291  SequencedSubexpression Sequenced(*this);
9292  Visit(BO->getLHS());
9293  }
9294 
9295  bool Result;
9296  if (Eval.evaluate(BO->getLHS(), Result)) {
9297  if (Result)
9298  Visit(BO->getRHS());
9299  } else {
9300  WorkList.push_back(BO->getRHS());
9301  }
9302  }
9303 
9304  // Only visit the condition, unless we can be sure which subexpression will
9305  // be chosen.
9306  void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
9307  EvaluationTracker Eval(*this);
9308  {
9309  SequencedSubexpression Sequenced(*this);
9310  Visit(CO->getCond());
9311  }
9312 
9313  bool Result;
9314  if (Eval.evaluate(CO->getCond(), Result))
9315  Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
9316  else {
9317  WorkList.push_back(CO->getTrueExpr());
9318  WorkList.push_back(CO->getFalseExpr());
9319  }
9320  }
9321 
9322  void VisitCallExpr(CallExpr *CE) {
9323  // C++11 [intro.execution]p15:
9324  // When calling a function [...], every value computation and side effect
9325  // associated with any argument expression, or with the postfix expression
9326  // designating the called function, is sequenced before execution of every
9327  // expression or statement in the body of the function [and thus before
9328  // the value computation of its result].
9329  SequencedSubexpression Sequenced(*this);
9330  Base::VisitCallExpr(CE);
9331 
9332  // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
9333  }
9334 
9335  void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
9336  // This is a call, so all subexpressions are sequenced before the result.
9337  SequencedSubexpression Sequenced(*this);
9338 
9339  if (!CCE->isListInitialization())
9340  return VisitExpr(CCE);
9341 
9342  // In C++11, list initializations are sequenced.
9344  SequenceTree::Seq Parent = Region;
9345  for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
9346  E = CCE->arg_end();
9347  I != E; ++I) {
9348  Region = Tree.allocate(Parent);
9349  Elts.push_back(Region);
9350  Visit(*I);
9351  }
9352 
9353  // Forget that the initializers are sequenced.
9354  Region = Parent;
9355  for (unsigned I = 0; I < Elts.size(); ++I)
9356  Tree.merge(Elts[I]);
9357  }
9358 
9359  void VisitInitListExpr(InitListExpr *ILE) {
9360  if (!SemaRef.getLangOpts().CPlusPlus11)
9361  return VisitExpr(ILE);
9362 
9363  // In C++11, list initializations are sequenced.
9365  SequenceTree::Seq Parent = Region;
9366  for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
9367  Expr *E = ILE->getInit(I);
9368  if (!E) continue;
9369  Region = Tree.allocate(Parent);
9370  Elts.push_back(Region);
9371  Visit(E);
9372  }
9373 
9374  // Forget that the initializers are sequenced.
9375  Region = Parent;
9376  for (unsigned I = 0; I < Elts.size(); ++I)
9377  Tree.merge(Elts[I]);
9378  }
9379 };
9380 } // end anonymous namespace
9381 
9382 void Sema::CheckUnsequencedOperations(Expr *E) {
9383  SmallVector<Expr *, 8> WorkList;
9384  WorkList.push_back(E);
9385  while (!WorkList.empty()) {
9386  Expr *Item = WorkList.pop_back_val();
9387  SequenceChecker(*this, Item, WorkList);
9388  }
9389 }
9390 
9391 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
9392  bool IsConstexpr) {
9393  CheckImplicitConversions(E, CheckLoc);
9394  if (!E->isInstantiationDependent())
9395  CheckUnsequencedOperations(E);
9396  if (!IsConstexpr && !E->isValueDependent())
9397  CheckForIntOverflow(E);
9398 }
9399 
9400 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
9401  FieldDecl *BitField,
9402  Expr *Init) {
9403  (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
9404 }
9405 
9407  SourceLocation Loc) {
9408  if (!PType->isVariablyModifiedType())
9409  return;
9410  if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
9411  diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
9412  return;
9413  }
9414  if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
9415  diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
9416  return;
9417  }
9418  if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
9419  diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
9420  return;
9421  }
9422 
9423  const ArrayType *AT = S.Context.getAsArrayType(PType);
9424  if (!AT)
9425  return;
9426 
9427  if (AT->getSizeModifier() != ArrayType::Star) {
9429  return;
9430  }
9431 
9432  S.Diag(Loc, diag::err_array_star_in_function_definition);
9433 }
9434 
9435 /// CheckParmsForFunctionDef - Check that the parameters of the given
9436 /// function are appropriate for the definition of a function. This
9437 /// takes care of any checks that cannot be performed on the
9438 /// declaration itself, e.g., that the types of each of the function
9439 /// parameters are complete.
9441  bool CheckParameterNames) {
9442  bool HasInvalidParm = false;
9443  for (ParmVarDecl *Param : Parameters) {
9444  // C99 6.7.5.3p4: the parameters in a parameter type list in a
9445  // function declarator that is part of a function definition of
9446  // that function shall not have incomplete type.
9447  //
9448  // This is also C++ [dcl.fct]p6.
9449  if (!Param->isInvalidDecl() &&
9450  RequireCompleteType(Param->getLocation(), Param->getType(),
9451  diag::err_typecheck_decl_incomplete_type)) {
9452  Param->setInvalidDecl();
9453  HasInvalidParm = true;
9454  }
9455 
9456  // C99 6.9.1p5: If the declarator includes a parameter type list, the
9457  // declaration of each parameter shall include an identifier.
9458  if (CheckParameterNames &&
9459  Param->getIdentifier() == nullptr &&
9460  !Param->isImplicit() &&
9461  !getLangOpts().CPlusPlus)
9462  Diag(Param->getLocation(), diag::err_parameter_name_omitted);
9463 
9464  // C99 6.7.5.3p12:
9465  // If the function declarator is not part of a definition of that
9466  // function, parameters may have incomplete type and may use the [*]
9467  // notation in their sequences of declarator specifiers to specify
9468  // variable length array types.
9469  QualType PType = Param->getOriginalType();
9470  // FIXME: This diagnostic should point the '[*]' if source-location
9471  // information is added for it.
9472  diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
9473 
9474  // MSVC destroys objects passed by value in the callee. Therefore a
9475  // function definition which takes such a parameter must be able to call the
9476  // object's destructor. However, we don't perform any direct access check
9477  // on the dtor.
9478  if (getLangOpts().CPlusPlus && Context.getTargetInfo()
9479  .getCXXABI()
9481  if (!Param->isInvalidDecl()) {
9482  if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
9483  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
9484  if (!ClassDecl->isInvalidDecl() &&
9485  !ClassDecl->hasIrrelevantDestructor() &&
9486  !ClassDecl->isDependentContext()) {
9487  CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
9488  MarkFunctionReferenced(Param->getLocation(), Destructor);
9489  DiagnoseUseOfDecl(Destructor, Param->getLocation());
9490  }
9491  }
9492  }
9493  }
9494 
9495  // Parameters with the pass_object_size attribute only need to be marked
9496  // constant at function definitions. Because we lack information about
9497  // whether we're on a declaration or definition when we're instantiating the
9498  // attribute, we need to check for constness here.
9499  if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
9500  if (!Param->getType().isConstQualified())
9501  Diag(Param->getLocation(), diag::err_attribute_pointers_only)
9502  << Attr->getSpelling() << 1;
9503  }
9504 
9505  return HasInvalidParm;
9506 }
9507 
9508 /// CheckCastAlign - Implements -Wcast-align, which warns when a
9509 /// pointer cast increases the alignment requirements.
9510 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
9511  // This is actually a lot of work to potentially be doing on every
9512  // cast; don't do it if we're ignoring -Wcast_align (as is the default).
9513  if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
9514  return;
9515 
9516  // Ignore dependent types.
9517  if (T->isDependentType() || Op->getType()->isDependentType())
9518  return;
9519 
9520  // Require that the destination be a pointer type.
9521  const PointerType *DestPtr = T->getAs<PointerType>();
9522  if (!DestPtr) return;
9523 
9524  // If the destination has alignment 1, we're done.
9525  QualType DestPointee = DestPtr->getPointeeType();
9526  if (DestPointee->isIncompleteType()) return;
9527  CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
9528  if (DestAlign.isOne()) return;
9529 
9530  // Require that the source be a pointer type.
9531  const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
9532  if (!SrcPtr) return;
9533  QualType SrcPointee = SrcPtr->getPointeeType();
9534 
9535  // Whitelist casts from cv void*. We already implicitly
9536  // whitelisted casts to cv void*, since they have alignment 1.
9537  // Also whitelist casts involving incomplete types, which implicitly
9538  // includes 'void'.
9539  if (SrcPointee->isIncompleteType()) return;
9540 
9541  CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
9542  if (SrcAlign >= DestAlign) return;
9543 
9544  Diag(TRange.getBegin(), diag::warn_cast_align)
9545  << Op->getType() << T
9546  << static_cast<unsigned>(SrcAlign.getQuantity())
9547  << static_cast<unsigned>(DestAlign.getQuantity())
9548  << TRange << Op->getSourceRange();
9549 }
9550 
9551 /// \brief Check whether this array fits the idiom of a size-one tail padded
9552 /// array member of a struct.
9553 ///
9554 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
9555 /// commonly used to emulate flexible arrays in C89 code.
9556 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
9557  const NamedDecl *ND) {
9558  if (Size != 1 || !ND) return false;
9559 
9560  const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
9561  if (!FD) return false;
9562 
9563  // Don't consider sizes resulting from macro expansions or template argument
9564  // substitution to form C89 tail-padded arrays.
9565 
9566  TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
9567  while (TInfo) {
9568  TypeLoc TL = TInfo->getTypeLoc();
9569  // Look through typedefs.
9570  if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
9571  const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
9572  TInfo = TDL->getTypeSourceInfo();
9573  continue;
9574  }
9576  const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
9577  if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
9578  return false;
9579  }
9580  break;
9581  }
9582 
9583  const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
9584  if (!RD) return false;
9585  if (RD->isUnion()) return false;
9586  if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
9587  if (!CRD->isStandardLayout()) return false;
9588  }
9589 
9590  // See if this is the last field decl in the record.
9591  const Decl *D = FD;
9592  while ((D = D->getNextDeclInContext()))
9593  if (isa<FieldDecl>(D))
9594  return false;
9595  return true;
9596 }
9597 
9598 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
9599  const ArraySubscriptExpr *ASE,
9600  bool AllowOnePastEnd, bool IndexNegated) {
9601  IndexExpr = IndexExpr->IgnoreParenImpCasts();
9602  if (IndexExpr->isValueDependent())
9603  return;
9604 
9605  const Type *EffectiveType =
9606  BaseExpr->getType()->getPointeeOrArrayElementType();
9607  BaseExpr = BaseExpr->IgnoreParenCasts();
9608  const ConstantArrayType *ArrayTy =
9609  Context.getAsConstantArrayType(BaseExpr->getType());
9610  if (!ArrayTy)
9611  return;
9612 
9613  llvm::APSInt index;
9614  if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
9615  return;
9616  if (IndexNegated)
9617  index = -index;
9618 
9619  const NamedDecl *ND = nullptr;
9620  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
9621  ND = dyn_cast<NamedDecl>(DRE->getDecl());
9622  if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
9623  ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
9624 
9625  if (index.isUnsigned() || !index.isNegative()) {
9626  llvm::APInt size = ArrayTy->getSize();
9627  if (!size.isStrictlyPositive())
9628  return;
9629 
9630  const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
9631  if (BaseType != EffectiveType) {
9632  // Make sure we're comparing apples to apples when comparing index to size
9633  uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
9634  uint64_t array_typesize = Context.getTypeSize(BaseType);
9635  // Handle ptrarith_typesize being zero, such as when casting to void*
9636  if (!ptrarith_typesize) ptrarith_typesize = 1;
9637  if (ptrarith_typesize != array_typesize) {
9638  // There's a cast to a different size type involved
9639  uint64_t ratio = array_typesize / ptrarith_typesize;
9640  // TODO: Be smarter about handling cases where array_typesize is not a
9641  // multiple of ptrarith_typesize
9642  if (ptrarith_typesize * ratio == array_typesize)
9643  size *= llvm::APInt(size.getBitWidth(), ratio);
9644  }
9645  }
9646 
9647  if (size.getBitWidth() > index.getBitWidth())
9648  index = index.zext(size.getBitWidth());
9649  else if (size.getBitWidth() < index.getBitWidth())
9650  size = size.zext(index.getBitWidth());
9651 
9652  // For array subscripting the index must be less than size, but for pointer
9653  // arithmetic also allow the index (offset) to be equal to size since
9654  // computing the next address after the end of the array is legal and
9655  // commonly done e.g. in C++ iterators and range-based for loops.
9656  if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
9657  return;
9658 
9659  // Also don't warn for arrays of size 1 which are members of some
9660  // structure. These are often used to approximate flexible arrays in C89
9661  // code.
9662  if (IsTailPaddedMemberArray(*this, size, ND))
9663  return;
9664 
9665  // Suppress the warning if the subscript expression (as identified by the
9666  // ']' location) and the index expression are both from macro expansions
9667  // within a system header.
9668  if (ASE) {
9669  SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
9670  ASE->getRBracketLoc());
9671  if (SourceMgr.isInSystemHeader(RBracketLoc)) {
9672  SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
9673  IndexExpr->getLocStart());
9674  if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
9675  return;
9676  }
9677  }
9678 
9679  unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
9680  if (ASE)
9681  DiagID = diag::warn_array_index_exceeds_bounds;
9682 
9683  DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
9684  PDiag(DiagID) << index.toString(10, true)
9685  << size.toString(10, true)
9686  << (unsigned)size.getLimitedValue(~0U)
9687  << IndexExpr->getSourceRange());
9688  } else {
9689  unsigned DiagID = diag::warn_array_index_precedes_bounds;
9690  if (!ASE) {
9691  DiagID = diag::warn_ptr_arith_precedes_bounds;
9692  if (index.isNegative()) index = -index;
9693  }
9694 
9695  DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
9696  PDiag(DiagID) << index.toString(10, true)
9697  << IndexExpr->getSourceRange());
9698  }
9699 
9700  if (!ND) {
9701  // Try harder to find a NamedDecl to point at in the note.
9702  while (const ArraySubscriptExpr *ASE =
9703  dyn_cast<ArraySubscriptExpr>(BaseExpr))
9704  BaseExpr = ASE->getBase()->IgnoreParenCasts();
9705  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
9706  ND = dyn_cast<NamedDecl>(DRE->getDecl());
9707  if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
9708  ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
9709  }
9710 
9711  if (ND)
9712  DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
9713  PDiag(diag::note_array_index_out_of_bounds)
9714  << ND->getDeclName());
9715 }
9716 
9717 void Sema::CheckArrayAccess(const Expr *expr) {
9718  int AllowOnePastEnd = 0;
9719  while (expr) {
9720  expr = expr->IgnoreParenImpCasts();
9721  switch (expr->getStmtClass()) {
9722  case Stmt::ArraySubscriptExprClass: {
9723  const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
9724  CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
9725  AllowOnePastEnd > 0);
9726  return;
9727  }
9728  case Stmt::OMPArraySectionExprClass: {
9729  const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
9730  if (ASE->getLowerBound())
9731  CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
9732  /*ASE=*/nullptr, AllowOnePastEnd > 0);
9733  return;
9734  }
9735  case Stmt::UnaryOperatorClass: {
9736  // Only unwrap the * and & unary operators
9737  const UnaryOperator *UO = cast<UnaryOperator>(expr);
9738  expr = UO->getSubExpr();
9739  switch (UO->getOpcode()) {
9740  case UO_AddrOf:
9741  AllowOnePastEnd++;
9742  break;
9743  case UO_Deref:
9744  AllowOnePastEnd--;
9745  break;
9746  default:
9747  return;
9748  }
9749  break;
9750  }
9751  case Stmt::ConditionalOperatorClass: {
9752  const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
9753  if (const Expr *lhs = cond->getLHS())
9754  CheckArrayAccess(lhs);
9755  if (const Expr *rhs = cond->getRHS())
9756  CheckArrayAccess(rhs);
9757  return;
9758  }
9759  default:
9760  return;
9761  }
9762  }
9763 }
9764 
9765 //===--- CHECK: Objective-C retain cycles ----------------------------------//
9766 
9767 namespace {
9768  struct RetainCycleOwner {
9769  RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
9770  VarDecl *Variable;
9771  SourceRange Range;
9772  SourceLocation Loc;
9773  bool Indirect;
9774 
9775  void setLocsFrom(Expr *e) {
9776  Loc = e->getExprLoc();
9777  Range = e->getSourceRange();
9778  }
9779  };
9780 } // end anonymous namespace
9781 
9782 /// Consider whether capturing the given variable can possibly lead to
9783 /// a retain cycle.
9784 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
9785  // In ARC, it's captured strongly iff the variable has __strong
9786  // lifetime. In MRR, it's captured strongly if the variable is
9787  // __block and has an appropriate type.
9789  return false;
9790 
9791  owner.Variable = var;
9792  if (ref)
9793  owner.setLocsFrom(ref);
9794  return true;
9795 }
9796 
9797 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
9798  while (true) {
9799  e = e->IgnoreParens();
9800  if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
9801  switch (cast->getCastKind()) {
9802  case CK_BitCast:
9803  case CK_LValueBitCast:
9804  case CK_LValueToRValue:
9805  case CK_ARCReclaimReturnedObject:
9806  e = cast->getSubExpr();
9807  continue;
9808 
9809  default:
9810  return false;
9811  }
9812  }
9813 
9814  if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
9815  ObjCIvarDecl *ivar = ref->getDecl();
9817  return false;
9818 
9819  // Try to find a retain cycle in the base.
9820  if (!findRetainCycleOwner(S, ref->getBase(), owner))
9821  return false;
9822 
9823  if (ref->isFreeIvar()) owner.setLocsFrom(ref);
9824  owner.Indirect = true;
9825  return true;
9826  }
9827 
9828  if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
9829  VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
9830  if (!var) return false;
9831  return considerVariable(var, ref, owner);
9832  }
9833 
9834  if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
9835  if (member->isArrow()) return false;
9836 
9837  // Don't count this as an indirect ownership.
9838  e = member->getBase();
9839  continue;
9840  }
9841 
9842  if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
9843  // Only pay attention to pseudo-objects on property references.
9844  ObjCPropertyRefExpr *pre
9845  = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
9846  ->IgnoreParens());
9847  if (!pre) return false;
9848  if (pre->isImplicitProperty()) return false;
9849  ObjCPropertyDecl *property = pre->getExplicitProperty();
9850  if (!property->isRetaining() &&
9851  !(property->getPropertyIvarDecl() &&
9852  property->getPropertyIvarDecl()->getType()
9853  .getObjCLifetime() == Qualifiers::OCL_Strong))
9854  return false;
9855 
9856  owner.Indirect = true;
9857  if (pre->isSuperReceiver()) {
9858  owner.Variable = S.getCurMethodDecl()->getSelfDecl();
9859  if (!owner.Variable)
9860  return false;
9861  owner.Loc = pre->getLocation();
9862  owner.Range = pre->getSourceRange();
9863  return true;
9864  }
9865  e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
9866  ->getSourceExpr());
9867  continue;
9868  }
9869 
9870  // Array ivars?
9871 
9872  return false;
9873  }
9874 }
9875 
9876 namespace {
9877  struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
9878  FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
9879  : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
9880  Context(Context), Variable(variable), Capturer(nullptr),
9881  VarWillBeReased(false) {}
9883  VarDecl *Variable;
9884  Expr *Capturer;
9885  bool VarWillBeReased;
9886 
9887  void VisitDeclRefExpr(DeclRefExpr *ref) {
9888  if (ref->getDecl() == Variable && !Capturer)
9889  Capturer = ref;
9890  }
9891 
9892  void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
9893  if (Capturer) return;
9894  Visit(ref->getBase());
9895  if (Capturer && ref->isFreeIvar())
9896  Capturer = ref;
9897  }
9898 
9899  void VisitBlockExpr(BlockExpr *block) {
9900  // Look inside nested blocks
9901  if (block->getBlockDecl()->capturesVariable(Variable))
9902  Visit(block->getBlockDecl()->getBody());
9903  }
9904 
9905  void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
9906  if (Capturer) return;
9907  if (OVE->getSourceExpr())
9908  Visit(OVE->getSourceExpr());
9909  }
9910  void VisitBinaryOperator(BinaryOperator *BinOp) {
9911  if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
9912  return;
9913  Expr *LHS = BinOp->getLHS();
9914  if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
9915  if (DRE->getDecl() != Variable)
9916  return;
9917  if (Expr *RHS = BinOp->getRHS()) {
9918  RHS = RHS->IgnoreParenCasts();
9919  llvm::APSInt Value;
9920  VarWillBeReased =
9921  (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
9922  }
9923  }
9924  }
9925  };
9926 } // end anonymous namespace
9927 
9928 /// Check whether the given argument is a block which captures a
9929 /// variable.
9930 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
9931  assert(owner.Variable && owner.Loc.isValid());
9932 
9933  e = e->IgnoreParenCasts();
9934 
9935  // Look through [^{...} copy] and Block_copy(^{...}).
9936  if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
9937  Selector Cmd = ME->getSelector();
9938  if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
9939  e = ME->getInstanceReceiver();
9940  if (!e)
9941  return nullptr;
9942  e = e->IgnoreParenCasts();
9943  }
9944  } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
9945  if (CE->getNumArgs() == 1) {
9946  FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
9947  if (Fn) {
9948  const IdentifierInfo *FnI = Fn->getIdentifier();
9949  if (FnI && FnI->isStr("_Block_copy")) {
9950  e = CE->getArg(0)->IgnoreParenCasts();
9951  }
9952  }
9953  }
9954  }
9955 
9956  BlockExpr *block = dyn_cast<BlockExpr>(e);
9957  if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
9958  return nullptr;
9959 
9960  FindCaptureVisitor visitor(S.Context, owner.Variable);
9961  visitor.Visit(block->getBlockDecl()->getBody());
9962  return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
9963 }
9964 
9965 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
9966  RetainCycleOwner &owner) {
9967  assert(capturer);
9968  assert(owner.Variable && owner.Loc.isValid());
9969 
9970  S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
9971  << owner.Variable << capturer->getSourceRange();
9972  S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
9973  << owner.Indirect << owner.Range;
9974 }
9975 
9976 /// Check for a keyword selector that starts with the word 'add' or
9977 /// 'set'.
9978 static bool isSetterLikeSelector(Selector sel) {
9979  if (sel.isUnarySelector()) return false;
9980 
9981  StringRef str = sel.getNameForSlot(0);
9982  while (!str.empty() && str.front() == '_') str = str.substr(1);
9983  if (str.startswith("set"))
9984  str = str.substr(3);
9985  else if (str.startswith("add")) {
9986  // Specially whitelist 'addOperationWithBlock:'.
9987  if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
9988  return false;
9989  str = str.substr(3);
9990  }
9991  else
9992  return false;
9993 
9994  if (str.empty()) return true;
9995  return !isLowercase(str.front());
9996 }
9997 
9998 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
9999  ObjCMessageExpr *Message) {
10000  bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
10001  Message->getReceiverInterface(),
10003  if (!IsMutableArray) {
10004  return None;
10005  }
10006 
10007  Selector Sel = Message->getSelector();
10008 
10009  Optional<NSAPI::NSArrayMethodKind> MKOpt =
10010  S.NSAPIObj->getNSArrayMethodKind(Sel);
10011  if (!MKOpt) {
10012  return None;
10013  }
10014 
10015  NSAPI::NSArrayMethodKind MK = *MKOpt;
10016 
10017  switch (MK) {
10021  return 0;
10023  return 1;
10024 
10025  default:
10026  return None;
10027  }
10028 
10029  return None;
10030 }
10031 
10032 static
10034  ObjCMessageExpr *Message) {
10035  bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
10036  Message->getReceiverInterface(),
10038  if (!IsMutableDictionary) {
10039  return None;
10040  }
10041 
10042  Selector Sel = Message->getSelector();
10043 
10044  Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
10045  S.NSAPIObj->getNSDictionaryMethodKind(Sel);
10046  if (!MKOpt) {
10047  return None;
10048  }
10049 
10050  NSAPI::NSDictionaryMethodKind MK = *MKOpt;
10051 
10052  switch (MK) {
10056  return 0;
10057 
10058  default:
10059  return None;
10060  }
10061 
10062  return None;
10063 }
10064 
10065 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
10066  bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
10067  Message->getReceiverInterface(),
10069 
10070  bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
10071  Message->getReceiverInterface(),
10073  if (!IsMutableSet && !IsMutableOrderedSet) {
10074  return None;
10075  }
10076 
10077  Selector Sel = Message->getSelector();
10078 
10079  Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
10080  if (!MKOpt) {
10081  return None;
10082  }
10083 
10084  NSAPI::NSSetMethodKind MK = *MKOpt;
10085 
10086  switch (MK) {
10091  return 0;
10093  return 1;
10094  }
10095 
10096  return None;
10097 }
10098 
10099 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
10100  if (!Message->isInstanceMessage()) {
10101  return;
10102  }
10103 
10104  Optional<int> ArgOpt;
10105 
10106  if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
10107  !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
10108  !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
10109  return;
10110  }
10111 
10112  int ArgIndex = *ArgOpt;
10113 
10114  Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
10115  if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
10116  Arg = OE->getSourceExpr()->IgnoreImpCasts();
10117  }
10118 
10119  if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
10120  if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
10121  if (ArgRE->isObjCSelfExpr()) {
10122  Diag(Message->getSourceRange().getBegin(),
10123  diag::warn_objc_circular_container)
10124  << ArgRE->getDecl()->getName() << StringRef("super");
10125  }
10126  }
10127  } else {
10128  Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
10129 
10130  if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
10131  Receiver = OE->getSourceExpr()->IgnoreImpCasts();
10132  }
10133 
10134  if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
10135  if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
10136  if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
10137  ValueDecl *Decl = ReceiverRE->getDecl();
10138  Diag(Message->getSourceRange().getBegin(),
10139  diag::warn_objc_circular_container)
10140  << Decl->getName() << Decl->getName();
10141  if (!ArgRE->isObjCSelfExpr()) {
10142  Diag(Decl->getLocation(),
10143  diag::note_objc_circular_container_declared_here)
10144  << Decl->getName();
10145  }
10146  }
10147  }
10148  } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
10149  if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
10150  if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
10151  ObjCIvarDecl *Decl = IvarRE->getDecl();
10152  Diag(Message->getSourceRange().getBegin(),
10153  diag::warn_objc_circular_container)
10154  << Decl->getName() << Decl->getName();
10155  Diag(Decl->getLocation(),
10156  diag::note_objc_circular_container_declared_here)
10157  << Decl->getName();
10158  }
10159  }
10160  }
10161  }
10162 }
10163 
10164 /// Check a message send to see if it's likely to cause a retain cycle.
10166  // Only check instance methods whose selector looks like a setter.
10167  if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
10168  return;
10169 
10170  // Try to find a variable that the receiver is strongly owned by.
10171  RetainCycleOwner owner;
10173  if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
10174  return;
10175  } else {
10177  owner.Variable = getCurMethodDecl()->getSelfDecl();
10178  owner.Loc = msg->getSuperLoc();
10179  owner.Range = msg->getSuperLoc();
10180  }
10181 
10182  // Check whether the receiver is captured by any of the arguments.
10183  for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
10184  if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
10185  return diagnoseRetainCycle(*this, capturer, owner);
10186 }
10187 
10188 /// Check a property assign to see if it's likely to cause a retain cycle.
10189 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
10190  RetainCycleOwner owner;
10191  if (!findRetainCycleOwner(*this, receiver, owner))
10192  return;
10193 
10194  if (Expr *capturer = findCapturingExpr(*this, argument, owner))
10195  diagnoseRetainCycle(*this, capturer, owner);
10196 }
10197 
10199  RetainCycleOwner Owner;
10200  if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
10201  return;
10202 
10203  // Because we don't have an expression for the variable, we have to set the
10204  // location explicitly here.
10205  Owner.Loc = Var->getLocation();
10206  Owner.Range = Var->getSourceRange();
10207 
10208  if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
10209  diagnoseRetainCycle(*this, Capturer, Owner);
10210 }
10211 
10213  Expr *RHS, bool isProperty) {
10214  // Check if RHS is an Objective-C object literal, which also can get
10215  // immediately zapped in a weak reference. Note that we explicitly
10216  // allow ObjCStringLiterals, since those are designed to never really die.
10217  RHS = RHS->IgnoreParenImpCasts();
10218 
10219  // This enum needs to match with the 'select' in
10220  // warn_objc_arc_literal_assign (off-by-1).
10222  if (Kind == Sema::LK_String || Kind == Sema::LK_None)
10223  return false;
10224 
10225  S.Diag(Loc, diag::warn_arc_literal_assign)
10226  << (unsigned) Kind
10227  << (isProperty ? 0 : 1)
10228  << RHS->getSourceRange();
10229 
10230  return true;
10231 }
10232 
10235  Expr *RHS, bool isProperty) {
10236  // Strip off any implicit cast added to get to the one ARC-specific.
10237  while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
10238  if (cast->getCastKind() == CK_ARCConsumeObject) {
10239  S.Diag(Loc, diag::warn_arc_retained_assign)
10240  << (LT == Qualifiers::OCL_ExplicitNone)
10241  << (isProperty ? 0 : 1)
10242  << RHS->getSourceRange();
10243  return true;
10244  }
10245  RHS = cast->getSubExpr();
10246  }
10247 
10248  if (LT == Qualifiers::OCL_Weak &&
10249  checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
10250  return true;
10251 
10252  return false;
10253 }
10254 
10256  QualType LHS, Expr *RHS) {
10258 
10260  return false;
10261 
10262  if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
10263  return true;
10264 
10265  return false;
10266 }
10267 
10269  Expr *LHS, Expr *RHS) {
10270  QualType LHSType;
10271  // PropertyRef on LHS type need be directly obtained from
10272  // its declaration as it has a PseudoType.
10273  ObjCPropertyRefExpr *PRE
10274  = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
10275  if (PRE && !PRE->isImplicitProperty()) {
10276  const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
10277  if (PD)
10278  LHSType = PD->getType();
10279  }
10280 
10281  if (LHSType.isNull())
10282  LHSType = LHS->getType();
10283 
10285 
10286  if (LT == Qualifiers::OCL_Weak) {
10287  if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
10288  getCurFunction()->markSafeWeakUse(LHS);
10289  }
10290 
10291  if (checkUnsafeAssigns(Loc, LHSType, RHS))
10292  return;
10293 
10294  // FIXME. Check for other life times.
10295  if (LT != Qualifiers::OCL_None)
10296  return;
10297 
10298  if (PRE) {
10299  if (PRE->isImplicitProperty())
10300  return;
10301  const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
10302  if (!PD)
10303  return;
10304 
10305  unsigned Attributes = PD->getPropertyAttributes();
10306  if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
10307  // when 'assign' attribute was not explicitly specified
10308  // by user, ignore it and rely on property type itself
10309  // for lifetime info.
10310  unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
10311  if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
10312  LHSType->isObjCRetainableType())
10313  return;
10314 
10315  while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
10316  if (cast->getCastKind() == CK_ARCConsumeObject) {
10317  Diag(Loc, diag::warn_arc_retained_property_assign)
10318  << RHS->getSourceRange();
10319  return;
10320  }
10321  RHS = cast->getSubExpr();
10322  }
10323  }
10324  else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
10325  if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
10326  return;
10327  }
10328  }
10329 }
10330 
10331 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
10332 
10333 namespace {
10334 bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
10335  SourceLocation StmtLoc,
10336  const NullStmt *Body) {
10337  // Do not warn if the body is a macro that expands to nothing, e.g:
10338  //
10339  // #define CALL(x)
10340  // if (condition)
10341  // CALL(0);
10342  //
10343  if (Body->hasLeadingEmptyMacro())
10344  return false;
10345 
10346  // Get line numbers of statement and body.
10347  bool StmtLineInvalid;
10348  unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
10349  &StmtLineInvalid);
10350  if (StmtLineInvalid)
10351  return false;
10352 
10353  bool BodyLineInvalid;
10354  unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
10355  &BodyLineInvalid);
10356  if (BodyLineInvalid)
10357  return false;
10358 
10359  // Warn if null statement and body are on the same line.
10360  if (StmtLine != BodyLine)
10361  return false;
10362 
10363  return true;
10364 }
10365 } // end anonymous namespace
10366 
10368  const Stmt *Body,
10369  unsigned DiagID) {
10370  // Since this is a syntactic check, don't emit diagnostic for template
10371  // instantiations, this just adds noise.
10372  if (CurrentInstantiationScope)
10373  return;
10374 
10375  // The body should be a null statement.
10376  const NullStmt *NBody = dyn_cast<NullStmt>(Body);
10377  if (!NBody)
10378  return;
10379 
10380  // Do the usual checks.
10381  if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
10382  return;
10383 
10384  Diag(NBody->getSemiLoc(), DiagID);
10385  Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
10386 }
10387 
10389  const Stmt *PossibleBody) {
10390  assert(!CurrentInstantiationScope); // Ensured by caller
10391 
10392  SourceLocation StmtLoc;
10393  const Stmt *Body;
10394  unsigned DiagID;
10395  if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
10396  StmtLoc = FS->getRParenLoc();
10397  Body = FS->getBody();
10398  DiagID = diag::warn_empty_for_body;
10399  } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
10400  StmtLoc = WS->getCond()->getSourceRange().getEnd();
10401  Body = WS->getBody();
10402  DiagID = diag::warn_empty_while_body;
10403  } else
10404  return; // Neither `for' nor `while'.
10405 
10406  // The body should be a null statement.
10407  const NullStmt *NBody = dyn_cast<NullStmt>(Body);
10408  if (!NBody)
10409  return;
10410 
10411  // Skip expensive checks if diagnostic is disabled.
10412  if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
10413  return;
10414 
10415  // Do the usual checks.
10416  if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
10417  return;
10418 
10419  // `for(...);' and `while(...);' are popular idioms, so in order to keep
10420  // noise level low, emit diagnostics only if for/while is followed by a
10421  // CompoundStmt, e.g.:
10422  // for (int i = 0; i < n; i++);
10423  // {
10424  // a(i);
10425  // }
10426  // or if for/while is followed by a statement with more indentation
10427  // than for/while itself:
10428  // for (int i = 0; i < n; i++);
10429  // a(i);
10430  bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
10431  if (!ProbableTypo) {
10432  bool BodyColInvalid;
10433  unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
10434  PossibleBody->getLocStart(),
10435  &BodyColInvalid);
10436  if (BodyColInvalid)
10437  return;
10438 
10439  bool StmtColInvalid;
10440  unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
10441  S->getLocStart(),
10442  &StmtColInvalid);
10443  if (StmtColInvalid)
10444  return;
10445 
10446  if (BodyCol > StmtCol)
10447  ProbableTypo = true;
10448  }
10449 
10450  if (ProbableTypo) {
10451  Diag(NBody->getSemiLoc(), DiagID);
10452  Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
10453  }
10454 }
10455 
10456 //===--- CHECK: Warn on self move with std::move. -------------------------===//
10457 
10458 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
10459 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
10460  SourceLocation OpLoc) {
10461  if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
10462  return;
10463 
10464  if (!ActiveTemplateInstantiations.empty())
10465  return;
10466 
10467  // Strip parens and casts away.
10468  LHSExpr = LHSExpr->IgnoreParenImpCasts();
10469  RHSExpr = RHSExpr->IgnoreParenImpCasts();
10470 
10471  // Check for a call expression
10472  const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
10473  if (!CE || CE->getNumArgs() != 1)
10474  return;
10475 
10476  // Check for a call to std::move
10477  const FunctionDecl *FD = CE->getDirectCallee();
10478  if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
10479  !FD->getIdentifier()->isStr("move"))
10480  return;
10481 
10482  // Get argument from std::move
10483  RHSExpr = CE->getArg(0);
10484 
10485  const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
10486  const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
10487 
10488  // Two DeclRefExpr's, check that the decls are the same.
10489  if (LHSDeclRef && RHSDeclRef) {
10490  if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
10491  return;
10492  if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
10493  RHSDeclRef->getDecl()->getCanonicalDecl())
10494  return;
10495 
10496  Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
10497  << LHSExpr->getSourceRange()
10498  << RHSExpr->getSourceRange();
10499  return;
10500  }
10501 
10502  // Member variables require a different approach to check for self moves.
10503  // MemberExpr's are the same if every nested MemberExpr refers to the same
10504  // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
10505  // the base Expr's are CXXThisExpr's.
10506  const Expr *LHSBase = LHSExpr;
10507  const Expr *RHSBase = RHSExpr;
10508  const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
10509  const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
10510  if (!LHSME || !RHSME)
10511  return;
10512 
10513  while (LHSME && RHSME) {
10514  if (LHSME->getMemberDecl()->getCanonicalDecl() !=
10515  RHSME->getMemberDecl()->getCanonicalDecl())
10516  return;
10517 
10518  LHSBase = LHSME->getBase();
10519  RHSBase = RHSME->getBase();
10520  LHSME = dyn_cast<MemberExpr>(LHSBase);
10521  RHSME = dyn_cast<MemberExpr>(RHSBase);
10522  }
10523 
10524  LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
10525  RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
10526  if (LHSDeclRef && RHSDeclRef) {
10527  if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
10528  return;
10529  if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
10530  RHSDeclRef->getDecl()->getCanonicalDecl())
10531  return;
10532 
10533  Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
10534  << LHSExpr->getSourceRange()
10535  << RHSExpr->getSourceRange();
10536  return;
10537  }
10538 
10539  if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
10540  Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
10541  << LHSExpr->getSourceRange()
10542  << RHSExpr->getSourceRange();
10543 }
10544 
10545 //===--- Layout compatibility ----------------------------------------------//
10546 
10547 namespace {
10548 
10549 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
10550 
10551 /// \brief Check if two enumeration types are layout-compatible.
10552 bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
10553  // C++11 [dcl.enum] p8:
10554  // Two enumeration types are layout-compatible if they have the same
10555  // underlying type.
10556  return ED1->isComplete() && ED2->isComplete() &&
10557  C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
10558 }
10559 
10560 /// \brief Check if two fields are layout-compatible.
10561 bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
10562  if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
10563  return false;
10564 
10565  if (Field1->isBitField() != Field2->isBitField())
10566  return false;
10567 
10568  if (Field1->isBitField()) {
10569  // Make sure that the bit-fields are the same length.
10570  unsigned Bits1 = Field1->getBitWidthValue(C);
10571  unsigned Bits2 = Field2->getBitWidthValue(C);
10572 
10573  if (Bits1 != Bits2)
10574  return false;
10575  }
10576 
10577  return true;
10578 }
10579 
10580 /// \brief Check if two standard-layout structs are layout-compatible.
10581 /// (C++11 [class.mem] p17)
10582 bool isLayoutCompatibleStruct(ASTContext &C,
10583  RecordDecl *RD1,
10584  RecordDecl *RD2) {
10585  // If both records are C++ classes, check that base classes match.
10586  if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
10587  // If one of records is a CXXRecordDecl we are in C++ mode,
10588  // thus the other one is a CXXRecordDecl, too.
10589  const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
10590  // Check number of base classes.
10591  if (D1CXX->getNumBases() != D2CXX->getNumBases())
10592  return false;
10593 
10594  // Check the base classes.
10596  Base1 = D1CXX->bases_begin(),
10597  BaseEnd1 = D1CXX->bases_end(),
10598  Base2 = D2CXX->bases_begin();
10599  Base1 != BaseEnd1;
10600  ++Base1, ++Base2) {
10601  if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
10602  return false;
10603  }
10604  } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
10605  // If only RD2 is a C++ class, it should have zero base classes.
10606  if (D2CXX->getNumBases() > 0)
10607  return false;
10608  }
10609 
10610  // Check the fields.
10611  RecordDecl::field_iterator Field2 = RD2->field_begin(),
10612  Field2End = RD2->field_end(),
10613  Field1 = RD1->field_begin(),
10614  Field1End = RD1->field_end();
10615  for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
10616  if (!isLayoutCompatible(C, *Field1, *Field2))
10617  return false;
10618  }
10619  if (Field1 != Field1End || Field2 != Field2End)
10620  return false;
10621 
10622  return true;
10623 }
10624 
10625 /// \brief Check if two standard-layout unions are layout-compatible.
10626 /// (C++11 [class.mem] p18)
10627 bool isLayoutCompatibleUnion(ASTContext &C,
10628  RecordDecl *RD1,
10629  RecordDecl *RD2) {
10630  llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
10631  for (auto *Field2 : RD2->fields())
10632  UnmatchedFields.insert(Field2);
10633 
10634  for (auto *Field1 : RD1->fields()) {
10636  I = UnmatchedFields.begin(),
10637  E = UnmatchedFields.end();
10638 
10639  for ( ; I != E; ++I) {
10640  if (isLayoutCompatible(C, Field1, *I)) {
10641  bool Result = UnmatchedFields.erase(*I);
10642  (void) Result;
10643  assert(Result);
10644  break;
10645  }
10646  }
10647  if (I == E)
10648  return false;
10649  }
10650 
10651  return UnmatchedFields.empty();
10652 }
10653 
10654 bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
10655  if (RD1->isUnion() != RD2->isUnion())
10656  return false;
10657 
10658  if (RD1->isUnion())
10659  return isLayoutCompatibleUnion(C, RD1, RD2);
10660  else
10661  return isLayoutCompatibleStruct(C, RD1, RD2);
10662 }
10663 
10664 /// \brief Check if two types are layout-compatible in C++11 sense.
10665 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
10666  if (T1.isNull() || T2.isNull())
10667  return false;
10668 
10669  // C++11 [basic.types] p11:
10670  // If two types T1 and T2 are the same type, then T1 and T2 are
10671  // layout-compatible types.
10672  if (C.hasSameType(T1, T2))
10673  return true;
10674 
10677 
10678  const Type::TypeClass TC1 = T1->getTypeClass();
10679  const Type::TypeClass TC2 = T2->getTypeClass();
10680 
10681  if (TC1 != TC2)
10682  return false;
10683 
10684  if (TC1 == Type::Enum) {
10685  return isLayoutCompatible(C,
10686  cast<EnumType>(T1)->getDecl(),
10687  cast<EnumType>(T2)->getDecl());
10688  } else if (TC1 == Type::Record) {
10689  if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
10690  return false;
10691 
10692  return isLayoutCompatible(C,
10693  cast<RecordType>(T1)->getDecl(),
10694  cast<RecordType>(T2)->getDecl());
10695  }
10696 
10697  return false;
10698 }
10699 } // end anonymous namespace
10700 
10701 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
10702 
10703 namespace {
10704 /// \brief Given a type tag expression find the type tag itself.
10705 ///
10706 /// \param TypeExpr Type tag expression, as it appears in user's code.
10707 ///
10708 /// \param VD Declaration of an identifier that appears in a type tag.
10709 ///
10710 /// \param MagicValue Type tag magic value.
10711 bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
10712  const ValueDecl **VD, uint64_t *MagicValue) {
10713  while(true) {
10714  if (!TypeExpr)
10715  return false;
10716 
10717  TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
10718 
10719  switch (TypeExpr->getStmtClass()) {
10720  case Stmt::UnaryOperatorClass: {
10721  const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
10722  if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
10723  TypeExpr = UO->getSubExpr();
10724  continue;
10725  }
10726  return false;
10727  }
10728 
10729  case Stmt::DeclRefExprClass: {
10730  const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
10731  *VD = DRE->getDecl();
10732  return true;
10733  }
10734 
10735  case Stmt::IntegerLiteralClass: {
10736  const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
10737  llvm::APInt MagicValueAPInt = IL->getValue();
10738  if (MagicValueAPInt.getActiveBits() <= 64) {
10739  *MagicValue = MagicValueAPInt.getZExtValue();
10740  return true;
10741  } else
10742  return false;
10743  }
10744 
10745  case Stmt::BinaryConditionalOperatorClass:
10746  case Stmt::ConditionalOperatorClass: {
10747  const AbstractConditionalOperator *ACO =
10748  cast<AbstractConditionalOperator>(TypeExpr);
10749  bool Result;
10750  if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
10751  if (Result)
10752  TypeExpr = ACO->getTrueExpr();
10753  else
10754  TypeExpr = ACO->getFalseExpr();
10755  continue;
10756  }
10757  return false;
10758  }
10759 
10760  case Stmt::BinaryOperatorClass: {
10761  const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
10762  if (BO->getOpcode() == BO_Comma) {
10763  TypeExpr = BO->getRHS();
10764  continue;
10765  }
10766  return false;
10767  }
10768 
10769  default:
10770  return false;
10771  }
10772  }
10773 }
10774 
10775 /// \brief Retrieve the C type corresponding to type tag TypeExpr.
10776 ///
10777 /// \param TypeExpr Expression that specifies a type tag.
10778 ///
10779 /// \param MagicValues Registered magic values.
10780 ///
10781 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
10782 /// kind.
10783 ///
10784 /// \param TypeInfo Information about the corresponding C type.
10785 ///
10786 /// \returns true if the corresponding C type was found.
10787 bool GetMatchingCType(
10788  const IdentifierInfo *ArgumentKind,
10789  const Expr *TypeExpr, const ASTContext &Ctx,
10790  const llvm::DenseMap<Sema::TypeTagMagicValue,
10791  Sema::TypeTagData> *MagicValues,
10792  bool &FoundWrongKind,
10794  FoundWrongKind = false;
10795 
10796  // Variable declaration that has type_tag_for_datatype attribute.
10797  const ValueDecl *VD = nullptr;
10798 
10799  uint64_t MagicValue;
10800 
10801  if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
10802  return false;
10803 
10804  if (VD) {
10805  if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
10806  if (I->getArgumentKind() != ArgumentKind) {
10807  FoundWrongKind = true;
10808  return false;
10809  }
10810  TypeInfo.Type = I->getMatchingCType();
10811  TypeInfo.LayoutCompatible = I->getLayoutCompatible();
10812  TypeInfo.MustBeNull = I->getMustBeNull();
10813  return true;
10814  }
10815  return false;
10816  }
10817 
10818  if (!MagicValues)
10819  return false;
10820 
10821  llvm::DenseMap<Sema::TypeTagMagicValue,
10822  Sema::TypeTagData>::const_iterator I =
10823  MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
10824  if (I == MagicValues->end())
10825  return false;
10826 
10827  TypeInfo = I->second;
10828  return true;
10829 }
10830 } // end anonymous namespace
10831 
10833  uint64_t MagicValue, QualType Type,
10834  bool LayoutCompatible,
10835  bool MustBeNull) {
10836  if (!TypeTagForDatatypeMagicValues)
10837  TypeTagForDatatypeMagicValues.reset(
10838  new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
10839 
10840  TypeTagMagicValue Magic(ArgumentKind, MagicValue);
10841  (*TypeTagForDatatypeMagicValues)[Magic] =
10842  TypeTagData(Type, LayoutCompatible, MustBeNull);
10843 }
10844 
10845 namespace {
10846 bool IsSameCharType(QualType T1, QualType T2) {
10847  const BuiltinType *BT1 = T1->getAs<BuiltinType>();
10848  if (!BT1)
10849  return false;
10850 
10851  const BuiltinType *BT2 = T2->getAs<BuiltinType>();
10852  if (!BT2)
10853  return false;
10854 
10855  BuiltinType::Kind T1Kind = BT1->getKind();
10856  BuiltinType::Kind T2Kind = BT2->getKind();
10857 
10858  return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
10859  (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
10860  (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
10861  (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
10862 }
10863 } // end anonymous namespace
10864 
10865 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
10866  const Expr * const *ExprArgs) {
10867  const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
10868  bool IsPointerAttr = Attr->getIsPointer();
10869 
10870  const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
10871  bool FoundWrongKind;
10872  TypeTagData TypeInfo;
10873  if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
10874  TypeTagForDatatypeMagicValues.get(),
10875  FoundWrongKind, TypeInfo)) {
10876  if (FoundWrongKind)
10877  Diag(TypeTagExpr->getExprLoc(),
10878  diag::warn_type_tag_for_datatype_wrong_kind)
10879  << TypeTagExpr->getSourceRange();
10880  return;
10881  }
10882 
10883  const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
10884  if (IsPointerAttr) {
10885  // Skip implicit cast of pointer to `void *' (as a function argument).
10886  if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
10887  if (ICE->getType()->isVoidPointerType() &&
10888  ICE->getCastKind() == CK_BitCast)
10889  ArgumentExpr = ICE->getSubExpr();
10890  }
10891  QualType ArgumentType = ArgumentExpr->getType();
10892 
10893  // Passing a `void*' pointer shouldn't trigger a warning.
10894  if (IsPointerAttr && ArgumentType->isVoidPointerType())
10895  return;
10896 
10897  if (TypeInfo.MustBeNull) {
10898  // Type tag with matching void type requires a null pointer.
10899  if (!ArgumentExpr->isNullPointerConstant(Context,
10901  Diag(ArgumentExpr->getExprLoc(),
10902  diag::warn_type_safety_null_pointer_required)
10903  << ArgumentKind->getName()
10904  << ArgumentExpr->getSourceRange()
10905  << TypeTagExpr->getSourceRange();
10906  }
10907  return;
10908  }
10909 
10910  QualType RequiredType = TypeInfo.Type;
10911  if (IsPointerAttr)
10912  RequiredType = Context.getPointerType(RequiredType);
10913 
10914  bool mismatch = false;
10915  if (!TypeInfo.LayoutCompatible) {
10916  mismatch = !Context.hasSameType(ArgumentType, RequiredType);
10917 
10918  // C++11 [basic.fundamental] p1:
10919  // Plain char, signed char, and unsigned char are three distinct types.
10920  //
10921  // But we treat plain `char' as equivalent to `signed char' or `unsigned
10922  // char' depending on the current char signedness mode.
10923  if (mismatch)
10924  if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
10925  RequiredType->getPointeeType())) ||
10926  (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
10927  mismatch = false;
10928  } else
10929  if (IsPointerAttr)
10930  mismatch = !isLayoutCompatible(Context,
10931  ArgumentType->getPointeeType(),
10932  RequiredType->getPointeeType());
10933  else
10934  mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
10935 
10936  if (mismatch)
10937  Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
10938  << ArgumentType << ArgumentKind
10939  << TypeInfo.LayoutCompatible << RequiredType
10940  << ArgumentExpr->getSourceRange()
10941  << TypeTagExpr->getSourceRange();
10942 }
ObjCPropertyRefExpr - A dot-syntax expression to access an ObjC property.
Definition: ExprObjC.h:539
const OptionalFlag & hasSpacePrefix() const
Definition: FormatString.h:510
Kind getKind() const
Definition: Type.h:2060
unsigned getFlags() const
getFlags - Return the flags for this scope.
Definition: Scope.h:210
The receiver is the instance of the superclass object.
Definition: ExprObjC.h:1009
static void diagnoseArrayStarInParamType(Sema &S, QualType PType, SourceLocation Loc)
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition: Expr.h:2411
static FormatStringType GetFormatStringType(const FormatAttr *Format)
bool isMacroArgExpansion(SourceLocation Loc, SourceLocation *StartLoc=nullptr) const
Tests whether the given source location represents a macro argument's expansion into the function-lik...
Defines the clang::ASTContext interface.
unsigned getNumInits() const
Definition: Expr.h:3776
VariadicCallType
Definition: Sema.h:8558
SourceLocation getEnd() const
static std::pair< QualType, StringRef > shouldNotPrintDirectly(const ASTContext &Context, QualType IntendedTy, const Expr *E)
const Expr * getBase() const
Definition: ExprObjC.h:509
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:64
CastKind getCastKind() const
Definition: Expr.h:2680
ObjCStringFormatFamily
CanQualType LongLongTy
Definition: ASTContext.h:901
FunctionDecl - An instance of this class is created to represent a function declaration or definition...
Definition: Decl.h:1561
bool isVariadic() const
Definition: Type.h:3366
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
Definition: ASTMatchers.h:1367
Expr ** getArgs()
Retrieve the call arguments.
Definition: Expr.h:2208
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
bool isVector() const
Definition: APValue.h:187
The receiver is an object instance.
Definition: ExprObjC.h:1005
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition: Sema.h:9565
bool isNullPtrType() const
Definition: Type.h:5693
StringRef getName() const
getName - Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:237
static void CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType, SourceLocation ReturnLoc)
CheckReturnStackAddr - Check if a return statement returns the address of a stack variable...
#define BUILTIN_ROW(x)
CanQualType OCLQueueTy
Definition: ASTContext.h:918
Smart pointer class that efficiently represents Objective-C method names.
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition: Type.h:5761
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:2179
EvaluatedExprVisitor - This class visits 'Expr *'s.
CanQualType VoidPtrTy
Definition: ASTContext.h:908
static llvm::SmallPtrSet< MemberKind *, 1 > CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty)
bool isAtLeastAsQualifiedAs(QualType Other) const
Determine whether this type is at least as qualified as the other given type, requiring exact equalit...
Definition: Type.h:5413
A (possibly-)qualified type.
Definition: Type.h:598
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition: Type.h:5781
bool isInvalid() const
Definition: Ownership.h:160
static bool CheckForReference(Sema &SemaRef, const Expr *E, const PartialDiagnostic &PD)
bool isCharType() const
Definition: Type.cpp:1656
bool isMacroID() const
bool isCanonicalUnqualified() const
Determines if this type would be canonical if it had no further qualification.
Definition: Type.h:1559
static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall)
OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different overload formats specified ...
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition: Type.h:5647
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition: Expr.h:2217
bool isVariadic() const
Definition: Decl.h:3532
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:2361
ArrayRef< QualType > getTypeArgs() const
Retrieve the type arguments for this type.
Definition: Type.h:5098
bool hasLeadingEmptyMacro() const
Definition: Stmt.h:532
FormatStringType
Definition: Sema.h:9413
bool isMemberPointerType() const
Definition: Type.h:5506
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc...
Definition: Sema.h:2705
IdentifierInfo * getIdentifier() const
getIdentifier - Get the identifier that names this declaration, if there is one.
Definition: Decl.h:232
bool CheckParmsForFunctionDef(ArrayRef< ParmVarDecl * > Parameters, bool CheckParameterNames)
Helpers for dealing with blocks and functions.
bool isOne() const
isOne - Test whether the quantity equals one.
Definition: CharUnits.h:119
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:1693
const LangOptions & getLangOpts() const
Definition: Sema.h:1062
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false)
Perform unqualified name lookup starting from a given scope.
SourceLocation getSpellingLoc(SourceLocation Loc) const
Given a SourceLocation object, return the spelling location referenced by the ID. ...
static bool IsFunctionStdAbs(const FunctionDecl *FDecl)
Optional< LengthModifier > getCorrectedLengthModifier() const
static Optional< int > GetNSMutableArrayArgumentIndex(Sema &S, ObjCMessageExpr *Message)
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:2879
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
EnumConstantDecl - An instance of this object exists for each enum constant that is defined...
Definition: Decl.h:2481
unsigned getIntWidth(QualType T) const
const ScanfConversionSpecifier & getConversionSpecifier() const
Definition: FormatString.h:578
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition: Scope.h:218
void addConst()
Add the const type qualifier to this QualType.
Definition: Type.h:761
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:179
bool hasStandardConversionSpecifier(const LangOptions &LangOpt) const
const LengthModifier & getLengthModifier() const
Definition: FormatString.h:373
bool isRecordType() const
Definition: Type.h:5539
unsigned getSpellingLineNumber(SourceLocation Loc, bool *Invalid=nullptr) const
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition: Sema.h:1139
bool isInteger() const
Definition: Type.h:2072
arg_iterator arg_begin()
Definition: ExprCXX.h:1276
const char * getCharacterData(SourceLocation SL, bool *Invalid=nullptr) const
Return a pointer to the start of the specified location in the appropriate spelling MemoryBuffer...
void setType(QualType t)
Definition: Expr.h:127
bool isVoidPointerType() const
Definition: Type.cpp:385
static bool referToTheSameDecl(const Expr *E1, const Expr *E2)
Check if two expressions refer to the same declaration.
const OptionalFlag & hasLeadingZeros() const
Definition: FormatString.h:509
bool isEnumeralType() const
Definition: Type.h:5542
ParenExpr - This represents a parethesized expression, e.g.
Definition: Expr.h:1619
PtrTy get() const
Definition: Ownership.h:164
Expr * getLowerBound()
Get lower bound of array section.
Definition: ExprOpenMP.h:91
The base class of the type hierarchy.
Definition: Type.h:1281
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:922
unsigned getPresumedLineNumber(SourceLocation Loc, bool *Invalid=nullptr) const
#define log2(__x)
Definition: tgmath.h:977
CanQualType LongTy
Definition: ASTContext.h:901
bool capturesVariable(const VarDecl *var) const
Definition: Decl.cpp:3901
NSDictionaryMethodKind
Enumerates the NSDictionary/NSMutableDictionary methods used to generate literals and to apply some c...
Definition: NSAPI.h:100
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:2456
NamespaceDecl - Represent a C++ namespace.
Definition: Decl.h:471
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:46
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1162
Wrapper for source info for typedefs.
Definition: TypeLoc.h:620
static AbsoluteValueKind getAbsoluteValueKind(QualType T)
bool isBooleanType() const
Definition: Type.h:5743
A container of type source information.
Definition: Decl.h:62
static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call)
Returns true if pipe element type is different from the pointer.
SourceLocation getOperatorLoc() const
Definition: Expr.h:2937
SourceLocation getLocStart() const LLVM_READONLY
Definition: Expr.h:1602
bool isBlockPointerType() const
Definition: Type.h:5488
bool isInSystemMacro(SourceLocation loc)
Returns whether Loc is expanded from a macro in a system header.
bool HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects=true) const
HasSideEffects - This routine returns true for all those expressions which have any effect other than...
Definition: Expr.cpp:2802
static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount)
Checks that a call expression's argument count is the desired number.
float __ovld __cnfn distance(float p0, float p1)
Returns the distance between p0 and p1.
bool hasUnsignedIntegerRepresentation() const
Determine whether this type has an unsigned integer representation of some sort, e.g., it is an unsigned integer type or a vector.
Definition: Type.cpp:1776
CanQualType HalfTy
Definition: ASTContext.h:905
const llvm::APInt & getSize() const
Definition: Type.h:2527
static unsigned changeAbsFunction(unsigned AbsKind, AbsoluteValueKind ValueKind)
bool isValidPointerAttrType(QualType T, bool RefOkay=false)
Determine if type T is a valid subject for a nonnull and similar attributes.
ObjCDictionaryElement getKeyValueElement(unsigned Index) const
Definition: ExprObjC.h:309
static void CheckFormatString(Sema &S, const StringLiteral *FExpr, const Expr *OrigFormatExpr, ArrayRef< const Expr * > Args, bool HasVAListArg, unsigned format_idx, unsigned firstDataArg, Sema::FormatStringType Type, bool inFunctionCall, Sema::VariadicCallType CallType, llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg)
VarDecl - An instance of this class is created to represent a variable declaration or definition...
Definition: Decl.h:768
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaInternal.h:25
ScopeFlags
ScopeFlags - These are bitfields that are or'd together when creating a scope, which defines the sort...
Definition: Scope.h:43
DiagnosticsEngine & Diags
Definition: Sema.h:301
CompoundLiteralExpr - [C99 6.5.2.5].
Definition: Expr.h:2562
const Expr * getCallee() const
Definition: Expr.h:2188
bool areArgsDestroyedLeftToRightInCallee() const
Are arguments to a call destroyed left to right in the callee? This is a fundamental language change...
Definition: TargetCXXABI.h:217
APFloat & getComplexFloatReal()
Definition: APValue.h:232
ArgType getArgType(ASTContext &Ctx, bool IsObjCLiteral) const
Returns the builtin type that a data argument paired with this format specifier should have...
Extra information about a function prototype.
Definition: Type.h:3167
field_iterator field_begin() const
Definition: Decl.cpp:3767
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:1813
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:113
Expr * IgnoreImplicit() LLVM_READONLY
IgnoreImplicit - Skip past any implicit AST nodes which might surround this expression.
Definition: Expr.h:724
Like System, but searched after the system directories.
Defines the Objective-C statement AST node classes.
static bool isAssignmentOp(Opcode Opc)
Definition: Expr.h:3022
ParmVarDecl - Represents a parameter to a function.
Definition: Decl.h:1377
bool isObjCRetainableType() const
Definition: Type.cpp:3699
NullPointerConstantKind isNullPointerConstant(ASTContext &Ctx, NullPointerConstantValueDependence NPC) const
isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to a Null pointer constant...
Definition: Expr.cpp:3132
Defines the clang::Expr interface and subclasses for C++ expressions.
ObjCInterfaceDecl * NSDictionaryDecl
The declaration of the Objective-C NSDictionary class.
Definition: Sema.h:769
SourceLocation getLocation() const
Definition: Expr.h:1025
static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, IdentifierInfo *FnName, SourceLocation FnLoc, SourceLocation RParenLoc)
Takes the expression passed to the size_t parameter of functions such as memcmp, strncat, etc and warns if it's a comparison.
Parse and apply any fixits to the source.
bool isVoidType() const
Definition: Type.h:5680
QualType getType() const
Definition: DeclObjC.h:781
FieldDecl * getSourceBitField()
If this expression refers to a bit-field, retrieve the declaration of that bit-field.
Definition: Expr.cpp:3289
QualType withConst() const
Retrieves a version of this type with const applied.
static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, Qualifiers::ObjCLifetime LT, Expr *RHS, bool isProperty)
PipeType - OpenCL20.
Definition: Type.h:5190
static bool requiresParensToAddCast(const Expr *E)
static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall, Expr *BlockArg, unsigned NumNonVarArgs)
OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all 'local void*' parameter of passed blo...
Base wrapper for a particular "section" of type source info.
Definition: TypeLoc.h:40
Expr * IgnoreImpCasts() LLVM_READONLY
IgnoreImpCasts - Skip past any implicit casts which might surround this expression.
Definition: Expr.h:2777
unsigned getNumParams() const
Definition: Type.h:3271
RecordDecl - Represents a struct/union/class.
Definition: Decl.h:3253
ExprResult UsualUnaryConversions(Expr *E)
UsualUnaryConversions - Performs various conversions that are common to most operators (C99 6...
Definition: SemaExpr.cpp:761
One of these records is kept for each identifier that is lexed.
std::unique_ptr< NSAPI > NSAPIObj
Caches identifiers/selectors for NSFoundation APIs.
Definition: Sema.h:733
bool isScalarType() const
Definition: Type.h:5715
bool isComplexInt() const
Definition: APValue.h:184
ShuffleVectorExpr - clang-specific builtin-in function __builtin_shufflevector.
Definition: Expr.h:3422
class LLVM_ALIGNAS(8) DependentTemplateSpecializationType const IdentifierInfo * Name
Represents a template specialization type whose template cannot be resolved, e.g. ...
Definition: Type.h:4549
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:1789
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:92
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:3276
QualType getAddrSpaceQualType(QualType T, unsigned AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
bool isReferenceType() const
Definition: Type.h:5491
QualType getReturnType() const
Definition: Decl.h:2034
virtual bool validateCpuSupports(StringRef Name) const
FieldDecl - An instance of this class is created by Sema::ActOnField to represent a member of a struc...
Definition: Decl.h:2293
bool ParseScanfString(FormatStringHandler &H, const char *beg, const char *end, const LangOptions &LO, const TargetInfo &Target)
bool isCompleteDefinition() const
isCompleteDefinition - Return true if this decl has its body fully specified.
Definition: Decl.h:2871
bool isAnyPointerType() const
Definition: Type.h:5485
static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op)
const internal::VariadicAllOfMatcher< Decl > decl
Matches declarations.
Definition: ASTMatchers.h:283
CXXRecordDecl * getDefinition() const
Definition: DeclCXX.h:678
void setArg(unsigned Arg, Expr *ArgExpr)
setArg - Set the specified argument.
Definition: Expr.h:2227
The iterator over UnresolvedSets.
Definition: UnresolvedSet.h:28
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:1982
bool isInlineNamespace() const
Definition: DeclBase.cpp:901
static DeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *D, bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc, QualType T, ExprValueKind VK, NamedDecl *FoundD=nullptr, const TemplateArgumentListInfo *TemplateArgs=nullptr)
Definition: Expr.cpp:368
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition: Type.cpp:450
Stmt * getBody() const override
Definition: Decl.h:3536
Expr * getSubExpr()
Definition: Expr.h:2684
CanQualType OCLReserveIDTy
Definition: ASTContext.h:918
ObjCArrayLiteral - used for objective-c array containers; as in: @["Hello", NSApp, [NSNumber numberWithInt:42]];.
Definition: ExprObjC.h:144
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1199
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2007
SourceLocation getRParenLoc() const
Definition: Expr.h:2284
void DiagnoseEmptyLoopBody(const Stmt *S, const Stmt *PossibleBody)
Warn if a for/while loop statement S, which is followed by PossibleBody, has a suspicious null statem...
Optional< ConversionSpecifier > getStandardSpecifier() const
IdentifierTable & Idents
Definition: ASTContext.h:459
static Optional< int > GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message)
An r-value expression (a pr-value in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:105
SourceLocation getSuperLoc() const
Retrieve the location of the 'super' keyword for a class or instance message to 'super', otherwise an invalid source location.
Definition: ExprObjC.h:1196
Expr * getLHS() const
Definition: Expr.h:2943
Describes an C or C++ initializer list.
Definition: Expr.h:3746
static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall, unsigned Start, unsigned End)
BinaryOperatorKind
ForStmt - This represents a 'for (init;cond;inc)' stmt.
Definition: Stmt.h:1153
static bool isEqualityOp(Opcode Opc)
Definition: Expr.h:2986
Represents the results of name lookup.
Definition: Sema/Lookup.h:30
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:588
SourceLocation getLocWithOffset(int Offset) const
Return a source location with the specified offset from this SourceLocation.
Expr * getTrueExpr() const
Definition: Expr.h:3326
ObjCMethodDecl * getCurMethodDecl()
getCurMethodDecl - If inside of a method body, this returns a pointer to the method decl for the meth...
Definition: Sema.cpp:945
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:38
APValue Val
Val - This is the value the expression can be folded to.
Definition: Expr.h:564
bool EvaluateAsFloat(llvm::APFloat &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects) const
EvaluateAsFloat - Return true if this is a constant which we can fold and convert to a floating point...
unsigned getMinRequiredArguments() const
getMinRequiredArguments - Returns the minimum number of arguments needed to call this function...
Definition: Decl.cpp:2785
QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error, unsigned *IntegerConstantArgs=nullptr) const
Return the type for the specified builtin.
SourceLocation getImmediateMacroCallerLoc(SourceLocation Loc) const
Gets the location of the immediate macro caller, one level up the stack toward the initial macro type...
bool isSuperReceiver() const
Definition: ExprObjC.h:700
bool isQuad() const
static bool isNonNullType(ASTContext &ctx, QualType type)
Determine whether the given type has a non-null nullability annotation.
field_range fields() const
Definition: Decl.h:3382
unsigned LayoutCompatible
If true, Type should be compared with other expression's types for layout-compatibility.
Definition: Sema.h:9507
bool isMacroBodyExpansion(SourceLocation Loc) const
Tests whether the given source location represents the expansion of a macro body. ...
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
Represents a typeof (or typeof) expression (a GCC extension).
Definition: Type.h:3525
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:2897
bool isUnsigned() const
Selector getSelector() const
Definition: ExprObjC.cpp:306
bool isValueDependent() const
isValueDependent - Determines whether this expression is value-dependent (C++ [temp.dep.constexpr]).
Definition: Expr.h:147
RecordDecl * getDecl() const
Definition: Type.h:3716
bool isUnsignedIntegerType() const
Return true if this is an integer type that is unsigned, according to C99 6.2.5p6 [which returns true...
Definition: Type.cpp:1746
Expr * IgnoreParenCasts() LLVM_READONLY
IgnoreParenCasts - Ignore parentheses and casts.
Definition: Expr.cpp:2326
ObjCStringLiteral, used for Objective-C string literals i.e.
Definition: ExprObjC.h:29
Values of this type can never be null.
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:39
static const Expr * EvalVal(const Expr *E, SmallVectorImpl< const DeclRefExpr * > &refVars, const Decl *ParentDecl)
EvalVal - This function is complements EvalAddr in the mutual recursion.
NSSetMethodKind
Enumerates the NSMutableSet/NSOrderedSet methods used to apply some checks.
Definition: NSAPI.h:125
Expr * getLHS() const
Definition: Expr.h:3215
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr...
Definition: Decl.cpp:4006
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition: Expr.h:2632
TypeClass getTypeClass() const
Definition: Type.h:1533
base_class_iterator bases_begin()
Definition: DeclCXX.h:725
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types...
Definition: Type.cpp:1892
QualType withVolatile() const
Definition: Type.h:772
iterator end() const
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
const char * getHeaderName(unsigned ID) const
If this is a library function that comes from a specific header, retrieve that header name...
Definition: Builtins.h:166
AssignConvertType CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS, bool Diagnose=true, bool DiagnoseCFAudited=false, bool ConvertRHS=true)
Definition: SemaExpr.cpp:7677
An ordinary object is located at an address in memory.
Definition: Specifiers.h:121
SmallVector< BoundNodes, 1 > match(MatcherT Matcher, const NodeT &Node, ASTContext &Context)
Returns the results of matching Matcher on Node.
static const CXXRecordDecl * getContainedDynamicClass(QualType T, bool &IsContained)
Determine whether the given type is or contains a dynamic class type (e.g., whether it has a vtable)...
const Expr * getBase() const
Definition: ExprObjC.h:682
bool fixType(QualType QT, QualType RawQT, const LangOptions &LangOpt, ASTContext &Ctx)
static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall)
OpenCL C v2.0, s6.13.17.6 - Check the argument to the get_kernel_work_group_size and get_kernel_prefe...
Member name lookup, which finds the names of class/struct/union members.
Definition: Sema.h:2713
Expression is a GNU-style __null constant.
Definition: Expr.h:681
detail::InMemoryDirectory::const_iterator I
static void diagnoseRetainCycle(Sema &S, Expr *capturer, RetainCycleOwner &owner)
PropertyAttributeKind getPropertyAttributes() const
Definition: DeclObjC.h:792
APSInt & getComplexIntReal()
Definition: APValue.h:216
QualType getCanonicalTypeInternal() const
Definition: Type.h:2001
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition: Type.cpp:2098
CanQualType UnsignedCharTy
Definition: ASTContext.h:902
QualType getType() const
Definition: Decl.h:599
bool isInvalid() const
This object can be modified without requiring retains or releases.
Definition: Type.h:138
param_iterator param_begin()
Definition: Decl.h:2000
arg_iterator arg_end()
Definition: Expr.h:2248
field_iterator field_end() const
Definition: Decl.h:3385
APValue & getVectorElt(unsigned I)
Definition: APValue.h:258
Expr * getRHS() const
Definition: Expr.h:3216
bool isAddrLabelDiff() const
Definition: APValue.h:192
bool isUnion() const
Definition: Decl.h:2939
OpenMP 4.0 [2.4, Array Sections].
Definition: ExprOpenMP.h:45
ConditionalOperator - The ?: ternary operator.
Definition: Expr.h:3170
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:263
Expr * getFalseExpr() const
Definition: Expr.h:3213
llvm::APInt getValue() const
Definition: Expr.h:1248
bool AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const
QualType getParamType(unsigned i) const
Definition: Type.h:3272
Represents a prototype with parameter type info, e.g.
Definition: Type.h:3073
bool hasIrrelevantDestructor() const
Determine whether this class has a destructor which has no semantic effect.
Definition: DeclCXX.h:1292
bool isFloatingPoint() const
Definition: Type.h:2084
bool isInstanceMessage() const
Determine whether this is an instance message to either a computed object or to super.
Definition: ExprObjC.h:1143
FileID getFileID(SourceLocation SpellingLoc) const
Return the FileID for a SourceLocation.
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1009
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
CastKind
CastKind - The kind of operation required for a conversion.
std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const
static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx)
Returns true if pipe element type is different from the pointer.
AbsoluteValueKind
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand...
Definition: Expr.h:1974
unsigned getPresumedColumnNumber(SourceLocation Loc, bool *Invalid=nullptr) const
ASTContext * Context
arg_iterator arg_end()
Definition: ExprCXX.h:1277
bool isInstantiationDependent() const
Whether this expression is instantiation-dependent, meaning that it depends in some way on a template...
Definition: Expr.h:189
const SmallVectorImpl< AnnotatedLine * >::const_iterator End
Expr * getCond() const
Definition: Expr.h:3204
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee...
Definition: Type.cpp:415
bool isUnarySelector() const
bool isFunctionPointerType() const
Definition: Type.h:5500
CanQualType OCLNDRangeTy
Definition: ASTContext.h:918
bool isRealFloatingType() const
Floating point categories.
Definition: Type.cpp:1799
unsigned getTypeWidth(IntType T) const
Return the width (in bits) of the specified integer type enum.
NSArrayMethodKind
Enumerates the NSArray/NSMutableArray methods used to generate literals and to apply some checks...
Definition: NSAPI.h:76
Retains information about a block that is currently being parsed.
Definition: ScopeInfo.h:597
static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl, CallExpr *TheCall, unsigned SizeIdx, unsigned DstSizeIdx)
BlockDecl - This represents a block literal declaration, which is like an unnamed FunctionDecl...
Definition: Decl.h:3456
static void CheckNonNullArguments(Sema &S, const NamedDecl *FDecl, const FunctionProtoType *Proto, ArrayRef< const Expr * > Args, SourceLocation CallSiteLoc)
bool isKnownToHaveBooleanValue() const
isKnownToHaveBooleanValue - Return true if this is an integer expression that is known to return 0 or...
Definition: Expr.cpp:112
QualType getPointeeType() const
Definition: Type.h:2300
ValueDecl - Represent the declaration of a variable (in which case it is an lvalue) a function (in wh...
Definition: Decl.h:590
Expr - This represents one expression.
Definition: Expr.h:105
bool isQueueT() const
Definition: Type.h:5615
StringRef getName() const
Return the actual identifier string.
Allow any unmodeled side effect.
Definition: Expr.h:589
const char * getName(unsigned ID) const
Return the identifier name for the specified builtin, e.g.
Definition: Builtins.h:83
Represents a character-granular source range.
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition: Specifiers.h:102
void setCallee(Expr *F)
Definition: Expr.h:2190
unsigned getNumArgs() const
bool isAnyComplexType() const
Definition: Type.h:5545
bool isSEHExceptScope() const
Determine whether this scope is a SEH '__except' block.
Definition: Scope.h:430
bool isListInitialization() const
Whether this constructor call was written as list-initialization.
Definition: ExprCXX.h:1240
Expr * getBitWidth() const
Definition: Decl.h:2375
bool isComplexFloat() const
Definition: APValue.h:185
bool isAtomicType() const
Definition: Type.h:5564
static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg)
OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local void*, which is a requirem...
bool isUnsignedInteger() const
Definition: Type.h:2080
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:4567
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2414
This scope corresponds to an SEH except.
Definition: Scope.h:123
bool isVariableArrayType() const
Definition: Type.h:5530
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2011
ObjCDictionaryLiteral - AST node to represent objective-c dictionary literals; as in:"name" : NSUserN...
Definition: ExprObjC.h:257
ObjCInterfaceDecl * getReceiverInterface() const
Retrieve the Objective-C interface to which this message is being directed, if known.
Definition: ExprObjC.cpp:327
void setObjectKind(ExprObjectKind Cat)
setObjectKind - Set the object kind produced by this expression.
Definition: Expr.h:421
bool isFloatingType() const
Definition: Type.cpp:1783
CanQualType ShortTy
Definition: ASTContext.h:901
ImplicitParamDecl * getSelfDecl() const
Definition: DeclObjC.h:406
void removeLocalConst()
Definition: Type.h:5353
void removeLocalVolatile()
Definition: Type.h:5361
char __ovld __cnfn min(char x, char y)
Returns y if y < x, otherwise it returns x.
unsigned getNumElements() const
getNumElements - Return number of elements of objective-c array literal.
Definition: ExprObjC.h:184
SourceLocation getQuestionLoc() const
Definition: Expr.h:3159
SourceLocation getLocation() const
Definition: ExprObjC.h:689
Expr * getSubExpr() const
Definition: Expr.h:1695
Expr * getElement(unsigned Index)
getExpr - Return the Expr at the specified index.
Definition: ExprObjC.h:187
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:1774
void setValueKind(ExprValueKind Cat)
setValueKind - Set the value kind produced by this expression.
Definition: Expr.h:418
bool fixType(QualType QT, const LangOptions &LangOpt, ASTContext &Ctx, bool IsObjCLiteral)
Changes the specifier and length according to a QualType, retaining any flags or options.
static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call)
bool EvaluateAsInt(llvm::APSInt &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer...
const PrintfConversionSpecifier & getConversionSpecifier() const
Definition: FormatString.h:479
An expression that sends a message to the given Objective-C object or class.
Definition: ExprObjC.h:860
UnaryOperator - This represents the unary-expression's (except sizeof and alignof), the postinc/postdec operators from postfix-expression, and various extensions.
Definition: Expr.h:1668
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:3543
SmallVector< ActiveTemplateInstantiation, 16 > ActiveTemplateInstantiations
List of active template instantiations.
Definition: Sema.h:6732
Represents a GCC generic vector type.
Definition: Type.h:2756
static OpenCLAccessAttr * getOpenCLArgAccess(const Decl *D)
Returns OpenCL access qual.
DeclarationName getDeclName() const
getDeclName - Get the actual, stored name of the declaration, which may be a special name...
Definition: Decl.h:258
class LLVM_ALIGNAS(8) TemplateSpecializationType unsigned NumArgs
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: Type.h:4154
static const Expr * EvalAddr(const Expr *E, SmallVectorImpl< const DeclRefExpr * > &refVars, const Decl *ParentDecl)
EvalAddr - EvalAddr and EvalVal are mutually recursive functions that check if the expression in a re...
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition: DeclCXX.h:712
ValueDecl * getDecl()
Definition: Expr.h:1017
APSInt & getComplexIntImag()
Definition: APValue.h:224
ObjCStringFormatFamily getObjCFStringFormattingFamily() const
Definition: Decl.cpp:1017
The result type of a method or function.
CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style cast in C++ (C++ [expr.cast]), which uses the syntax (Type)expr.
Definition: Expr.h:2834
NestedNameSpecifierLoc getQualifierLoc() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name, with source-location information.
Definition: Expr.h:1036
static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, const NamedDecl *ND)
Check whether this array fits the idiom of a size-one tail padded array member of a struct...
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
Definition: Type.cpp:1762
SourceLocation getSemiLoc() const
Definition: Stmt.h:529
const SourceManager & SM
Definition: Format.cpp:1184
void EvaluateForOverflow(const ASTContext &Ctx) const
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:671
static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, bool IsPolyUnsigned, bool IsInt64Long)
getNeonEltType - Return the QualType corresponding to the elements of the vector type specified by th...
Expr * getTrueExpr() const
Definition: Expr.h:3208
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:231
static const Expr * getStrlenExprArg(const Expr *E)
static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall)
SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition: ExprObjC.h:1290
CanQualType SignedCharTy
Definition: ASTContext.h:901
static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, ASTContext &Context)
static CharSourceRange getCharRange(SourceRange R)
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:3561
bool isNothrow(const ASTContext &Ctx, bool ResultIfDependent=false) const
Determine whether this function type has a non-throwing exception specification.
Definition: Type.cpp:2775
std::pair< const IdentifierInfo *, uint64_t > TypeTagMagicValue
A pair of ArgumentKind identifier and magic value.
Definition: Sema.h:9513
static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call)
static StringLiteralCheckType checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef< const Expr * > Args, bool HasVAListArg, unsigned format_idx, unsigned firstDataArg, Sema::FormatStringType Type, Sema::VariadicCallType CallType, bool InFunctionCall, llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg)
bool ParseFormatStringHasSArg(const char *beg, const char *end, const LangOptions &LO, const TargetInfo &Target)
There is no lifetime qualification on this type.
Definition: Type.h:134
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:215
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class...
Definition: Expr.h:848
Enumerates target-specific builtins in their own namespaces within namespace clang.
bool EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx) const
EvaluateAsBooleanCondition - Return true if this is a constant which we we can fold and convert to a ...
ConvertVectorExpr - Clang builtin function __builtin_convertvector This AST node provides support for...
Definition: Expr.h:3487
#define false
Definition: stdbool.h:33
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
CanQualType BuiltinFnTy
Definition: ASTContext.h:910
Assigning into this object requires the old value to be released and the new value to be retained...
Definition: Type.h:145
Kind
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:5730
const char * getSpelling() const
not a target-specific vector type
Definition: Type.h:2759
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition: Expr.h:4679
static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner)
Consider whether capturing the given variable can possibly lead to a retain cycle.
Encodes a location in the source.
bool hasIntegerRepresentation() const
Determine whether this type has an integer representation of some sort, e.g., it is an integer type o...
Definition: Type.cpp:1599
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
unsigned getNumParams() const
getNumParams - Return the number of parameters this function must have based on its FunctionType...
Definition: Decl.cpp:2742
static const Expr * getSizeOfExprArg(const Expr *E)
If E is a sizeof expression, returns its argument expression, otherwise returns NULL.
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:5259
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums...
Definition: Type.h:3733
const TemplateArgument * iterator
Definition: Type.h:4233
Expression is not a Null pointer constant.
Definition: Expr.h:665
bool isConstant(const ASTContext &Ctx) const
Definition: Type.h:735
unsigned getBitWidthValue(const ASTContext &Ctx) const
Definition: Decl.cpp:3468
Expr * getSourceExpr() const
The source expression of an opaque value expression is the expression which originally generated the ...
Definition: Expr.h:902
void checkRetainCycles(ObjCMessageExpr *msg)
checkRetainCycles - Check whether an Objective-C message send might create an obvious retain cycle...
static const Expr * ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx)
bool isValid() const
Return true if this is a valid SourceLocation object.
StringRef getNameForSlot(unsigned argIndex) const
Retrieve the name at a given position in the selector.
ASTContext & getASTContext() const
Definition: Sema.h:1069
bool refersToEnclosingVariableOrCapture() const
Does this DeclRefExpr refer to an enclosing local or a captured variable?
Definition: Expr.h:1141
bool isFreeIvar() const
Definition: ExprObjC.h:514
bool isVariadic() const
Definition: DeclObjC.h:416
APFloat & getFloat()
Definition: APValue.h:208
QualType withConst() const
Definition: Type.h:764
ExprObjectKind
A further classification of the kind of object referenced by an l-value or x-value.
Definition: Specifiers.h:119
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:1736
ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall)
SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
static bool CheckNonNullExpr(Sema &S, const Expr *Expr)
Checks if a the given expression evaluates to null.
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:1989
CanQualType FloatTy
Definition: ASTContext.h:904
virtual bool hasSjLjLowering() const
Controls if __builtin_longjmp / __builtin_setjmp can be lowered to llvm.eh.sjlj.longjmp / llvm...
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition: Type.cpp:1625
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2114
static void DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, const NamedDecl *FDecl, Expr **Args, unsigned NumArgs)
Diagnose use of s directive in an NSString which is being passed as formatting string to formatting m...
const OptionalFlag & hasPlusPrefix() const
Definition: FormatString.h:507
bool isIntegerConstantExpr(llvm::APSInt &Result, const ASTContext &Ctx, SourceLocation *Loc=nullptr, bool isEvaluated=true) const
isIntegerConstantExpr - Return true if this expression is a valid integer constant expression...
AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*, __atomic_load, __atomic_store, and __atomic_compare_exchange_*, for the similarly-named C++11 instructions, and __c11 variants for <stdatomic.h>.
Definition: Expr.h:4804
Specifies that a value-dependent expression should be considered to never be a null pointer constant...
Definition: Expr.h:696
CanQualType VoidTy
Definition: ASTContext.h:893
unsigned getMemoryFunctionKind() const
Identify a memory copying or setting function.
Definition: Decl.cpp:3350
Look up any declaration with any name.
Definition: Sema.h:2745
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: Type.h:5774
static bool isBlockPointer(Expr *Arg)
EltType getEltType() const
bool FormatStringHasSArg(const StringLiteral *FExpr)
bool isReserveIDT() const
Definition: Type.h:5623
Represents one property declaration in an Objective-C interface.
Definition: DeclObjC.h:699
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition: Expr.h:2734
bool isRValue() const
Definition: Expr.h:248
bool containsNonAsciiOrNull() const
Definition: Expr.h:1564
SourceLocation getBegin() const
void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, uint64_t MagicValue, QualType Type, bool LayoutCompatible, bool MustBeNull)
Register a magic integral constant to be used as a type tag.
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:5849
bool isTypeDependent() const
isTypeDependent - Determines whether this expression is type-dependent (C++ [temp.dep.expr]), which means that its type could change from one template instantiation to the next.
Definition: Expr.h:165
bool isAscii() const
Definition: Expr.h:1557
const IdentifierInfo * getIdentifier() const
Definition: Type.h:4580
bool isVectorType() const
Definition: Type.h:5548
SourceRange getSourceRange() const override LLVM_READONLY
Definition: Decl.cpp:1840
static bool isLogicalOp(Opcode Opc)
Definition: Expr.h:3019
bool hasCStrMethod(const Expr *E)
Check to see if a given expression could have '.c_str()' called on it.
unsigned getBuiltinID() const
Returns a value indicating whether this function corresponds to a builtin function.
Definition: Decl.cpp:2687
bool isPromotableIntegerType() const
More type predicates useful for type checking/promotion.
Definition: Type.cpp:2320
Assigning into this object requires a lifetime extension.
Definition: Type.h:151
const OptionalAmount & getFieldWidth() const
Definition: FormatString.h:377
SourceRange getSourceRange() const override LLVM_READONLY
Definition: DeclObjC.h:293
SourceLocation getLocStart() const LLVM_READONLY
Definition: Expr.cpp:427
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition: Diagnostic.h:652
static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call)
const BlockDecl * getBlockDecl() const
Definition: Expr.h:4581
SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL, unsigned ByteNo) const
We are currently in the filter expression of an SEH except block.
Definition: Scope.h:126
QualType getType() const
Return the type wrapped by this type source info.
Definition: Decl.h:70
static StringRef getImmediateMacroName(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
Retrieve the name of the immediate macro expansion.
Definition: Lexer.cpp:958
bool isDynamicClass() const
Definition: DeclCXX.h:698
static StringRef getImmediateMacroNameForDiagnostics(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
Retrieve the name of the immediate macro expansion.
Definition: Lexer.cpp:1005
Opcode getOpcode() const
Definition: Expr.h:1692
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:193
bool isFunctionProtoType() const
Definition: Type.h:1662
QualType getPointeeType() const
Definition: Type.h:2193
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
SourceLocation getRBracketLoc() const
Definition: Expr.h:2125
CompoundAssignOperator - For compound assignments (e.g.
Definition: Expr.h:3092
Expr * getInstanceReceiver()
Returns the object expression (receiver) for an instance message, or null for a message that is not a...
Definition: ExprObjC.h:1155
QualType getCallReturnType(const ASTContext &Ctx) const
getCallReturnType - Get the return type of the call expr.
Definition: Expr.cpp:1272
CanQualType UnsignedShortTy
Definition: ASTContext.h:902
bool isArrow() const
Definition: Expr.h:2510
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
bool isTSBuiltin(unsigned ID) const
Return true if this function is a target-specific builtin.
Definition: Builtins.h:93
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:2609
QualType getType() const
Definition: Expr.h:126
CanQualType CharTy
Definition: ASTContext.h:895
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
Definition: SemaInit.cpp:7836
NullStmt - This is the null statement ";": C99 6.8.3p3.
Definition: Stmt.h:511
bool isImplicitProperty() const
Definition: ExprObjC.h:630
EvalResult is a struct with detailed info about an evaluated expression.
Definition: Expr.h:562
static bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx)
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
Definition: OperatorKinds.h:22
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return 0.
Definition: Expr.cpp:1209
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
Definition: ASTMatchers.h:1983
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_RValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CCK_ImplicitConversion)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition: Sema.cpp:368
bool isUTF8() const
Definition: Expr.h:1559
SourceRange getSourceRange(const SourceRange &Range)
Returns the SourceRange of a SourceRange.
Definition: FixIt.h:34
ObjCLiteralKind CheckLiteralKind(Expr *FromE)
Definition: SemaExpr.cpp:8896
const OptionalFlag & hasThousandsGrouping() const
Definition: FormatString.h:503
bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the current evaluation context.
Definition: SemaExpr.cpp:14216
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:903
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:104
std::pair< SourceLocation, SourceLocation > getImmediateExpansionRange(SourceLocation Loc) const
Return the start/end of the expansion information for an expansion location.
static QualType getAbsoluteValueArgumentType(ASTContext &Context, unsigned AbsType)
bool isStandardLayoutType() const
Test if this type is a standard-layout type.
Definition: Type.cpp:2221
QualType getExceptionObjectType(QualType T) const
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
DeclarationName - The name of a declaration.
Expression is a Null pointer constant built from a zero integer expression that is not a simple...
Definition: Expr.h:672
U cast(CodeGen::Address addr)
Definition: Address.h:109
static bool isSetterLikeSelector(Selector sel)
Check for a keyword selector that starts with the word 'add' or 'set'.
A set of unresolved declarations.
SourceLocation getLocStart() const LLVM_READONLY
Definition: Expr.h:4883
StringRef getString() const
Definition: Expr.h:1514
SourceLocation getLocStart() const LLVM_READONLY
Definition: Decl.h:693
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
EnumDecl - Represents an enum.
Definition: Decl.h:3013
Expression is a C++11 nullptr.
Definition: Expr.h:678
detail::InMemoryDirectory::const_iterator E
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition: Expr.h:2205
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:1966
Flags to identify the types for overloaded Neon builtins.
void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange)
CheckCastAlign - Implements -Wcast-align, which warns when a pointer cast increases the alignment req...
static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner)
bool isFloat() const
Definition: APValue.h:183
specific_decl_iterator - Iterates over a subrange of declarations stored in a DeclContext, providing only those that are of type SpecificDecl (or a class derived from it).
Definition: DeclBase.h:1473
ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
SemaConvertVectorExpr - Handle __builtin_convertvector.
Expr * IgnoreParenImpCasts() LLVM_READONLY
IgnoreParenImpCasts - Ignore parentheses and implicit casts.
Definition: Expr.cpp:2413
param_iterator param_end()
Definition: Decl.h:2001
static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall)
Decl * getCalleeDecl()
Definition: Expr.cpp:1185
Represents a pointer to an Objective C object.
Definition: Type.h:4991
static LLVM_READONLY bool isLowercase(unsigned char c)
Return true if this character is a lowercase ASCII letter: [a-z].
Definition: CharInfo.h:100
Pointer to a block type.
Definition: Type.h:2286
ArgType getArgType(ASTContext &Ctx) const
static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID, CallExpr *Call)
static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, unsigned AbsFunctionKind)
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:3707
Complex values, per C99 6.2.5p11.
Definition: Type.h:2119
unsigned getNumNegativeBits() const
Returns the width in bits required to store all the negative enumerators of this enum.
Definition: Decl.h:3180
QualType getPointerDiffType() const
Return the unique type for "ptrdiff_t" (C99 7.17) defined in <stddef.h>.
SourceManager & getSourceManager() const
Definition: Sema.h:1067
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:5818
Expr * getFalseExpr() const
Definition: Expr.h:3332
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition: Expr.h:2063
StringLiteralCheckType
QualType getCanonicalType() const
Definition: Type.h:5298
ObjCLiteralKind
Definition: Sema.h:2431
AbstractConditionalOperator - An abstract base class for ConditionalOperator and BinaryConditionalOpe...
Definition: Expr.h:3128
CanQualType UnsignedLongTy
Definition: ASTContext.h:902
static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call)
bool isObjCQualifiedIdType() const
Definition: Type.h:5568
QualType getIntegerType() const
getIntegerType - Return the integer type this enum decl corresponds to.
Definition: Decl.h:3137
static unsigned RFT(unsigned t, bool shift=false, bool ForceQuad=false)
SourceLocation getLocStart() const LLVM_READONLY
Definition: Expr.cpp:1291
const OptionalAmount & getPrecision() const
Definition: FormatString.h:488
bool isFunctionType() const
Definition: Type.h:5479
const OptionalFlag & hasAlternativeForm() const
Definition: FormatString.h:508
bool isComplete() const
Returns true if this can be considered a complete type.
Definition: Decl.h:3204
static bool isAdditiveOp(Opcode Opc)
Definition: Expr.h:2975
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1528
ObjCInterfaceDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this Objective-C class.
Definition: DeclObjC.h:1815
bool isNDRangeT() const
Definition: Type.h:5619
uint64_t getCharWidth() const
Return the size of the character type, in bits.
Definition: ASTContext.h:1817
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition: Diagnostic.h:78
ObjCInterfaceDecl * NSArrayDecl
The declaration of the Objective-C NSArray class.
Definition: Sema.h:763
SourceLocation getLocEnd() const LLVM_READONLY
Definition: Expr.cpp:1300
unsigned getNumArgs() const
Return the number of actual arguments in this message, not counting the receiver. ...
Definition: ExprObjC.h:1277
SourceLocation getExprLoc() const LLVM_READONLY
Definition: Expr.h:2936
static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, unsigned AbsKind, QualType ArgType)
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat]...
Definition: APValue.h:38
Represents a base class of a C++ class.
Definition: DeclCXX.h:159
ObjCPropertyDecl * getExplicitProperty() const
Definition: ExprObjC.h:633
char __ovld __cnfn max(char x, char y)
Returns y if x < y, otherwise it returns x.
static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex)
checkBuiltinArgument - Given a call to a builtin function, perform normal type-checking on the given ...
ObjCIvarRefExpr - A reference to an ObjC instance variable.
Definition: ExprObjC.h:479
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
Expr * getBase() const
Definition: Expr.h:2405
bool hasNonTrivialObjCLifetime() const
Definition: Type.h:1013
Reading or writing from this object requires a barrier call.
Definition: Type.h:148
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate.h) and friends (in DeclFriend.h).
Expression is a Null pointer constant built from a literal zero.
Definition: Expr.h:675
bool typesAreCompatible(QualType T1, QualType T2, bool CompareUnqualified=false)
Compatibility predicates used to check assignment expressions.
static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, Scope::ScopeFlags NeededScopeFlags, unsigned DiagID)
void DiagnoseEmptyStmtBody(SourceLocation StmtLoc, const Stmt *Body, unsigned DiagID)
Emit DiagID if statement located on StmtLoc has a suspicious null statement as a Body, and it is located on the same line.
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:2315
const OptionalFlag & isLeftJustified() const
Definition: FormatString.h:506
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:5339
bool isClkEventT() const
Definition: Type.h:5611
APFloat & getComplexFloatImag()
Definition: APValue.h:240
unsigned getNumPositiveBits() const
Returns the width in bits required to store all the non-negative enumerators of this enum...
Definition: Decl.h:3163
Represents a C++ struct/union/class.
Definition: DeclCXX.h:263
Compatible - the types are compatible according to the standard.
Definition: Sema.h:8620
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
bool isObjCObjectPointerType() const
Definition: Type.h:5554
Opcode getOpcode() const
Definition: Expr.h:2940
static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr, SourceLocation CallSiteLoc)
ObjCIvarDecl - Represents an ObjC instance variable.
Definition: DeclObjC.h:1849
ArraySizeModifier getSizeModifier() const
Definition: Type.h:2491
WhileStmt - This represents a 'while' stmt.
Definition: Stmt.h:1047
bool isPipeType() const
Definition: Type.h:5634
Builtin::Context & BuiltinInfo
Definition: ASTContext.h:461
QualType getVectorType(QualType VectorType, unsigned NumElts, VectorType::VectorKind VecKind) const
Return the unique reference to a vector type of the specified element type and size.
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string...
Definition: Diagnostic.h:115
This class is used for builtin types like 'int'.
Definition: Type.h:2039
static QualType getSizeOfArgType(const Expr *E)
If E is a sizeof expression, returns its argument type.
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
Definition: CanonicalType.h:70
bool isArrayType() const
Definition: Type.h:5521
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1466
Defines the clang::TargetInfo interface.
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2148
Expr * getRHS() const
Definition: Expr.h:2945
ExprResult ExprError()
Definition: Ownership.h:268
PropertyAttributeKind getPropertyAttributesAsWritten() const
Definition: DeclObjC.h:802
bool isInt() const
Definition: APValue.h:182
CanQualType IntTy
Definition: ASTContext.h:901
void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, SourceLocation OpLoc)
Warn if a value is moved to itself.
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:932
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition: Expr.h:401
virtual bool hasFeature(StringRef Feature) const
Determine whether the given target has the given feature.
ArgType getArgType(ASTContext &Ctx) const
static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl)
QualType getElementType() const
Definition: Type.h:5203
static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall)
Check that the argument to __builtin_addressof is a glvalue, and set the result type to the correspon...
bool ParsePrintfString(FormatStringHandler &H, const char *beg, const char *end, const LangOptions &LO, const TargetInfo &Target, bool isFreeBSDKPrintf)
QualType getElementType() const
Definition: Type.h:2490
SourceManager & SourceMgr
Definition: Sema.h:302
const Expr * getInit(unsigned Init) const
Definition: Expr.h:3785
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition: Diagnostic.h:52
void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS)
checkUnsafeExprAssigns - Check whether +1 expr is being assigned to weak/__unsafe_unretained expressi...
bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS)
checkUnsafeAssigns - Check whether +1 expr is being assigned to weak/__unsafe_unretained type...
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition: Sema/Lookup.h:566
ExprIterator arg_iterator
Definition: ExprCXX.h:1266
#define true
Definition: stdbool.h:32
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:109
static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc)
bool hasValidLengthModifier(const TargetInfo &Target) const
const llvm::fltSemantics & getFloatTypeSemantics(QualType T) const
Return the APFloat 'semantics' for the specified scalar floating point type.
A trivial tuple used to represent a source range.
ASTContext & Context
Definition: Sema.h:299
NamedDecl - This represents a decl with a name.
Definition: Decl.h:213
static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction)
void DiagnoseAlwaysNonNullPointer(Expr *E, Expr::NullPointerConstantKind NullType, bool IsEqual, SourceRange Range)
Diagnose pointers that are always non-null.
CanQualType BoolTy
Definition: ASTContext.h:894
static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, Expr *RHS, bool isProperty)
SourceLocation getLocationOfByte(unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, const TargetInfo &Target, unsigned *StartToken=nullptr, unsigned *StartTokenByteOffset=nullptr) const
getLocationOfByte - Return a source location that points to the specified byte of this string literal...
Definition: Expr.cpp:1009
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char, signed char, short, int, long..], or an enum decl which has a signed representation.
Definition: Type.cpp:1706
APSInt & getInt()
Definition: APValue.h:200
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:5318
bool hasSignedIntegerRepresentation() const
Determine whether this type has an signed integer representation of some sort, e.g., it is an signed integer type or a vector.
Definition: Type.cpp:1736
CanQualType DoubleTy
Definition: ASTContext.h:904
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:665
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:2644
static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall)
Check that the first argument to __builtin_annotation is an integer and the second argument is a non-...
Describes an entity that is being initialized.
static InitializedEntity InitializeParameter(ASTContext &Context, ParmVarDecl *Parm)
Create the initialization entity for a parameter.
NamespaceDecl * getStdNamespace() const
static bool isComparisonOp(Opcode Opc)
Definition: Expr.h:2989
Optional< NullabilityKind > getNullability(const ASTContext &context) const
Determine the nullability of the given type.
Definition: Type.cpp:3480
static Expr * findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner)
Check whether the given argument is a block which captures a variable.
ReceiverKind getReceiverKind() const
Determine the kind of receiver that this message is being sent to.
Definition: ExprObjC.h:1136
static Optional< int > GetNSMutableDictionaryArgumentIndex(Sema &S, ObjCMessageExpr *Message)
static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall)
This class handles loading and caching of source files into memory.
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:2512
unsigned getVectorLength() const
Definition: APValue.h:266
bool isObjC(ID Id)
isObjC - Is this an "ObjC" input (Obj-C and Obj-C++ sources and headers).
Definition: Types.cpp:104
unsigned getNumElements() const
getNumElements - Return number of elements of objective-c dictionary literal.
Definition: ExprObjC.h:307
NullPointerConstantKind
Enumeration used to describe the kind of Null pointer constant returned from isNullPointerConstant()...
Definition: Expr.h:663
Attr - This represents one attribute.
Definition: Attr.h:45
Represents a shadow declaration introduced into a scope by a (resolved) using declaration.
Definition: DeclCXX.h:2835
QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc)
CheckAddressOfOperand - The operand of & must be either a function designator or an lvalue designatin...
Definition: SemaExpr.cpp:10334
CanQualType OCLClkEventTy
Definition: ASTContext.h:917
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:5702
Helper class that creates diagnostics with optional template instantiation stacks.
Definition: Sema.h:1092
Expr * IgnoreParens() LLVM_READONLY
IgnoreParens - Ignore parentheses.
Definition: Expr.cpp:2295
CanQualType UnsignedIntTy
Definition: ASTContext.h:902
bool isLValue() const
Definition: APValue.h:186
Expr * getBase()
An array section can be written only as Base[LowerBound:Length].
Definition: ExprOpenMP.h:82
bool isPointerType() const
Definition: Type.h:5482
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any...
Definition: Decl.cpp:3014