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 
15 #include "clang/Sema/SemaInternal.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/CharUnits.h"
18 #include "clang/AST/DeclCXX.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/EvaluatedExprVisitor.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"
27 #include "clang/Analysis/Analyses/FormatString.h"
28 #include "clang/Basic/CharInfo.h"
29 #include "clang/Basic/TargetBuiltins.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
32 #include "clang/Sema/Initialization.h"
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 
48 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
49                                                     unsigned ByteNo) const {
50   return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
51                                Context.getTargetInfo());
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 
151 static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
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 /// Returns OpenCL access qual.
265 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
266     return D->getAttr<OpenCLAccessAttr>();
267 }
268 
269 /// Returns true if pipe element type is different from the pointer.
270 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
271   const Expr *Arg0 = Call->getArg(0);
272   // First argument type should always be pipe.
273   if (!Arg0->getType()->isPipeType()) {
274     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
275         << Call->getDirectCallee() << Arg0->getSourceRange();
276     return true;
277   }
278   OpenCLAccessAttr *AccessQual =
279       getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
280   // Validates the access qualifier is compatible with the call.
281   // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
282   // read_only and write_only, and assumed to be read_only if no qualifier is
283   // specified.
284   switch (Call->getDirectCallee()->getBuiltinID()) {
285   case Builtin::BIread_pipe:
286   case Builtin::BIreserve_read_pipe:
287   case Builtin::BIcommit_read_pipe:
288   case Builtin::BIwork_group_reserve_read_pipe:
289   case Builtin::BIsub_group_reserve_read_pipe:
290   case Builtin::BIwork_group_commit_read_pipe:
291   case Builtin::BIsub_group_commit_read_pipe:
292     if (!(!AccessQual || AccessQual->isReadOnly())) {
293       S.Diag(Arg0->getLocStart(),
294              diag::err_opencl_builtin_pipe_invalid_access_modifier)
295           << "read_only" << Arg0->getSourceRange();
296       return true;
297     }
298     break;
299   case Builtin::BIwrite_pipe:
300   case Builtin::BIreserve_write_pipe:
301   case Builtin::BIcommit_write_pipe:
302   case Builtin::BIwork_group_reserve_write_pipe:
303   case Builtin::BIsub_group_reserve_write_pipe:
304   case Builtin::BIwork_group_commit_write_pipe:
305   case Builtin::BIsub_group_commit_write_pipe:
306     if (!(AccessQual && AccessQual->isWriteOnly())) {
307       S.Diag(Arg0->getLocStart(),
308              diag::err_opencl_builtin_pipe_invalid_access_modifier)
309           << "write_only" << Arg0->getSourceRange();
310       return true;
311     }
312     break;
313   default:
314     break;
315   }
316   return false;
317 }
318 
319 /// Returns true if pipe element type is different from the pointer.
320 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
321   const Expr *Arg0 = Call->getArg(0);
322   const Expr *ArgIdx = Call->getArg(Idx);
323   const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
324   const QualType EltTy = PipeTy->getElementType();
325   const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
326   // The Idx argument should be a pointer and the type of the pointer and
327   // the type of pipe element should also be the same.
328   if (!ArgTy ||
329       !S.Context.hasSameType(
330           EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
331     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
332         << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
333         << ArgIdx->getType() << ArgIdx->getSourceRange();
334     return true;
335   }
336   return false;
337 }
338 
339 // \brief Performs semantic analysis for the read/write_pipe call.
340 // \param S Reference to the semantic analyzer.
341 // \param Call A pointer to the builtin call.
342 // \return True if a semantic error has been found, false otherwise.
343 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
344   // OpenCL v2.0 s6.13.16.2 - The built-in read/write
345   // functions have two forms.
346   switch (Call->getNumArgs()) {
347   case 2: {
348     if (checkOpenCLPipeArg(S, Call))
349       return true;
350     // The call with 2 arguments should be
351     // read/write_pipe(pipe T, T*).
352     // Check packet type T.
353     if (checkOpenCLPipePacketType(S, Call, 1))
354       return true;
355   } break;
356 
357   case 4: {
358     if (checkOpenCLPipeArg(S, Call))
359       return true;
360     // The call with 4 arguments should be
361     // read/write_pipe(pipe T, reserve_id_t, uint, T*).
362     // Check reserve_id_t.
363     if (!Call->getArg(1)->getType()->isReserveIDT()) {
364       S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
365           << Call->getDirectCallee() << S.Context.OCLReserveIDTy
366           << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
367       return true;
368     }
369 
370     // Check the index.
371     const Expr *Arg2 = Call->getArg(2);
372     if (!Arg2->getType()->isIntegerType() &&
373         !Arg2->getType()->isUnsignedIntegerType()) {
374       S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
375           << Call->getDirectCallee() << S.Context.UnsignedIntTy
376           << Arg2->getType() << Arg2->getSourceRange();
377       return true;
378     }
379 
380     // Check packet type T.
381     if (checkOpenCLPipePacketType(S, Call, 3))
382       return true;
383   } break;
384   default:
385     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num)
386         << Call->getDirectCallee() << Call->getSourceRange();
387     return true;
388   }
389 
390   return false;
391 }
392 
393 // \brief Performs a semantic analysis on the {work_group_/sub_group_
394 //        /_}reserve_{read/write}_pipe
395 // \param S Reference to the semantic analyzer.
396 // \param Call The call to the builtin function to be analyzed.
397 // \return True if a semantic error was found, false otherwise.
398 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
399   if (checkArgCount(S, Call, 2))
400     return true;
401 
402   if (checkOpenCLPipeArg(S, Call))
403     return true;
404 
405   // Check the reserve size.
406   if (!Call->getArg(1)->getType()->isIntegerType() &&
407       !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
408     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
409         << Call->getDirectCallee() << S.Context.UnsignedIntTy
410         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
411     return true;
412   }
413 
414   return false;
415 }
416 
417 // \brief Performs a semantic analysis on {work_group_/sub_group_
418 //        /_}commit_{read/write}_pipe
419 // \param S Reference to the semantic analyzer.
420 // \param Call The call to the builtin function to be analyzed.
421 // \return True if a semantic error was found, false otherwise.
422 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
423   if (checkArgCount(S, Call, 2))
424     return true;
425 
426   if (checkOpenCLPipeArg(S, Call))
427     return true;
428 
429   // Check reserve_id_t.
430   if (!Call->getArg(1)->getType()->isReserveIDT()) {
431     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
432         << Call->getDirectCallee() << S.Context.OCLReserveIDTy
433         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
434     return true;
435   }
436 
437   return false;
438 }
439 
440 // \brief Performs a semantic analysis on the call to built-in Pipe
441 //        Query Functions.
442 // \param S Reference to the semantic analyzer.
443 // \param Call The call to the builtin function to be analyzed.
444 // \return True if a semantic error was found, false otherwise.
445 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
446   if (checkArgCount(S, Call, 1))
447     return true;
448 
449   if (!Call->getArg(0)->getType()->isPipeType()) {
450     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
451         << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
452     return true;
453   }
454 
455   return false;
456 }
457 
458 // \brief Performs semantic analysis for the to_global/local/private call.
459 // \param S Reference to the semantic analyzer.
460 // \param BuiltinID ID of the builtin function.
461 // \param Call A pointer to the builtin call.
462 // \return True if a semantic error has been found, false otherwise.
463 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
464                                     CallExpr *Call) {
465   // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
466   if (S.getLangOpts().OpenCLVersion < 200) {
467     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_requires_version)
468         << Call->getDirectCallee() << "2.0" << 1 << Call->getSourceRange();
469     return true;
470   }
471 
472   if (Call->getNumArgs() != 1) {
473     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_arg_num)
474         << Call->getDirectCallee() << Call->getSourceRange();
475     return true;
476   }
477 
478   auto RT = Call->getArg(0)->getType();
479   if (!RT->isPointerType() || RT->getPointeeType()
480       .getAddressSpace() == LangAS::opencl_constant) {
481     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg)
482         << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
483     return true;
484   }
485 
486   RT = RT->getPointeeType();
487   auto Qual = RT.getQualifiers();
488   switch (BuiltinID) {
489   case Builtin::BIto_global:
490     Qual.setAddressSpace(LangAS::opencl_global);
491     break;
492   case Builtin::BIto_local:
493     Qual.setAddressSpace(LangAS::opencl_local);
494     break;
495   default:
496     Qual.removeAddressSpace();
497   }
498   Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
499       RT.getUnqualifiedType(), Qual)));
500 
501   return false;
502 }
503 
504 ExprResult
505 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
506                                CallExpr *TheCall) {
507   ExprResult TheCallResult(TheCall);
508 
509   // Find out if any arguments are required to be integer constant expressions.
510   unsigned ICEArguments = 0;
511   ASTContext::GetBuiltinTypeError Error;
512   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
513   if (Error != ASTContext::GE_None)
514     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
515 
516   // If any arguments are required to be ICE's, check and diagnose.
517   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
518     // Skip arguments not required to be ICE's.
519     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
520 
521     llvm::APSInt Result;
522     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
523       return true;
524     ICEArguments &= ~(1 << ArgNo);
525   }
526 
527   switch (BuiltinID) {
528   case Builtin::BI__builtin___CFStringMakeConstantString:
529     assert(TheCall->getNumArgs() == 1 &&
530            "Wrong # arguments to builtin CFStringMakeConstantString");
531     if (CheckObjCString(TheCall->getArg(0)))
532       return ExprError();
533     break;
534   case Builtin::BI__builtin_stdarg_start:
535   case Builtin::BI__builtin_va_start:
536     if (SemaBuiltinVAStart(TheCall))
537       return ExprError();
538     break;
539   case Builtin::BI__va_start: {
540     switch (Context.getTargetInfo().getTriple().getArch()) {
541     case llvm::Triple::arm:
542     case llvm::Triple::thumb:
543       if (SemaBuiltinVAStartARM(TheCall))
544         return ExprError();
545       break;
546     default:
547       if (SemaBuiltinVAStart(TheCall))
548         return ExprError();
549       break;
550     }
551     break;
552   }
553   case Builtin::BI__builtin_isgreater:
554   case Builtin::BI__builtin_isgreaterequal:
555   case Builtin::BI__builtin_isless:
556   case Builtin::BI__builtin_islessequal:
557   case Builtin::BI__builtin_islessgreater:
558   case Builtin::BI__builtin_isunordered:
559     if (SemaBuiltinUnorderedCompare(TheCall))
560       return ExprError();
561     break;
562   case Builtin::BI__builtin_fpclassify:
563     if (SemaBuiltinFPClassification(TheCall, 6))
564       return ExprError();
565     break;
566   case Builtin::BI__builtin_isfinite:
567   case Builtin::BI__builtin_isinf:
568   case Builtin::BI__builtin_isinf_sign:
569   case Builtin::BI__builtin_isnan:
570   case Builtin::BI__builtin_isnormal:
571     if (SemaBuiltinFPClassification(TheCall, 1))
572       return ExprError();
573     break;
574   case Builtin::BI__builtin_shufflevector:
575     return SemaBuiltinShuffleVector(TheCall);
576     // TheCall will be freed by the smart pointer here, but that's fine, since
577     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
578   case Builtin::BI__builtin_prefetch:
579     if (SemaBuiltinPrefetch(TheCall))
580       return ExprError();
581     break;
582   case Builtin::BI__assume:
583   case Builtin::BI__builtin_assume:
584     if (SemaBuiltinAssume(TheCall))
585       return ExprError();
586     break;
587   case Builtin::BI__builtin_assume_aligned:
588     if (SemaBuiltinAssumeAligned(TheCall))
589       return ExprError();
590     break;
591   case Builtin::BI__builtin_object_size:
592     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
593       return ExprError();
594     break;
595   case Builtin::BI__builtin_longjmp:
596     if (SemaBuiltinLongjmp(TheCall))
597       return ExprError();
598     break;
599   case Builtin::BI__builtin_setjmp:
600     if (SemaBuiltinSetjmp(TheCall))
601       return ExprError();
602     break;
603   case Builtin::BI_setjmp:
604   case Builtin::BI_setjmpex:
605     if (checkArgCount(*this, TheCall, 1))
606       return true;
607     break;
608 
609   case Builtin::BI__builtin_classify_type:
610     if (checkArgCount(*this, TheCall, 1)) return true;
611     TheCall->setType(Context.IntTy);
612     break;
613   case Builtin::BI__builtin_constant_p:
614     if (checkArgCount(*this, TheCall, 1)) return true;
615     TheCall->setType(Context.IntTy);
616     break;
617   case Builtin::BI__sync_fetch_and_add:
618   case Builtin::BI__sync_fetch_and_add_1:
619   case Builtin::BI__sync_fetch_and_add_2:
620   case Builtin::BI__sync_fetch_and_add_4:
621   case Builtin::BI__sync_fetch_and_add_8:
622   case Builtin::BI__sync_fetch_and_add_16:
623   case Builtin::BI__sync_fetch_and_sub:
624   case Builtin::BI__sync_fetch_and_sub_1:
625   case Builtin::BI__sync_fetch_and_sub_2:
626   case Builtin::BI__sync_fetch_and_sub_4:
627   case Builtin::BI__sync_fetch_and_sub_8:
628   case Builtin::BI__sync_fetch_and_sub_16:
629   case Builtin::BI__sync_fetch_and_or:
630   case Builtin::BI__sync_fetch_and_or_1:
631   case Builtin::BI__sync_fetch_and_or_2:
632   case Builtin::BI__sync_fetch_and_or_4:
633   case Builtin::BI__sync_fetch_and_or_8:
634   case Builtin::BI__sync_fetch_and_or_16:
635   case Builtin::BI__sync_fetch_and_and:
636   case Builtin::BI__sync_fetch_and_and_1:
637   case Builtin::BI__sync_fetch_and_and_2:
638   case Builtin::BI__sync_fetch_and_and_4:
639   case Builtin::BI__sync_fetch_and_and_8:
640   case Builtin::BI__sync_fetch_and_and_16:
641   case Builtin::BI__sync_fetch_and_xor:
642   case Builtin::BI__sync_fetch_and_xor_1:
643   case Builtin::BI__sync_fetch_and_xor_2:
644   case Builtin::BI__sync_fetch_and_xor_4:
645   case Builtin::BI__sync_fetch_and_xor_8:
646   case Builtin::BI__sync_fetch_and_xor_16:
647   case Builtin::BI__sync_fetch_and_nand:
648   case Builtin::BI__sync_fetch_and_nand_1:
649   case Builtin::BI__sync_fetch_and_nand_2:
650   case Builtin::BI__sync_fetch_and_nand_4:
651   case Builtin::BI__sync_fetch_and_nand_8:
652   case Builtin::BI__sync_fetch_and_nand_16:
653   case Builtin::BI__sync_add_and_fetch:
654   case Builtin::BI__sync_add_and_fetch_1:
655   case Builtin::BI__sync_add_and_fetch_2:
656   case Builtin::BI__sync_add_and_fetch_4:
657   case Builtin::BI__sync_add_and_fetch_8:
658   case Builtin::BI__sync_add_and_fetch_16:
659   case Builtin::BI__sync_sub_and_fetch:
660   case Builtin::BI__sync_sub_and_fetch_1:
661   case Builtin::BI__sync_sub_and_fetch_2:
662   case Builtin::BI__sync_sub_and_fetch_4:
663   case Builtin::BI__sync_sub_and_fetch_8:
664   case Builtin::BI__sync_sub_and_fetch_16:
665   case Builtin::BI__sync_and_and_fetch:
666   case Builtin::BI__sync_and_and_fetch_1:
667   case Builtin::BI__sync_and_and_fetch_2:
668   case Builtin::BI__sync_and_and_fetch_4:
669   case Builtin::BI__sync_and_and_fetch_8:
670   case Builtin::BI__sync_and_and_fetch_16:
671   case Builtin::BI__sync_or_and_fetch:
672   case Builtin::BI__sync_or_and_fetch_1:
673   case Builtin::BI__sync_or_and_fetch_2:
674   case Builtin::BI__sync_or_and_fetch_4:
675   case Builtin::BI__sync_or_and_fetch_8:
676   case Builtin::BI__sync_or_and_fetch_16:
677   case Builtin::BI__sync_xor_and_fetch:
678   case Builtin::BI__sync_xor_and_fetch_1:
679   case Builtin::BI__sync_xor_and_fetch_2:
680   case Builtin::BI__sync_xor_and_fetch_4:
681   case Builtin::BI__sync_xor_and_fetch_8:
682   case Builtin::BI__sync_xor_and_fetch_16:
683   case Builtin::BI__sync_nand_and_fetch:
684   case Builtin::BI__sync_nand_and_fetch_1:
685   case Builtin::BI__sync_nand_and_fetch_2:
686   case Builtin::BI__sync_nand_and_fetch_4:
687   case Builtin::BI__sync_nand_and_fetch_8:
688   case Builtin::BI__sync_nand_and_fetch_16:
689   case Builtin::BI__sync_val_compare_and_swap:
690   case Builtin::BI__sync_val_compare_and_swap_1:
691   case Builtin::BI__sync_val_compare_and_swap_2:
692   case Builtin::BI__sync_val_compare_and_swap_4:
693   case Builtin::BI__sync_val_compare_and_swap_8:
694   case Builtin::BI__sync_val_compare_and_swap_16:
695   case Builtin::BI__sync_bool_compare_and_swap:
696   case Builtin::BI__sync_bool_compare_and_swap_1:
697   case Builtin::BI__sync_bool_compare_and_swap_2:
698   case Builtin::BI__sync_bool_compare_and_swap_4:
699   case Builtin::BI__sync_bool_compare_and_swap_8:
700   case Builtin::BI__sync_bool_compare_and_swap_16:
701   case Builtin::BI__sync_lock_test_and_set:
702   case Builtin::BI__sync_lock_test_and_set_1:
703   case Builtin::BI__sync_lock_test_and_set_2:
704   case Builtin::BI__sync_lock_test_and_set_4:
705   case Builtin::BI__sync_lock_test_and_set_8:
706   case Builtin::BI__sync_lock_test_and_set_16:
707   case Builtin::BI__sync_lock_release:
708   case Builtin::BI__sync_lock_release_1:
709   case Builtin::BI__sync_lock_release_2:
710   case Builtin::BI__sync_lock_release_4:
711   case Builtin::BI__sync_lock_release_8:
712   case Builtin::BI__sync_lock_release_16:
713   case Builtin::BI__sync_swap:
714   case Builtin::BI__sync_swap_1:
715   case Builtin::BI__sync_swap_2:
716   case Builtin::BI__sync_swap_4:
717   case Builtin::BI__sync_swap_8:
718   case Builtin::BI__sync_swap_16:
719     return SemaBuiltinAtomicOverloaded(TheCallResult);
720   case Builtin::BI__builtin_nontemporal_load:
721   case Builtin::BI__builtin_nontemporal_store:
722     return SemaBuiltinNontemporalOverloaded(TheCallResult);
723 #define BUILTIN(ID, TYPE, ATTRS)
724 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
725   case Builtin::BI##ID: \
726     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
727 #include "clang/Basic/Builtins.def"
728   case Builtin::BI__builtin_annotation:
729     if (SemaBuiltinAnnotation(*this, TheCall))
730       return ExprError();
731     break;
732   case Builtin::BI__builtin_addressof:
733     if (SemaBuiltinAddressof(*this, TheCall))
734       return ExprError();
735     break;
736   case Builtin::BI__builtin_add_overflow:
737   case Builtin::BI__builtin_sub_overflow:
738   case Builtin::BI__builtin_mul_overflow:
739     if (SemaBuiltinOverflow(*this, TheCall))
740       return ExprError();
741     break;
742   case Builtin::BI__builtin_operator_new:
743   case Builtin::BI__builtin_operator_delete:
744     if (!getLangOpts().CPlusPlus) {
745       Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
746         << (BuiltinID == Builtin::BI__builtin_operator_new
747                 ? "__builtin_operator_new"
748                 : "__builtin_operator_delete")
749         << "C++";
750       return ExprError();
751     }
752     // CodeGen assumes it can find the global new and delete to call,
753     // so ensure that they are declared.
754     DeclareGlobalNewDelete();
755     break;
756 
757   // check secure string manipulation functions where overflows
758   // are detectable at compile time
759   case Builtin::BI__builtin___memcpy_chk:
760   case Builtin::BI__builtin___memmove_chk:
761   case Builtin::BI__builtin___memset_chk:
762   case Builtin::BI__builtin___strlcat_chk:
763   case Builtin::BI__builtin___strlcpy_chk:
764   case Builtin::BI__builtin___strncat_chk:
765   case Builtin::BI__builtin___strncpy_chk:
766   case Builtin::BI__builtin___stpncpy_chk:
767     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
768     break;
769   case Builtin::BI__builtin___memccpy_chk:
770     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
771     break;
772   case Builtin::BI__builtin___snprintf_chk:
773   case Builtin::BI__builtin___vsnprintf_chk:
774     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
775     break;
776   case Builtin::BI__builtin_call_with_static_chain:
777     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
778       return ExprError();
779     break;
780   case Builtin::BI__exception_code:
781   case Builtin::BI_exception_code:
782     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
783                                  diag::err_seh___except_block))
784       return ExprError();
785     break;
786   case Builtin::BI__exception_info:
787   case Builtin::BI_exception_info:
788     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
789                                  diag::err_seh___except_filter))
790       return ExprError();
791     break;
792   case Builtin::BI__GetExceptionInfo:
793     if (checkArgCount(*this, TheCall, 1))
794       return ExprError();
795 
796     if (CheckCXXThrowOperand(
797             TheCall->getLocStart(),
798             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
799             TheCall))
800       return ExprError();
801 
802     TheCall->setType(Context.VoidPtrTy);
803     break;
804   case Builtin::BIread_pipe:
805   case Builtin::BIwrite_pipe:
806     // Since those two functions are declared with var args, we need a semantic
807     // check for the argument.
808     if (SemaBuiltinRWPipe(*this, TheCall))
809       return ExprError();
810     break;
811   case Builtin::BIreserve_read_pipe:
812   case Builtin::BIreserve_write_pipe:
813   case Builtin::BIwork_group_reserve_read_pipe:
814   case Builtin::BIwork_group_reserve_write_pipe:
815   case Builtin::BIsub_group_reserve_read_pipe:
816   case Builtin::BIsub_group_reserve_write_pipe:
817     if (SemaBuiltinReserveRWPipe(*this, TheCall))
818       return ExprError();
819     // Since return type of reserve_read/write_pipe built-in function is
820     // reserve_id_t, which is not defined in the builtin def file , we used int
821     // as return type and need to override the return type of these functions.
822     TheCall->setType(Context.OCLReserveIDTy);
823     break;
824   case Builtin::BIcommit_read_pipe:
825   case Builtin::BIcommit_write_pipe:
826   case Builtin::BIwork_group_commit_read_pipe:
827   case Builtin::BIwork_group_commit_write_pipe:
828   case Builtin::BIsub_group_commit_read_pipe:
829   case Builtin::BIsub_group_commit_write_pipe:
830     if (SemaBuiltinCommitRWPipe(*this, TheCall))
831       return ExprError();
832     break;
833   case Builtin::BIget_pipe_num_packets:
834   case Builtin::BIget_pipe_max_packets:
835     if (SemaBuiltinPipePackets(*this, TheCall))
836       return ExprError();
837     break;
838   case Builtin::BIto_global:
839   case Builtin::BIto_local:
840   case Builtin::BIto_private:
841     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
842       return ExprError();
843     break;
844   }
845 
846   // Since the target specific builtins for each arch overlap, only check those
847   // of the arch we are compiling for.
848   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
849     switch (Context.getTargetInfo().getTriple().getArch()) {
850       case llvm::Triple::arm:
851       case llvm::Triple::armeb:
852       case llvm::Triple::thumb:
853       case llvm::Triple::thumbeb:
854         if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
855           return ExprError();
856         break;
857       case llvm::Triple::aarch64:
858       case llvm::Triple::aarch64_be:
859         if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
860           return ExprError();
861         break;
862       case llvm::Triple::mips:
863       case llvm::Triple::mipsel:
864       case llvm::Triple::mips64:
865       case llvm::Triple::mips64el:
866         if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
867           return ExprError();
868         break;
869       case llvm::Triple::systemz:
870         if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
871           return ExprError();
872         break;
873       case llvm::Triple::x86:
874       case llvm::Triple::x86_64:
875         if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
876           return ExprError();
877         break;
878       case llvm::Triple::ppc:
879       case llvm::Triple::ppc64:
880       case llvm::Triple::ppc64le:
881         if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
882           return ExprError();
883         break;
884       default:
885         break;
886     }
887   }
888 
889   return TheCallResult;
890 }
891 
892 // Get the valid immediate range for the specified NEON type code.
893 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
894   NeonTypeFlags Type(t);
895   int IsQuad = ForceQuad ? true : Type.isQuad();
896   switch (Type.getEltType()) {
897   case NeonTypeFlags::Int8:
898   case NeonTypeFlags::Poly8:
899     return shift ? 7 : (8 << IsQuad) - 1;
900   case NeonTypeFlags::Int16:
901   case NeonTypeFlags::Poly16:
902     return shift ? 15 : (4 << IsQuad) - 1;
903   case NeonTypeFlags::Int32:
904     return shift ? 31 : (2 << IsQuad) - 1;
905   case NeonTypeFlags::Int64:
906   case NeonTypeFlags::Poly64:
907     return shift ? 63 : (1 << IsQuad) - 1;
908   case NeonTypeFlags::Poly128:
909     return shift ? 127 : (1 << IsQuad) - 1;
910   case NeonTypeFlags::Float16:
911     assert(!shift && "cannot shift float types!");
912     return (4 << IsQuad) - 1;
913   case NeonTypeFlags::Float32:
914     assert(!shift && "cannot shift float types!");
915     return (2 << IsQuad) - 1;
916   case NeonTypeFlags::Float64:
917     assert(!shift && "cannot shift float types!");
918     return (1 << IsQuad) - 1;
919   }
920   llvm_unreachable("Invalid NeonTypeFlag!");
921 }
922 
923 /// getNeonEltType - Return the QualType corresponding to the elements of
924 /// the vector type specified by the NeonTypeFlags.  This is used to check
925 /// the pointer arguments for Neon load/store intrinsics.
926 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
927                                bool IsPolyUnsigned, bool IsInt64Long) {
928   switch (Flags.getEltType()) {
929   case NeonTypeFlags::Int8:
930     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
931   case NeonTypeFlags::Int16:
932     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
933   case NeonTypeFlags::Int32:
934     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
935   case NeonTypeFlags::Int64:
936     if (IsInt64Long)
937       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
938     else
939       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
940                                 : Context.LongLongTy;
941   case NeonTypeFlags::Poly8:
942     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
943   case NeonTypeFlags::Poly16:
944     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
945   case NeonTypeFlags::Poly64:
946     if (IsInt64Long)
947       return Context.UnsignedLongTy;
948     else
949       return Context.UnsignedLongLongTy;
950   case NeonTypeFlags::Poly128:
951     break;
952   case NeonTypeFlags::Float16:
953     return Context.HalfTy;
954   case NeonTypeFlags::Float32:
955     return Context.FloatTy;
956   case NeonTypeFlags::Float64:
957     return Context.DoubleTy;
958   }
959   llvm_unreachable("Invalid NeonTypeFlag!");
960 }
961 
962 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
963   llvm::APSInt Result;
964   uint64_t mask = 0;
965   unsigned TV = 0;
966   int PtrArgNum = -1;
967   bool HasConstPtr = false;
968   switch (BuiltinID) {
969 #define GET_NEON_OVERLOAD_CHECK
970 #include "clang/Basic/arm_neon.inc"
971 #undef GET_NEON_OVERLOAD_CHECK
972   }
973 
974   // For NEON intrinsics which are overloaded on vector element type, validate
975   // the immediate which specifies which variant to emit.
976   unsigned ImmArg = TheCall->getNumArgs()-1;
977   if (mask) {
978     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
979       return true;
980 
981     TV = Result.getLimitedValue(64);
982     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
983       return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
984         << TheCall->getArg(ImmArg)->getSourceRange();
985   }
986 
987   if (PtrArgNum >= 0) {
988     // Check that pointer arguments have the specified type.
989     Expr *Arg = TheCall->getArg(PtrArgNum);
990     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
991       Arg = ICE->getSubExpr();
992     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
993     QualType RHSTy = RHS.get()->getType();
994 
995     llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
996     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64;
997     bool IsInt64Long =
998         Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
999     QualType EltTy =
1000         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
1001     if (HasConstPtr)
1002       EltTy = EltTy.withConst();
1003     QualType LHSTy = Context.getPointerType(EltTy);
1004     AssignConvertType ConvTy;
1005     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1006     if (RHS.isInvalid())
1007       return true;
1008     if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
1009                                  RHS.get(), AA_Assigning))
1010       return true;
1011   }
1012 
1013   // For NEON intrinsics which take an immediate value as part of the
1014   // instruction, range check them here.
1015   unsigned i = 0, l = 0, u = 0;
1016   switch (BuiltinID) {
1017   default:
1018     return false;
1019 #define GET_NEON_IMMEDIATE_CHECK
1020 #include "clang/Basic/arm_neon.inc"
1021 #undef GET_NEON_IMMEDIATE_CHECK
1022   }
1023 
1024   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1025 }
1026 
1027 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1028                                         unsigned MaxWidth) {
1029   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
1030           BuiltinID == ARM::BI__builtin_arm_ldaex ||
1031           BuiltinID == ARM::BI__builtin_arm_strex ||
1032           BuiltinID == ARM::BI__builtin_arm_stlex ||
1033           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1034           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1035           BuiltinID == AArch64::BI__builtin_arm_strex ||
1036           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
1037          "unexpected ARM builtin");
1038   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
1039                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
1040                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1041                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
1042 
1043   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1044 
1045   // Ensure that we have the proper number of arguments.
1046   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1047     return true;
1048 
1049   // Inspect the pointer argument of the atomic builtin.  This should always be
1050   // a pointer type, whose element is an integral scalar or pointer type.
1051   // Because it is a pointer type, we don't have to worry about any implicit
1052   // casts here.
1053   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1054   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1055   if (PointerArgRes.isInvalid())
1056     return true;
1057   PointerArg = PointerArgRes.get();
1058 
1059   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1060   if (!pointerType) {
1061     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1062       << PointerArg->getType() << PointerArg->getSourceRange();
1063     return true;
1064   }
1065 
1066   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1067   // task is to insert the appropriate casts into the AST. First work out just
1068   // what the appropriate type is.
1069   QualType ValType = pointerType->getPointeeType();
1070   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1071   if (IsLdrex)
1072     AddrType.addConst();
1073 
1074   // Issue a warning if the cast is dodgy.
1075   CastKind CastNeeded = CK_NoOp;
1076   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1077     CastNeeded = CK_BitCast;
1078     Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
1079       << PointerArg->getType()
1080       << Context.getPointerType(AddrType)
1081       << AA_Passing << PointerArg->getSourceRange();
1082   }
1083 
1084   // Finally, do the cast and replace the argument with the corrected version.
1085   AddrType = Context.getPointerType(AddrType);
1086   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1087   if (PointerArgRes.isInvalid())
1088     return true;
1089   PointerArg = PointerArgRes.get();
1090 
1091   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1092 
1093   // In general, we allow ints, floats and pointers to be loaded and stored.
1094   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1095       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1096     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1097       << PointerArg->getType() << PointerArg->getSourceRange();
1098     return true;
1099   }
1100 
1101   // But ARM doesn't have instructions to deal with 128-bit versions.
1102   if (Context.getTypeSize(ValType) > MaxWidth) {
1103     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
1104     Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
1105       << PointerArg->getType() << PointerArg->getSourceRange();
1106     return true;
1107   }
1108 
1109   switch (ValType.getObjCLifetime()) {
1110   case Qualifiers::OCL_None:
1111   case Qualifiers::OCL_ExplicitNone:
1112     // okay
1113     break;
1114 
1115   case Qualifiers::OCL_Weak:
1116   case Qualifiers::OCL_Strong:
1117   case Qualifiers::OCL_Autoreleasing:
1118     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1119       << ValType << PointerArg->getSourceRange();
1120     return true;
1121   }
1122 
1123   if (IsLdrex) {
1124     TheCall->setType(ValType);
1125     return false;
1126   }
1127 
1128   // Initialize the argument to be stored.
1129   ExprResult ValArg = TheCall->getArg(0);
1130   InitializedEntity Entity = InitializedEntity::InitializeParameter(
1131       Context, ValType, /*consume*/ false);
1132   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1133   if (ValArg.isInvalid())
1134     return true;
1135   TheCall->setArg(0, ValArg.get());
1136 
1137   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1138   // but the custom checker bypasses all default analysis.
1139   TheCall->setType(Context.IntTy);
1140   return false;
1141 }
1142 
1143 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1144   llvm::APSInt Result;
1145 
1146   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
1147       BuiltinID == ARM::BI__builtin_arm_ldaex ||
1148       BuiltinID == ARM::BI__builtin_arm_strex ||
1149       BuiltinID == ARM::BI__builtin_arm_stlex) {
1150     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
1151   }
1152 
1153   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1154     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1155       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1156   }
1157 
1158   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1159       BuiltinID == ARM::BI__builtin_arm_wsr64)
1160     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1161 
1162   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1163       BuiltinID == ARM::BI__builtin_arm_rsrp ||
1164       BuiltinID == ARM::BI__builtin_arm_wsr ||
1165       BuiltinID == ARM::BI__builtin_arm_wsrp)
1166     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1167 
1168   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1169     return true;
1170 
1171   // For intrinsics which take an immediate value as part of the instruction,
1172   // range check them here.
1173   unsigned i = 0, l = 0, u = 0;
1174   switch (BuiltinID) {
1175   default: return false;
1176   case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
1177   case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
1178   case ARM::BI__builtin_arm_vcvtr_f:
1179   case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
1180   case ARM::BI__builtin_arm_dmb:
1181   case ARM::BI__builtin_arm_dsb:
1182   case ARM::BI__builtin_arm_isb:
1183   case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
1184   }
1185 
1186   // FIXME: VFP Intrinsics should error if VFP not present.
1187   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1188 }
1189 
1190 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
1191                                          CallExpr *TheCall) {
1192   llvm::APSInt Result;
1193 
1194   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1195       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1196       BuiltinID == AArch64::BI__builtin_arm_strex ||
1197       BuiltinID == AArch64::BI__builtin_arm_stlex) {
1198     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1199   }
1200 
1201   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1202     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1203       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1204       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1205       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1206   }
1207 
1208   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1209       BuiltinID == AArch64::BI__builtin_arm_wsr64)
1210     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1211 
1212   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1213       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1214       BuiltinID == AArch64::BI__builtin_arm_wsr ||
1215       BuiltinID == AArch64::BI__builtin_arm_wsrp)
1216     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1217 
1218   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1219     return true;
1220 
1221   // For intrinsics which take an immediate value as part of the instruction,
1222   // range check them here.
1223   unsigned i = 0, l = 0, u = 0;
1224   switch (BuiltinID) {
1225   default: return false;
1226   case AArch64::BI__builtin_arm_dmb:
1227   case AArch64::BI__builtin_arm_dsb:
1228   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1229   }
1230 
1231   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1232 }
1233 
1234 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1235   unsigned i = 0, l = 0, u = 0;
1236   switch (BuiltinID) {
1237   default: return false;
1238   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
1239   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
1240   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
1241   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
1242   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
1243   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
1244   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
1245   }
1246 
1247   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1248 }
1249 
1250 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1251   unsigned i = 0, l = 0, u = 0;
1252   bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
1253                       BuiltinID == PPC::BI__builtin_divdeu ||
1254                       BuiltinID == PPC::BI__builtin_bpermd;
1255   bool IsTarget64Bit = Context.getTargetInfo()
1256                               .getTypeWidth(Context
1257                                             .getTargetInfo()
1258                                             .getIntPtrType()) == 64;
1259   bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
1260                        BuiltinID == PPC::BI__builtin_divweu ||
1261                        BuiltinID == PPC::BI__builtin_divde ||
1262                        BuiltinID == PPC::BI__builtin_divdeu;
1263 
1264   if (Is64BitBltin && !IsTarget64Bit)
1265       return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
1266              << TheCall->getSourceRange();
1267 
1268   if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
1269       (BuiltinID == PPC::BI__builtin_bpermd &&
1270        !Context.getTargetInfo().hasFeature("bpermd")))
1271     return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
1272            << TheCall->getSourceRange();
1273 
1274   switch (BuiltinID) {
1275   default: return false;
1276   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
1277   case PPC::BI__builtin_altivec_crypto_vshasigmad:
1278     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1279            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1280   case PPC::BI__builtin_tbegin:
1281   case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
1282   case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
1283   case PPC::BI__builtin_tabortwc:
1284   case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
1285   case PPC::BI__builtin_tabortwci:
1286   case PPC::BI__builtin_tabortdci:
1287     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
1288            SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
1289   }
1290   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1291 }
1292 
1293 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
1294                                            CallExpr *TheCall) {
1295   if (BuiltinID == SystemZ::BI__builtin_tabort) {
1296     Expr *Arg = TheCall->getArg(0);
1297     llvm::APSInt AbortCode(32);
1298     if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
1299         AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
1300       return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
1301              << Arg->getSourceRange();
1302   }
1303 
1304   // For intrinsics which take an immediate value as part of the instruction,
1305   // range check them here.
1306   unsigned i = 0, l = 0, u = 0;
1307   switch (BuiltinID) {
1308   default: return false;
1309   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
1310   case SystemZ::BI__builtin_s390_verimb:
1311   case SystemZ::BI__builtin_s390_verimh:
1312   case SystemZ::BI__builtin_s390_verimf:
1313   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
1314   case SystemZ::BI__builtin_s390_vfaeb:
1315   case SystemZ::BI__builtin_s390_vfaeh:
1316   case SystemZ::BI__builtin_s390_vfaef:
1317   case SystemZ::BI__builtin_s390_vfaebs:
1318   case SystemZ::BI__builtin_s390_vfaehs:
1319   case SystemZ::BI__builtin_s390_vfaefs:
1320   case SystemZ::BI__builtin_s390_vfaezb:
1321   case SystemZ::BI__builtin_s390_vfaezh:
1322   case SystemZ::BI__builtin_s390_vfaezf:
1323   case SystemZ::BI__builtin_s390_vfaezbs:
1324   case SystemZ::BI__builtin_s390_vfaezhs:
1325   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
1326   case SystemZ::BI__builtin_s390_vfidb:
1327     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1328            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1329   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
1330   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
1331   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
1332   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
1333   case SystemZ::BI__builtin_s390_vstrcb:
1334   case SystemZ::BI__builtin_s390_vstrch:
1335   case SystemZ::BI__builtin_s390_vstrcf:
1336   case SystemZ::BI__builtin_s390_vstrczb:
1337   case SystemZ::BI__builtin_s390_vstrczh:
1338   case SystemZ::BI__builtin_s390_vstrczf:
1339   case SystemZ::BI__builtin_s390_vstrcbs:
1340   case SystemZ::BI__builtin_s390_vstrchs:
1341   case SystemZ::BI__builtin_s390_vstrcfs:
1342   case SystemZ::BI__builtin_s390_vstrczbs:
1343   case SystemZ::BI__builtin_s390_vstrczhs:
1344   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
1345   }
1346   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1347 }
1348 
1349 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
1350 /// This checks that the target supports __builtin_cpu_supports and
1351 /// that the string argument is constant and valid.
1352 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
1353   Expr *Arg = TheCall->getArg(0);
1354 
1355   // Check if the argument is a string literal.
1356   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1357     return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1358            << Arg->getSourceRange();
1359 
1360   // Check the contents of the string.
1361   StringRef Feature =
1362       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1363   if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
1364     return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
1365            << Arg->getSourceRange();
1366   return false;
1367 }
1368 
1369 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1370   int i = 0, l = 0, u = 0;
1371   switch (BuiltinID) {
1372   default:
1373     return false;
1374   case X86::BI__builtin_cpu_supports:
1375     return SemaBuiltinCpuSupports(*this, TheCall);
1376   case X86::BI__builtin_ms_va_start:
1377     return SemaBuiltinMSVAStart(TheCall);
1378   case X86::BI__builtin_ia32_extractf64x4_mask:
1379   case X86::BI__builtin_ia32_extracti64x4_mask:
1380   case X86::BI__builtin_ia32_extractf32x8_mask:
1381   case X86::BI__builtin_ia32_extracti32x8_mask:
1382   case X86::BI__builtin_ia32_extractf64x2_256_mask:
1383   case X86::BI__builtin_ia32_extracti64x2_256_mask:
1384   case X86::BI__builtin_ia32_extractf32x4_256_mask:
1385   case X86::BI__builtin_ia32_extracti32x4_256_mask:
1386     i = 1; l = 0; u = 1;
1387     break;
1388   case X86::BI_mm_prefetch:
1389   case X86::BI__builtin_ia32_extractf32x4_mask:
1390   case X86::BI__builtin_ia32_extracti32x4_mask:
1391   case X86::BI__builtin_ia32_vpermilpd_mask:
1392   case X86::BI__builtin_ia32_vpermilps_mask:
1393   case X86::BI__builtin_ia32_extractf64x2_512_mask:
1394   case X86::BI__builtin_ia32_extracti64x2_512_mask:
1395     i = 1; l = 0; u = 3;
1396     break;
1397   case X86::BI__builtin_ia32_insertf32x8_mask:
1398   case X86::BI__builtin_ia32_inserti32x8_mask:
1399   case X86::BI__builtin_ia32_insertf64x4_mask:
1400   case X86::BI__builtin_ia32_inserti64x4_mask:
1401   case X86::BI__builtin_ia32_insertf64x2_256_mask:
1402   case X86::BI__builtin_ia32_inserti64x2_256_mask:
1403   case X86::BI__builtin_ia32_insertf32x4_256_mask:
1404   case X86::BI__builtin_ia32_inserti32x4_256_mask:
1405     i = 2; l = 0; u = 1;
1406     break;
1407   case X86::BI__builtin_ia32_sha1rnds4:
1408   case X86::BI__builtin_ia32_shuf_f32x4_256_mask:
1409   case X86::BI__builtin_ia32_shuf_f64x2_256_mask:
1410   case X86::BI__builtin_ia32_shuf_i32x4_256_mask:
1411   case X86::BI__builtin_ia32_shuf_i64x2_256_mask:
1412   case X86::BI__builtin_ia32_shufpd128_mask:
1413   case X86::BI__builtin_ia32_insertf64x2_512_mask:
1414   case X86::BI__builtin_ia32_inserti64x2_512_mask:
1415   case X86::BI__builtin_ia32_insertf32x4_mask:
1416   case X86::BI__builtin_ia32_inserti32x4_mask:
1417     i = 2; l = 0; u = 3;
1418     break;
1419   case X86::BI__builtin_ia32_vpermil2pd:
1420   case X86::BI__builtin_ia32_vpermil2pd256:
1421   case X86::BI__builtin_ia32_vpermil2ps:
1422   case X86::BI__builtin_ia32_vpermil2ps256:
1423     i = 3; l = 0; u = 3;
1424     break;
1425   case X86::BI__builtin_ia32_cmpb128_mask:
1426   case X86::BI__builtin_ia32_cmpw128_mask:
1427   case X86::BI__builtin_ia32_cmpd128_mask:
1428   case X86::BI__builtin_ia32_cmpq128_mask:
1429   case X86::BI__builtin_ia32_cmpb256_mask:
1430   case X86::BI__builtin_ia32_cmpw256_mask:
1431   case X86::BI__builtin_ia32_cmpd256_mask:
1432   case X86::BI__builtin_ia32_cmpq256_mask:
1433   case X86::BI__builtin_ia32_cmpb512_mask:
1434   case X86::BI__builtin_ia32_cmpw512_mask:
1435   case X86::BI__builtin_ia32_cmpd512_mask:
1436   case X86::BI__builtin_ia32_cmpq512_mask:
1437   case X86::BI__builtin_ia32_ucmpb128_mask:
1438   case X86::BI__builtin_ia32_ucmpw128_mask:
1439   case X86::BI__builtin_ia32_ucmpd128_mask:
1440   case X86::BI__builtin_ia32_ucmpq128_mask:
1441   case X86::BI__builtin_ia32_ucmpb256_mask:
1442   case X86::BI__builtin_ia32_ucmpw256_mask:
1443   case X86::BI__builtin_ia32_ucmpd256_mask:
1444   case X86::BI__builtin_ia32_ucmpq256_mask:
1445   case X86::BI__builtin_ia32_ucmpb512_mask:
1446   case X86::BI__builtin_ia32_ucmpw512_mask:
1447   case X86::BI__builtin_ia32_ucmpd512_mask:
1448   case X86::BI__builtin_ia32_ucmpq512_mask:
1449   case X86::BI__builtin_ia32_vpcomub:
1450   case X86::BI__builtin_ia32_vpcomuw:
1451   case X86::BI__builtin_ia32_vpcomud:
1452   case X86::BI__builtin_ia32_vpcomuq:
1453   case X86::BI__builtin_ia32_vpcomb:
1454   case X86::BI__builtin_ia32_vpcomw:
1455   case X86::BI__builtin_ia32_vpcomd:
1456   case X86::BI__builtin_ia32_vpcomq:
1457     i = 2; l = 0; u = 7;
1458     break;
1459   case X86::BI__builtin_ia32_roundps:
1460   case X86::BI__builtin_ia32_roundpd:
1461   case X86::BI__builtin_ia32_roundps256:
1462   case X86::BI__builtin_ia32_roundpd256:
1463   case X86::BI__builtin_ia32_vpermilpd256_mask:
1464   case X86::BI__builtin_ia32_vpermilps256_mask:
1465     i = 1; l = 0; u = 15;
1466     break;
1467   case X86::BI__builtin_ia32_roundss:
1468   case X86::BI__builtin_ia32_roundsd:
1469   case X86::BI__builtin_ia32_rangepd128_mask:
1470   case X86::BI__builtin_ia32_rangepd256_mask:
1471   case X86::BI__builtin_ia32_rangepd512_mask:
1472   case X86::BI__builtin_ia32_rangeps128_mask:
1473   case X86::BI__builtin_ia32_rangeps256_mask:
1474   case X86::BI__builtin_ia32_rangeps512_mask:
1475   case X86::BI__builtin_ia32_getmantsd_round_mask:
1476   case X86::BI__builtin_ia32_getmantss_round_mask:
1477   case X86::BI__builtin_ia32_shufpd256_mask:
1478     i = 2; l = 0; u = 15;
1479     break;
1480   case X86::BI__builtin_ia32_cmpps:
1481   case X86::BI__builtin_ia32_cmpss:
1482   case X86::BI__builtin_ia32_cmppd:
1483   case X86::BI__builtin_ia32_cmpsd:
1484   case X86::BI__builtin_ia32_cmpps256:
1485   case X86::BI__builtin_ia32_cmppd256:
1486   case X86::BI__builtin_ia32_cmpps128_mask:
1487   case X86::BI__builtin_ia32_cmppd128_mask:
1488   case X86::BI__builtin_ia32_cmpps256_mask:
1489   case X86::BI__builtin_ia32_cmppd256_mask:
1490   case X86::BI__builtin_ia32_cmpps512_mask:
1491   case X86::BI__builtin_ia32_cmppd512_mask:
1492   case X86::BI__builtin_ia32_cmpsd_mask:
1493   case X86::BI__builtin_ia32_cmpss_mask:
1494     i = 2; l = 0; u = 31;
1495     break;
1496   case X86::BI__builtin_ia32_xabort:
1497     i = 0; l = -128; u = 255;
1498     break;
1499   case X86::BI__builtin_ia32_pshufw:
1500   case X86::BI__builtin_ia32_aeskeygenassist128:
1501     i = 1; l = -128; u = 255;
1502     break;
1503   case X86::BI__builtin_ia32_vcvtps2ph:
1504   case X86::BI__builtin_ia32_vcvtps2ph256:
1505   case X86::BI__builtin_ia32_vcvtps2ph512:
1506   case X86::BI__builtin_ia32_rndscaleps_128_mask:
1507   case X86::BI__builtin_ia32_rndscalepd_128_mask:
1508   case X86::BI__builtin_ia32_rndscaleps_256_mask:
1509   case X86::BI__builtin_ia32_rndscalepd_256_mask:
1510   case X86::BI__builtin_ia32_rndscaleps_mask:
1511   case X86::BI__builtin_ia32_rndscalepd_mask:
1512   case X86::BI__builtin_ia32_reducepd128_mask:
1513   case X86::BI__builtin_ia32_reducepd256_mask:
1514   case X86::BI__builtin_ia32_reducepd512_mask:
1515   case X86::BI__builtin_ia32_reduceps128_mask:
1516   case X86::BI__builtin_ia32_reduceps256_mask:
1517   case X86::BI__builtin_ia32_reduceps512_mask:
1518   case X86::BI__builtin_ia32_prold512_mask:
1519   case X86::BI__builtin_ia32_prolq512_mask:
1520   case X86::BI__builtin_ia32_prold128_mask:
1521   case X86::BI__builtin_ia32_prold256_mask:
1522   case X86::BI__builtin_ia32_prolq128_mask:
1523   case X86::BI__builtin_ia32_prolq256_mask:
1524   case X86::BI__builtin_ia32_prord128_mask:
1525   case X86::BI__builtin_ia32_prord256_mask:
1526   case X86::BI__builtin_ia32_prorq128_mask:
1527   case X86::BI__builtin_ia32_prorq256_mask:
1528   case X86::BI__builtin_ia32_pshufhw512_mask:
1529   case X86::BI__builtin_ia32_pshuflw512_mask:
1530   case X86::BI__builtin_ia32_pshufhw128_mask:
1531   case X86::BI__builtin_ia32_pshufhw256_mask:
1532   case X86::BI__builtin_ia32_pshuflw128_mask:
1533   case X86::BI__builtin_ia32_pshuflw256_mask:
1534   case X86::BI__builtin_ia32_psllwi512_mask:
1535   case X86::BI__builtin_ia32_psllwi128_mask:
1536   case X86::BI__builtin_ia32_psllwi256_mask:
1537   case X86::BI__builtin_ia32_psrldi128_mask:
1538   case X86::BI__builtin_ia32_psrldi256_mask:
1539   case X86::BI__builtin_ia32_psrldi512_mask:
1540   case X86::BI__builtin_ia32_psrlqi128_mask:
1541   case X86::BI__builtin_ia32_psrlqi256_mask:
1542   case X86::BI__builtin_ia32_psrlqi512_mask:
1543   case X86::BI__builtin_ia32_psrawi512_mask:
1544   case X86::BI__builtin_ia32_psrawi128_mask:
1545   case X86::BI__builtin_ia32_psrawi256_mask:
1546   case X86::BI__builtin_ia32_psrlwi512_mask:
1547   case X86::BI__builtin_ia32_psrlwi128_mask:
1548   case X86::BI__builtin_ia32_psrlwi256_mask:
1549   case X86::BI__builtin_ia32_vpermilpd512_mask:
1550   case X86::BI__builtin_ia32_vpermilps512_mask:
1551   case X86::BI__builtin_ia32_psradi128_mask:
1552   case X86::BI__builtin_ia32_psradi256_mask:
1553   case X86::BI__builtin_ia32_psradi512_mask:
1554   case X86::BI__builtin_ia32_psraqi128_mask:
1555   case X86::BI__builtin_ia32_psraqi256_mask:
1556   case X86::BI__builtin_ia32_psraqi512_mask:
1557   case X86::BI__builtin_ia32_pslldi128_mask:
1558   case X86::BI__builtin_ia32_pslldi256_mask:
1559   case X86::BI__builtin_ia32_pslldi512_mask:
1560   case X86::BI__builtin_ia32_psllqi128_mask:
1561   case X86::BI__builtin_ia32_psllqi256_mask:
1562   case X86::BI__builtin_ia32_psllqi512_mask:
1563   case X86::BI__builtin_ia32_permdf512_mask:
1564   case X86::BI__builtin_ia32_permdi512_mask:
1565   case X86::BI__builtin_ia32_permdf256_mask:
1566   case X86::BI__builtin_ia32_permdi256_mask:
1567   case X86::BI__builtin_ia32_fpclasspd128_mask:
1568   case X86::BI__builtin_ia32_fpclasspd256_mask:
1569   case X86::BI__builtin_ia32_fpclassps128_mask:
1570   case X86::BI__builtin_ia32_fpclassps256_mask:
1571   case X86::BI__builtin_ia32_fpclassps512_mask:
1572   case X86::BI__builtin_ia32_fpclasspd512_mask:
1573   case X86::BI__builtin_ia32_fpclasssd_mask:
1574   case X86::BI__builtin_ia32_fpclassss_mask:
1575   case X86::BI__builtin_ia32_pshufd512_mask:
1576   case X86::BI__builtin_ia32_pshufd256_mask:
1577   case X86::BI__builtin_ia32_pshufd128_mask:
1578     i = 1; l = 0; u = 255;
1579     break;
1580   case X86::BI__builtin_ia32_palignr:
1581   case X86::BI__builtin_ia32_insertps128:
1582   case X86::BI__builtin_ia32_dpps:
1583   case X86::BI__builtin_ia32_dppd:
1584   case X86::BI__builtin_ia32_dpps256:
1585   case X86::BI__builtin_ia32_mpsadbw128:
1586   case X86::BI__builtin_ia32_mpsadbw256:
1587   case X86::BI__builtin_ia32_pcmpistrm128:
1588   case X86::BI__builtin_ia32_pcmpistri128:
1589   case X86::BI__builtin_ia32_pcmpistria128:
1590   case X86::BI__builtin_ia32_pcmpistric128:
1591   case X86::BI__builtin_ia32_pcmpistrio128:
1592   case X86::BI__builtin_ia32_pcmpistris128:
1593   case X86::BI__builtin_ia32_pcmpistriz128:
1594   case X86::BI__builtin_ia32_pclmulqdq128:
1595   case X86::BI__builtin_ia32_vperm2f128_pd256:
1596   case X86::BI__builtin_ia32_vperm2f128_ps256:
1597   case X86::BI__builtin_ia32_vperm2f128_si256:
1598   case X86::BI__builtin_ia32_permti256:
1599     i = 2; l = -128; u = 255;
1600     break;
1601   case X86::BI__builtin_ia32_palignr128:
1602   case X86::BI__builtin_ia32_palignr256:
1603   case X86::BI__builtin_ia32_palignr128_mask:
1604   case X86::BI__builtin_ia32_palignr256_mask:
1605   case X86::BI__builtin_ia32_palignr512_mask:
1606   case X86::BI__builtin_ia32_alignq512_mask:
1607   case X86::BI__builtin_ia32_alignd512_mask:
1608   case X86::BI__builtin_ia32_alignd128_mask:
1609   case X86::BI__builtin_ia32_alignd256_mask:
1610   case X86::BI__builtin_ia32_alignq128_mask:
1611   case X86::BI__builtin_ia32_alignq256_mask:
1612   case X86::BI__builtin_ia32_vcomisd:
1613   case X86::BI__builtin_ia32_vcomiss:
1614   case X86::BI__builtin_ia32_shuf_f32x4_mask:
1615   case X86::BI__builtin_ia32_shuf_f64x2_mask:
1616   case X86::BI__builtin_ia32_shuf_i32x4_mask:
1617   case X86::BI__builtin_ia32_shuf_i64x2_mask:
1618   case X86::BI__builtin_ia32_shufpd512_mask:
1619   case X86::BI__builtin_ia32_shufps128_mask:
1620   case X86::BI__builtin_ia32_shufps256_mask:
1621   case X86::BI__builtin_ia32_shufps512_mask:
1622   case X86::BI__builtin_ia32_dbpsadbw128_mask:
1623   case X86::BI__builtin_ia32_dbpsadbw256_mask:
1624   case X86::BI__builtin_ia32_dbpsadbw512_mask:
1625     i = 2; l = 0; u = 255;
1626     break;
1627   case X86::BI__builtin_ia32_fixupimmpd512_mask:
1628   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
1629   case X86::BI__builtin_ia32_fixupimmps512_mask:
1630   case X86::BI__builtin_ia32_fixupimmps512_maskz:
1631   case X86::BI__builtin_ia32_fixupimmsd_mask:
1632   case X86::BI__builtin_ia32_fixupimmsd_maskz:
1633   case X86::BI__builtin_ia32_fixupimmss_mask:
1634   case X86::BI__builtin_ia32_fixupimmss_maskz:
1635   case X86::BI__builtin_ia32_fixupimmpd128_mask:
1636   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
1637   case X86::BI__builtin_ia32_fixupimmpd256_mask:
1638   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
1639   case X86::BI__builtin_ia32_fixupimmps128_mask:
1640   case X86::BI__builtin_ia32_fixupimmps128_maskz:
1641   case X86::BI__builtin_ia32_fixupimmps256_mask:
1642   case X86::BI__builtin_ia32_fixupimmps256_maskz:
1643   case X86::BI__builtin_ia32_pternlogd512_mask:
1644   case X86::BI__builtin_ia32_pternlogd512_maskz:
1645   case X86::BI__builtin_ia32_pternlogq512_mask:
1646   case X86::BI__builtin_ia32_pternlogq512_maskz:
1647   case X86::BI__builtin_ia32_pternlogd128_mask:
1648   case X86::BI__builtin_ia32_pternlogd128_maskz:
1649   case X86::BI__builtin_ia32_pternlogd256_mask:
1650   case X86::BI__builtin_ia32_pternlogd256_maskz:
1651   case X86::BI__builtin_ia32_pternlogq128_mask:
1652   case X86::BI__builtin_ia32_pternlogq128_maskz:
1653   case X86::BI__builtin_ia32_pternlogq256_mask:
1654   case X86::BI__builtin_ia32_pternlogq256_maskz:
1655     i = 3; l = 0; u = 255;
1656     break;
1657   case X86::BI__builtin_ia32_pcmpestrm128:
1658   case X86::BI__builtin_ia32_pcmpestri128:
1659   case X86::BI__builtin_ia32_pcmpestria128:
1660   case X86::BI__builtin_ia32_pcmpestric128:
1661   case X86::BI__builtin_ia32_pcmpestrio128:
1662   case X86::BI__builtin_ia32_pcmpestris128:
1663   case X86::BI__builtin_ia32_pcmpestriz128:
1664     i = 4; l = -128; u = 255;
1665     break;
1666   case X86::BI__builtin_ia32_rndscalesd_round_mask:
1667   case X86::BI__builtin_ia32_rndscaless_round_mask:
1668     i = 4; l = 0; u = 255;
1669     break;
1670   }
1671   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1672 }
1673 
1674 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
1675 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
1676 /// Returns true when the format fits the function and the FormatStringInfo has
1677 /// been populated.
1678 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
1679                                FormatStringInfo *FSI) {
1680   FSI->HasVAListArg = Format->getFirstArg() == 0;
1681   FSI->FormatIdx = Format->getFormatIdx() - 1;
1682   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
1683 
1684   // The way the format attribute works in GCC, the implicit this argument
1685   // of member functions is counted. However, it doesn't appear in our own
1686   // lists, so decrement format_idx in that case.
1687   if (IsCXXMember) {
1688     if(FSI->FormatIdx == 0)
1689       return false;
1690     --FSI->FormatIdx;
1691     if (FSI->FirstDataArg != 0)
1692       --FSI->FirstDataArg;
1693   }
1694   return true;
1695 }
1696 
1697 /// Checks if a the given expression evaluates to null.
1698 ///
1699 /// \brief Returns true if the value evaluates to null.
1700 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
1701   // If the expression has non-null type, it doesn't evaluate to null.
1702   if (auto nullability
1703         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
1704     if (*nullability == NullabilityKind::NonNull)
1705       return false;
1706   }
1707 
1708   // As a special case, transparent unions initialized with zero are
1709   // considered null for the purposes of the nonnull attribute.
1710   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
1711     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
1712       if (const CompoundLiteralExpr *CLE =
1713           dyn_cast<CompoundLiteralExpr>(Expr))
1714         if (const InitListExpr *ILE =
1715             dyn_cast<InitListExpr>(CLE->getInitializer()))
1716           Expr = ILE->getInit(0);
1717   }
1718 
1719   bool Result;
1720   return (!Expr->isValueDependent() &&
1721           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
1722           !Result);
1723 }
1724 
1725 static void CheckNonNullArgument(Sema &S,
1726                                  const Expr *ArgExpr,
1727                                  SourceLocation CallSiteLoc) {
1728   if (CheckNonNullExpr(S, ArgExpr))
1729     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
1730            S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
1731 }
1732 
1733 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
1734   FormatStringInfo FSI;
1735   if ((GetFormatStringType(Format) == FST_NSString) &&
1736       getFormatStringInfo(Format, false, &FSI)) {
1737     Idx = FSI.FormatIdx;
1738     return true;
1739   }
1740   return false;
1741 }
1742 /// \brief Diagnose use of %s directive in an NSString which is being passed
1743 /// as formatting string to formatting method.
1744 static void
1745 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
1746                                         const NamedDecl *FDecl,
1747                                         Expr **Args,
1748                                         unsigned NumArgs) {
1749   unsigned Idx = 0;
1750   bool Format = false;
1751   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
1752   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
1753     Idx = 2;
1754     Format = true;
1755   }
1756   else
1757     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
1758       if (S.GetFormatNSStringIdx(I, Idx)) {
1759         Format = true;
1760         break;
1761       }
1762     }
1763   if (!Format || NumArgs <= Idx)
1764     return;
1765   const Expr *FormatExpr = Args[Idx];
1766   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
1767     FormatExpr = CSCE->getSubExpr();
1768   const StringLiteral *FormatString;
1769   if (const ObjCStringLiteral *OSL =
1770       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
1771     FormatString = OSL->getString();
1772   else
1773     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
1774   if (!FormatString)
1775     return;
1776   if (S.FormatStringHasSArg(FormatString)) {
1777     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
1778       << "%s" << 1 << 1;
1779     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
1780       << FDecl->getDeclName();
1781   }
1782 }
1783 
1784 /// Determine whether the given type has a non-null nullability annotation.
1785 static bool isNonNullType(ASTContext &ctx, QualType type) {
1786   if (auto nullability = type->getNullability(ctx))
1787     return *nullability == NullabilityKind::NonNull;
1788 
1789   return false;
1790 }
1791 
1792 static void CheckNonNullArguments(Sema &S,
1793                                   const NamedDecl *FDecl,
1794                                   const FunctionProtoType *Proto,
1795                                   ArrayRef<const Expr *> Args,
1796                                   SourceLocation CallSiteLoc) {
1797   assert((FDecl || Proto) && "Need a function declaration or prototype");
1798 
1799   // Check the attributes attached to the method/function itself.
1800   llvm::SmallBitVector NonNullArgs;
1801   if (FDecl) {
1802     // Handle the nonnull attribute on the function/method declaration itself.
1803     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
1804       if (!NonNull->args_size()) {
1805         // Easy case: all pointer arguments are nonnull.
1806         for (const auto *Arg : Args)
1807           if (S.isValidPointerAttrType(Arg->getType()))
1808             CheckNonNullArgument(S, Arg, CallSiteLoc);
1809         return;
1810       }
1811 
1812       for (unsigned Val : NonNull->args()) {
1813         if (Val >= Args.size())
1814           continue;
1815         if (NonNullArgs.empty())
1816           NonNullArgs.resize(Args.size());
1817         NonNullArgs.set(Val);
1818       }
1819     }
1820   }
1821 
1822   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
1823     // Handle the nonnull attribute on the parameters of the
1824     // function/method.
1825     ArrayRef<ParmVarDecl*> parms;
1826     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
1827       parms = FD->parameters();
1828     else
1829       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
1830 
1831     unsigned ParamIndex = 0;
1832     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
1833          I != E; ++I, ++ParamIndex) {
1834       const ParmVarDecl *PVD = *I;
1835       if (PVD->hasAttr<NonNullAttr>() ||
1836           isNonNullType(S.Context, PVD->getType())) {
1837         if (NonNullArgs.empty())
1838           NonNullArgs.resize(Args.size());
1839 
1840         NonNullArgs.set(ParamIndex);
1841       }
1842     }
1843   } else {
1844     // If we have a non-function, non-method declaration but no
1845     // function prototype, try to dig out the function prototype.
1846     if (!Proto) {
1847       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
1848         QualType type = VD->getType().getNonReferenceType();
1849         if (auto pointerType = type->getAs<PointerType>())
1850           type = pointerType->getPointeeType();
1851         else if (auto blockType = type->getAs<BlockPointerType>())
1852           type = blockType->getPointeeType();
1853         // FIXME: data member pointers?
1854 
1855         // Dig out the function prototype, if there is one.
1856         Proto = type->getAs<FunctionProtoType>();
1857       }
1858     }
1859 
1860     // Fill in non-null argument information from the nullability
1861     // information on the parameter types (if we have them).
1862     if (Proto) {
1863       unsigned Index = 0;
1864       for (auto paramType : Proto->getParamTypes()) {
1865         if (isNonNullType(S.Context, paramType)) {
1866           if (NonNullArgs.empty())
1867             NonNullArgs.resize(Args.size());
1868 
1869           NonNullArgs.set(Index);
1870         }
1871 
1872         ++Index;
1873       }
1874     }
1875   }
1876 
1877   // Check for non-null arguments.
1878   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
1879        ArgIndex != ArgIndexEnd; ++ArgIndex) {
1880     if (NonNullArgs[ArgIndex])
1881       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
1882   }
1883 }
1884 
1885 /// Handles the checks for format strings, non-POD arguments to vararg
1886 /// functions, and NULL arguments passed to non-NULL parameters.
1887 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
1888                      ArrayRef<const Expr *> Args, bool IsMemberFunction,
1889                      SourceLocation Loc, SourceRange Range,
1890                      VariadicCallType CallType) {
1891   // FIXME: We should check as much as we can in the template definition.
1892   if (CurContext->isDependentContext())
1893     return;
1894 
1895   // Printf and scanf checking.
1896   llvm::SmallBitVector CheckedVarArgs;
1897   if (FDecl) {
1898     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
1899       // Only create vector if there are format attributes.
1900       CheckedVarArgs.resize(Args.size());
1901 
1902       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
1903                            CheckedVarArgs);
1904     }
1905   }
1906 
1907   // Refuse POD arguments that weren't caught by the format string
1908   // checks above.
1909   if (CallType != VariadicDoesNotApply) {
1910     unsigned NumParams = Proto ? Proto->getNumParams()
1911                        : FDecl && isa<FunctionDecl>(FDecl)
1912                            ? cast<FunctionDecl>(FDecl)->getNumParams()
1913                        : FDecl && isa<ObjCMethodDecl>(FDecl)
1914                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
1915                        : 0;
1916 
1917     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
1918       // Args[ArgIdx] can be null in malformed code.
1919       if (const Expr *Arg = Args[ArgIdx]) {
1920         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
1921           checkVariadicArgument(Arg, CallType);
1922       }
1923     }
1924   }
1925 
1926   if (FDecl || Proto) {
1927     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
1928 
1929     // Type safety checking.
1930     if (FDecl) {
1931       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
1932         CheckArgumentWithTypeTag(I, Args.data());
1933     }
1934   }
1935 }
1936 
1937 /// CheckConstructorCall - Check a constructor call for correctness and safety
1938 /// properties not enforced by the C type system.
1939 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
1940                                 ArrayRef<const Expr *> Args,
1941                                 const FunctionProtoType *Proto,
1942                                 SourceLocation Loc) {
1943   VariadicCallType CallType =
1944     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
1945   checkCall(FDecl, Proto, Args, /*IsMemberFunction=*/true, Loc, SourceRange(),
1946             CallType);
1947 }
1948 
1949 /// CheckFunctionCall - Check a direct function call for various correctness
1950 /// and safety properties not strictly enforced by the C type system.
1951 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
1952                              const FunctionProtoType *Proto) {
1953   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
1954                               isa<CXXMethodDecl>(FDecl);
1955   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
1956                           IsMemberOperatorCall;
1957   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
1958                                                   TheCall->getCallee());
1959   Expr** Args = TheCall->getArgs();
1960   unsigned NumArgs = TheCall->getNumArgs();
1961   if (IsMemberOperatorCall) {
1962     // If this is a call to a member operator, hide the first argument
1963     // from checkCall.
1964     // FIXME: Our choice of AST representation here is less than ideal.
1965     ++Args;
1966     --NumArgs;
1967   }
1968   checkCall(FDecl, Proto, llvm::makeArrayRef(Args, NumArgs),
1969             IsMemberFunction, TheCall->getRParenLoc(),
1970             TheCall->getCallee()->getSourceRange(), CallType);
1971 
1972   IdentifierInfo *FnInfo = FDecl->getIdentifier();
1973   // None of the checks below are needed for functions that don't have
1974   // simple names (e.g., C++ conversion functions).
1975   if (!FnInfo)
1976     return false;
1977 
1978   CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
1979   if (getLangOpts().ObjC1)
1980     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
1981 
1982   unsigned CMId = FDecl->getMemoryFunctionKind();
1983   if (CMId == 0)
1984     return false;
1985 
1986   // Handle memory setting and copying functions.
1987   if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
1988     CheckStrlcpycatArguments(TheCall, FnInfo);
1989   else if (CMId == Builtin::BIstrncat)
1990     CheckStrncatArguments(TheCall, FnInfo);
1991   else
1992     CheckMemaccessArguments(TheCall, CMId, FnInfo);
1993 
1994   return false;
1995 }
1996 
1997 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
1998                                ArrayRef<const Expr *> Args) {
1999   VariadicCallType CallType =
2000       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
2001 
2002   checkCall(Method, nullptr, Args,
2003             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
2004             CallType);
2005 
2006   return false;
2007 }
2008 
2009 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
2010                             const FunctionProtoType *Proto) {
2011   QualType Ty;
2012   if (const auto *V = dyn_cast<VarDecl>(NDecl))
2013     Ty = V->getType().getNonReferenceType();
2014   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
2015     Ty = F->getType().getNonReferenceType();
2016   else
2017     return false;
2018 
2019   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
2020       !Ty->isFunctionProtoType())
2021     return false;
2022 
2023   VariadicCallType CallType;
2024   if (!Proto || !Proto->isVariadic()) {
2025     CallType = VariadicDoesNotApply;
2026   } else if (Ty->isBlockPointerType()) {
2027     CallType = VariadicBlock;
2028   } else { // Ty->isFunctionPointerType()
2029     CallType = VariadicFunction;
2030   }
2031 
2032   checkCall(NDecl, Proto,
2033             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2034             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
2035             TheCall->getCallee()->getSourceRange(), CallType);
2036 
2037   return false;
2038 }
2039 
2040 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
2041 /// such as function pointers returned from functions.
2042 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
2043   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
2044                                                   TheCall->getCallee());
2045   checkCall(/*FDecl=*/nullptr, Proto,
2046             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2047             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
2048             TheCall->getCallee()->getSourceRange(), CallType);
2049 
2050   return false;
2051 }
2052 
2053 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
2054   if (!llvm::isValidAtomicOrderingCABI(Ordering))
2055     return false;
2056 
2057   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
2058   switch (Op) {
2059   case AtomicExpr::AO__c11_atomic_init:
2060     llvm_unreachable("There is no ordering argument for an init");
2061 
2062   case AtomicExpr::AO__c11_atomic_load:
2063   case AtomicExpr::AO__atomic_load_n:
2064   case AtomicExpr::AO__atomic_load:
2065     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
2066            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
2067 
2068   case AtomicExpr::AO__c11_atomic_store:
2069   case AtomicExpr::AO__atomic_store:
2070   case AtomicExpr::AO__atomic_store_n:
2071     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
2072            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
2073            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
2074 
2075   default:
2076     return true;
2077   }
2078 }
2079 
2080 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
2081                                          AtomicExpr::AtomicOp Op) {
2082   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
2083   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2084 
2085   // All these operations take one of the following forms:
2086   enum {
2087     // C    __c11_atomic_init(A *, C)
2088     Init,
2089     // C    __c11_atomic_load(A *, int)
2090     Load,
2091     // void __atomic_load(A *, CP, int)
2092     LoadCopy,
2093     // void __atomic_store(A *, CP, int)
2094     Copy,
2095     // C    __c11_atomic_add(A *, M, int)
2096     Arithmetic,
2097     // C    __atomic_exchange_n(A *, CP, int)
2098     Xchg,
2099     // void __atomic_exchange(A *, C *, CP, int)
2100     GNUXchg,
2101     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
2102     C11CmpXchg,
2103     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
2104     GNUCmpXchg
2105   } Form = Init;
2106   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
2107   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
2108   // where:
2109   //   C is an appropriate type,
2110   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
2111   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
2112   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
2113   //   the int parameters are for orderings.
2114 
2115   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
2116                     AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
2117                         AtomicExpr::AO__atomic_load,
2118                 "need to update code for modified C11 atomics");
2119   bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
2120                Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
2121   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
2122              Op == AtomicExpr::AO__atomic_store_n ||
2123              Op == AtomicExpr::AO__atomic_exchange_n ||
2124              Op == AtomicExpr::AO__atomic_compare_exchange_n;
2125   bool IsAddSub = false;
2126 
2127   switch (Op) {
2128   case AtomicExpr::AO__c11_atomic_init:
2129     Form = Init;
2130     break;
2131 
2132   case AtomicExpr::AO__c11_atomic_load:
2133   case AtomicExpr::AO__atomic_load_n:
2134     Form = Load;
2135     break;
2136 
2137   case AtomicExpr::AO__atomic_load:
2138     Form = LoadCopy;
2139     break;
2140 
2141   case AtomicExpr::AO__c11_atomic_store:
2142   case AtomicExpr::AO__atomic_store:
2143   case AtomicExpr::AO__atomic_store_n:
2144     Form = Copy;
2145     break;
2146 
2147   case AtomicExpr::AO__c11_atomic_fetch_add:
2148   case AtomicExpr::AO__c11_atomic_fetch_sub:
2149   case AtomicExpr::AO__atomic_fetch_add:
2150   case AtomicExpr::AO__atomic_fetch_sub:
2151   case AtomicExpr::AO__atomic_add_fetch:
2152   case AtomicExpr::AO__atomic_sub_fetch:
2153     IsAddSub = true;
2154     // Fall through.
2155   case AtomicExpr::AO__c11_atomic_fetch_and:
2156   case AtomicExpr::AO__c11_atomic_fetch_or:
2157   case AtomicExpr::AO__c11_atomic_fetch_xor:
2158   case AtomicExpr::AO__atomic_fetch_and:
2159   case AtomicExpr::AO__atomic_fetch_or:
2160   case AtomicExpr::AO__atomic_fetch_xor:
2161   case AtomicExpr::AO__atomic_fetch_nand:
2162   case AtomicExpr::AO__atomic_and_fetch:
2163   case AtomicExpr::AO__atomic_or_fetch:
2164   case AtomicExpr::AO__atomic_xor_fetch:
2165   case AtomicExpr::AO__atomic_nand_fetch:
2166     Form = Arithmetic;
2167     break;
2168 
2169   case AtomicExpr::AO__c11_atomic_exchange:
2170   case AtomicExpr::AO__atomic_exchange_n:
2171     Form = Xchg;
2172     break;
2173 
2174   case AtomicExpr::AO__atomic_exchange:
2175     Form = GNUXchg;
2176     break;
2177 
2178   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
2179   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
2180     Form = C11CmpXchg;
2181     break;
2182 
2183   case AtomicExpr::AO__atomic_compare_exchange:
2184   case AtomicExpr::AO__atomic_compare_exchange_n:
2185     Form = GNUCmpXchg;
2186     break;
2187   }
2188 
2189   // Check we have the right number of arguments.
2190   if (TheCall->getNumArgs() < NumArgs[Form]) {
2191     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
2192       << 0 << NumArgs[Form] << TheCall->getNumArgs()
2193       << TheCall->getCallee()->getSourceRange();
2194     return ExprError();
2195   } else if (TheCall->getNumArgs() > NumArgs[Form]) {
2196     Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
2197          diag::err_typecheck_call_too_many_args)
2198       << 0 << NumArgs[Form] << TheCall->getNumArgs()
2199       << TheCall->getCallee()->getSourceRange();
2200     return ExprError();
2201   }
2202 
2203   // Inspect the first argument of the atomic operation.
2204   Expr *Ptr = TheCall->getArg(0);
2205   Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
2206   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
2207   if (!pointerType) {
2208     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
2209       << Ptr->getType() << Ptr->getSourceRange();
2210     return ExprError();
2211   }
2212 
2213   // For a __c11 builtin, this should be a pointer to an _Atomic type.
2214   QualType AtomTy = pointerType->getPointeeType(); // 'A'
2215   QualType ValType = AtomTy; // 'C'
2216   if (IsC11) {
2217     if (!AtomTy->isAtomicType()) {
2218       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
2219         << Ptr->getType() << Ptr->getSourceRange();
2220       return ExprError();
2221     }
2222     if (AtomTy.isConstQualified()) {
2223       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
2224         << Ptr->getType() << Ptr->getSourceRange();
2225       return ExprError();
2226     }
2227     ValType = AtomTy->getAs<AtomicType>()->getValueType();
2228   } else if (Form != Load && Form != LoadCopy) {
2229     if (ValType.isConstQualified()) {
2230       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
2231         << Ptr->getType() << Ptr->getSourceRange();
2232       return ExprError();
2233     }
2234   }
2235 
2236   // For an arithmetic operation, the implied arithmetic must be well-formed.
2237   if (Form == Arithmetic) {
2238     // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
2239     if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
2240       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
2241         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2242       return ExprError();
2243     }
2244     if (!IsAddSub && !ValType->isIntegerType()) {
2245       Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
2246         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2247       return ExprError();
2248     }
2249     if (IsC11 && ValType->isPointerType() &&
2250         RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
2251                             diag::err_incomplete_type)) {
2252       return ExprError();
2253     }
2254   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
2255     // For __atomic_*_n operations, the value type must be a scalar integral or
2256     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
2257     Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
2258       << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2259     return ExprError();
2260   }
2261 
2262   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
2263       !AtomTy->isScalarType()) {
2264     // For GNU atomics, require a trivially-copyable type. This is not part of
2265     // the GNU atomics specification, but we enforce it for sanity.
2266     Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
2267       << Ptr->getType() << Ptr->getSourceRange();
2268     return ExprError();
2269   }
2270 
2271   switch (ValType.getObjCLifetime()) {
2272   case Qualifiers::OCL_None:
2273   case Qualifiers::OCL_ExplicitNone:
2274     // okay
2275     break;
2276 
2277   case Qualifiers::OCL_Weak:
2278   case Qualifiers::OCL_Strong:
2279   case Qualifiers::OCL_Autoreleasing:
2280     // FIXME: Can this happen? By this point, ValType should be known
2281     // to be trivially copyable.
2282     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
2283       << ValType << Ptr->getSourceRange();
2284     return ExprError();
2285   }
2286 
2287   // atomic_fetch_or takes a pointer to a volatile 'A'.  We shouldn't let the
2288   // volatile-ness of the pointee-type inject itself into the result or the
2289   // other operands. Similarly atomic_load can take a pointer to a const 'A'.
2290   ValType.removeLocalVolatile();
2291   ValType.removeLocalConst();
2292   QualType ResultType = ValType;
2293   if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init)
2294     ResultType = Context.VoidTy;
2295   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
2296     ResultType = Context.BoolTy;
2297 
2298   // The type of a parameter passed 'by value'. In the GNU atomics, such
2299   // arguments are actually passed as pointers.
2300   QualType ByValType = ValType; // 'CP'
2301   if (!IsC11 && !IsN)
2302     ByValType = Ptr->getType();
2303 
2304   // The first argument --- the pointer --- has a fixed type; we
2305   // deduce the types of the rest of the arguments accordingly.  Walk
2306   // the remaining arguments, converting them to the deduced value type.
2307   for (unsigned i = 1; i != NumArgs[Form]; ++i) {
2308     QualType Ty;
2309     if (i < NumVals[Form] + 1) {
2310       switch (i) {
2311       case 1:
2312         // The second argument is the non-atomic operand. For arithmetic, this
2313         // is always passed by value, and for a compare_exchange it is always
2314         // passed by address. For the rest, GNU uses by-address and C11 uses
2315         // by-value.
2316         assert(Form != Load);
2317         if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
2318           Ty = ValType;
2319         else if (Form == Copy || Form == Xchg)
2320           Ty = ByValType;
2321         else if (Form == Arithmetic)
2322           Ty = Context.getPointerDiffType();
2323         else {
2324           Expr *ValArg = TheCall->getArg(i);
2325           unsigned AS = 0;
2326           // Keep address space of non-atomic pointer type.
2327           if (const PointerType *PtrTy =
2328                   ValArg->getType()->getAs<PointerType>()) {
2329             AS = PtrTy->getPointeeType().getAddressSpace();
2330           }
2331           Ty = Context.getPointerType(
2332               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
2333         }
2334         break;
2335       case 2:
2336         // The third argument to compare_exchange / GNU exchange is a
2337         // (pointer to a) desired value.
2338         Ty = ByValType;
2339         break;
2340       case 3:
2341         // The fourth argument to GNU compare_exchange is a 'weak' flag.
2342         Ty = Context.BoolTy;
2343         break;
2344       }
2345     } else {
2346       // The order(s) are always converted to int.
2347       Ty = Context.IntTy;
2348     }
2349 
2350     InitializedEntity Entity =
2351         InitializedEntity::InitializeParameter(Context, Ty, false);
2352     ExprResult Arg = TheCall->getArg(i);
2353     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2354     if (Arg.isInvalid())
2355       return true;
2356     TheCall->setArg(i, Arg.get());
2357   }
2358 
2359   // Permute the arguments into a 'consistent' order.
2360   SmallVector<Expr*, 5> SubExprs;
2361   SubExprs.push_back(Ptr);
2362   switch (Form) {
2363   case Init:
2364     // Note, AtomicExpr::getVal1() has a special case for this atomic.
2365     SubExprs.push_back(TheCall->getArg(1)); // Val1
2366     break;
2367   case Load:
2368     SubExprs.push_back(TheCall->getArg(1)); // Order
2369     break;
2370   case LoadCopy:
2371   case Copy:
2372   case Arithmetic:
2373   case Xchg:
2374     SubExprs.push_back(TheCall->getArg(2)); // Order
2375     SubExprs.push_back(TheCall->getArg(1)); // Val1
2376     break;
2377   case GNUXchg:
2378     // Note, AtomicExpr::getVal2() has a special case for this atomic.
2379     SubExprs.push_back(TheCall->getArg(3)); // Order
2380     SubExprs.push_back(TheCall->getArg(1)); // Val1
2381     SubExprs.push_back(TheCall->getArg(2)); // Val2
2382     break;
2383   case C11CmpXchg:
2384     SubExprs.push_back(TheCall->getArg(3)); // Order
2385     SubExprs.push_back(TheCall->getArg(1)); // Val1
2386     SubExprs.push_back(TheCall->getArg(4)); // OrderFail
2387     SubExprs.push_back(TheCall->getArg(2)); // Val2
2388     break;
2389   case GNUCmpXchg:
2390     SubExprs.push_back(TheCall->getArg(4)); // Order
2391     SubExprs.push_back(TheCall->getArg(1)); // Val1
2392     SubExprs.push_back(TheCall->getArg(5)); // OrderFail
2393     SubExprs.push_back(TheCall->getArg(2)); // Val2
2394     SubExprs.push_back(TheCall->getArg(3)); // Weak
2395     break;
2396   }
2397 
2398   if (SubExprs.size() >= 2 && Form != Init) {
2399     llvm::APSInt Result(32);
2400     if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
2401         !isValidOrderingForOp(Result.getSExtValue(), Op))
2402       Diag(SubExprs[1]->getLocStart(),
2403            diag::warn_atomic_op_has_invalid_memory_order)
2404           << SubExprs[1]->getSourceRange();
2405   }
2406 
2407   AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
2408                                             SubExprs, ResultType, Op,
2409                                             TheCall->getRParenLoc());
2410 
2411   if ((Op == AtomicExpr::AO__c11_atomic_load ||
2412        (Op == AtomicExpr::AO__c11_atomic_store)) &&
2413       Context.AtomicUsesUnsupportedLibcall(AE))
2414     Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
2415     ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
2416 
2417   return AE;
2418 }
2419 
2420 /// checkBuiltinArgument - Given a call to a builtin function, perform
2421 /// normal type-checking on the given argument, updating the call in
2422 /// place.  This is useful when a builtin function requires custom
2423 /// type-checking for some of its arguments but not necessarily all of
2424 /// them.
2425 ///
2426 /// Returns true on error.
2427 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
2428   FunctionDecl *Fn = E->getDirectCallee();
2429   assert(Fn && "builtin call without direct callee!");
2430 
2431   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
2432   InitializedEntity Entity =
2433     InitializedEntity::InitializeParameter(S.Context, Param);
2434 
2435   ExprResult Arg = E->getArg(0);
2436   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
2437   if (Arg.isInvalid())
2438     return true;
2439 
2440   E->setArg(ArgIndex, Arg.get());
2441   return false;
2442 }
2443 
2444 /// SemaBuiltinAtomicOverloaded - We have a call to a function like
2445 /// __sync_fetch_and_add, which is an overloaded function based on the pointer
2446 /// type of its first argument.  The main ActOnCallExpr routines have already
2447 /// promoted the types of arguments because all of these calls are prototyped as
2448 /// void(...).
2449 ///
2450 /// This function goes through and does final semantic checking for these
2451 /// builtins,
2452 ExprResult
2453 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
2454   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
2455   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2456   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2457 
2458   // Ensure that we have at least one argument to do type inference from.
2459   if (TheCall->getNumArgs() < 1) {
2460     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
2461       << 0 << 1 << TheCall->getNumArgs()
2462       << TheCall->getCallee()->getSourceRange();
2463     return ExprError();
2464   }
2465 
2466   // Inspect the first argument of the atomic builtin.  This should always be
2467   // a pointer type, whose element is an integral scalar or pointer type.
2468   // Because it is a pointer type, we don't have to worry about any implicit
2469   // casts here.
2470   // FIXME: We don't allow floating point scalars as input.
2471   Expr *FirstArg = TheCall->getArg(0);
2472   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
2473   if (FirstArgResult.isInvalid())
2474     return ExprError();
2475   FirstArg = FirstArgResult.get();
2476   TheCall->setArg(0, FirstArg);
2477 
2478   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
2479   if (!pointerType) {
2480     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
2481       << FirstArg->getType() << FirstArg->getSourceRange();
2482     return ExprError();
2483   }
2484 
2485   QualType ValType = pointerType->getPointeeType();
2486   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2487       !ValType->isBlockPointerType()) {
2488     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
2489       << FirstArg->getType() << FirstArg->getSourceRange();
2490     return ExprError();
2491   }
2492 
2493   switch (ValType.getObjCLifetime()) {
2494   case Qualifiers::OCL_None:
2495   case Qualifiers::OCL_ExplicitNone:
2496     // okay
2497     break;
2498 
2499   case Qualifiers::OCL_Weak:
2500   case Qualifiers::OCL_Strong:
2501   case Qualifiers::OCL_Autoreleasing:
2502     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
2503       << ValType << FirstArg->getSourceRange();
2504     return ExprError();
2505   }
2506 
2507   // Strip any qualifiers off ValType.
2508   ValType = ValType.getUnqualifiedType();
2509 
2510   // The majority of builtins return a value, but a few have special return
2511   // types, so allow them to override appropriately below.
2512   QualType ResultType = ValType;
2513 
2514   // We need to figure out which concrete builtin this maps onto.  For example,
2515   // __sync_fetch_and_add with a 2 byte object turns into
2516   // __sync_fetch_and_add_2.
2517 #define BUILTIN_ROW(x) \
2518   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
2519     Builtin::BI##x##_8, Builtin::BI##x##_16 }
2520 
2521   static const unsigned BuiltinIndices[][5] = {
2522     BUILTIN_ROW(__sync_fetch_and_add),
2523     BUILTIN_ROW(__sync_fetch_and_sub),
2524     BUILTIN_ROW(__sync_fetch_and_or),
2525     BUILTIN_ROW(__sync_fetch_and_and),
2526     BUILTIN_ROW(__sync_fetch_and_xor),
2527     BUILTIN_ROW(__sync_fetch_and_nand),
2528 
2529     BUILTIN_ROW(__sync_add_and_fetch),
2530     BUILTIN_ROW(__sync_sub_and_fetch),
2531     BUILTIN_ROW(__sync_and_and_fetch),
2532     BUILTIN_ROW(__sync_or_and_fetch),
2533     BUILTIN_ROW(__sync_xor_and_fetch),
2534     BUILTIN_ROW(__sync_nand_and_fetch),
2535 
2536     BUILTIN_ROW(__sync_val_compare_and_swap),
2537     BUILTIN_ROW(__sync_bool_compare_and_swap),
2538     BUILTIN_ROW(__sync_lock_test_and_set),
2539     BUILTIN_ROW(__sync_lock_release),
2540     BUILTIN_ROW(__sync_swap)
2541   };
2542 #undef BUILTIN_ROW
2543 
2544   // Determine the index of the size.
2545   unsigned SizeIndex;
2546   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
2547   case 1: SizeIndex = 0; break;
2548   case 2: SizeIndex = 1; break;
2549   case 4: SizeIndex = 2; break;
2550   case 8: SizeIndex = 3; break;
2551   case 16: SizeIndex = 4; break;
2552   default:
2553     Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
2554       << FirstArg->getType() << FirstArg->getSourceRange();
2555     return ExprError();
2556   }
2557 
2558   // Each of these builtins has one pointer argument, followed by some number of
2559   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
2560   // that we ignore.  Find out which row of BuiltinIndices to read from as well
2561   // as the number of fixed args.
2562   unsigned BuiltinID = FDecl->getBuiltinID();
2563   unsigned BuiltinIndex, NumFixed = 1;
2564   bool WarnAboutSemanticsChange = false;
2565   switch (BuiltinID) {
2566   default: llvm_unreachable("Unknown overloaded atomic builtin!");
2567   case Builtin::BI__sync_fetch_and_add:
2568   case Builtin::BI__sync_fetch_and_add_1:
2569   case Builtin::BI__sync_fetch_and_add_2:
2570   case Builtin::BI__sync_fetch_and_add_4:
2571   case Builtin::BI__sync_fetch_and_add_8:
2572   case Builtin::BI__sync_fetch_and_add_16:
2573     BuiltinIndex = 0;
2574     break;
2575 
2576   case Builtin::BI__sync_fetch_and_sub:
2577   case Builtin::BI__sync_fetch_and_sub_1:
2578   case Builtin::BI__sync_fetch_and_sub_2:
2579   case Builtin::BI__sync_fetch_and_sub_4:
2580   case Builtin::BI__sync_fetch_and_sub_8:
2581   case Builtin::BI__sync_fetch_and_sub_16:
2582     BuiltinIndex = 1;
2583     break;
2584 
2585   case Builtin::BI__sync_fetch_and_or:
2586   case Builtin::BI__sync_fetch_and_or_1:
2587   case Builtin::BI__sync_fetch_and_or_2:
2588   case Builtin::BI__sync_fetch_and_or_4:
2589   case Builtin::BI__sync_fetch_and_or_8:
2590   case Builtin::BI__sync_fetch_and_or_16:
2591     BuiltinIndex = 2;
2592     break;
2593 
2594   case Builtin::BI__sync_fetch_and_and:
2595   case Builtin::BI__sync_fetch_and_and_1:
2596   case Builtin::BI__sync_fetch_and_and_2:
2597   case Builtin::BI__sync_fetch_and_and_4:
2598   case Builtin::BI__sync_fetch_and_and_8:
2599   case Builtin::BI__sync_fetch_and_and_16:
2600     BuiltinIndex = 3;
2601     break;
2602 
2603   case Builtin::BI__sync_fetch_and_xor:
2604   case Builtin::BI__sync_fetch_and_xor_1:
2605   case Builtin::BI__sync_fetch_and_xor_2:
2606   case Builtin::BI__sync_fetch_and_xor_4:
2607   case Builtin::BI__sync_fetch_and_xor_8:
2608   case Builtin::BI__sync_fetch_and_xor_16:
2609     BuiltinIndex = 4;
2610     break;
2611 
2612   case Builtin::BI__sync_fetch_and_nand:
2613   case Builtin::BI__sync_fetch_and_nand_1:
2614   case Builtin::BI__sync_fetch_and_nand_2:
2615   case Builtin::BI__sync_fetch_and_nand_4:
2616   case Builtin::BI__sync_fetch_and_nand_8:
2617   case Builtin::BI__sync_fetch_and_nand_16:
2618     BuiltinIndex = 5;
2619     WarnAboutSemanticsChange = true;
2620     break;
2621 
2622   case Builtin::BI__sync_add_and_fetch:
2623   case Builtin::BI__sync_add_and_fetch_1:
2624   case Builtin::BI__sync_add_and_fetch_2:
2625   case Builtin::BI__sync_add_and_fetch_4:
2626   case Builtin::BI__sync_add_and_fetch_8:
2627   case Builtin::BI__sync_add_and_fetch_16:
2628     BuiltinIndex = 6;
2629     break;
2630 
2631   case Builtin::BI__sync_sub_and_fetch:
2632   case Builtin::BI__sync_sub_and_fetch_1:
2633   case Builtin::BI__sync_sub_and_fetch_2:
2634   case Builtin::BI__sync_sub_and_fetch_4:
2635   case Builtin::BI__sync_sub_and_fetch_8:
2636   case Builtin::BI__sync_sub_and_fetch_16:
2637     BuiltinIndex = 7;
2638     break;
2639 
2640   case Builtin::BI__sync_and_and_fetch:
2641   case Builtin::BI__sync_and_and_fetch_1:
2642   case Builtin::BI__sync_and_and_fetch_2:
2643   case Builtin::BI__sync_and_and_fetch_4:
2644   case Builtin::BI__sync_and_and_fetch_8:
2645   case Builtin::BI__sync_and_and_fetch_16:
2646     BuiltinIndex = 8;
2647     break;
2648 
2649   case Builtin::BI__sync_or_and_fetch:
2650   case Builtin::BI__sync_or_and_fetch_1:
2651   case Builtin::BI__sync_or_and_fetch_2:
2652   case Builtin::BI__sync_or_and_fetch_4:
2653   case Builtin::BI__sync_or_and_fetch_8:
2654   case Builtin::BI__sync_or_and_fetch_16:
2655     BuiltinIndex = 9;
2656     break;
2657 
2658   case Builtin::BI__sync_xor_and_fetch:
2659   case Builtin::BI__sync_xor_and_fetch_1:
2660   case Builtin::BI__sync_xor_and_fetch_2:
2661   case Builtin::BI__sync_xor_and_fetch_4:
2662   case Builtin::BI__sync_xor_and_fetch_8:
2663   case Builtin::BI__sync_xor_and_fetch_16:
2664     BuiltinIndex = 10;
2665     break;
2666 
2667   case Builtin::BI__sync_nand_and_fetch:
2668   case Builtin::BI__sync_nand_and_fetch_1:
2669   case Builtin::BI__sync_nand_and_fetch_2:
2670   case Builtin::BI__sync_nand_and_fetch_4:
2671   case Builtin::BI__sync_nand_and_fetch_8:
2672   case Builtin::BI__sync_nand_and_fetch_16:
2673     BuiltinIndex = 11;
2674     WarnAboutSemanticsChange = true;
2675     break;
2676 
2677   case Builtin::BI__sync_val_compare_and_swap:
2678   case Builtin::BI__sync_val_compare_and_swap_1:
2679   case Builtin::BI__sync_val_compare_and_swap_2:
2680   case Builtin::BI__sync_val_compare_and_swap_4:
2681   case Builtin::BI__sync_val_compare_and_swap_8:
2682   case Builtin::BI__sync_val_compare_and_swap_16:
2683     BuiltinIndex = 12;
2684     NumFixed = 2;
2685     break;
2686 
2687   case Builtin::BI__sync_bool_compare_and_swap:
2688   case Builtin::BI__sync_bool_compare_and_swap_1:
2689   case Builtin::BI__sync_bool_compare_and_swap_2:
2690   case Builtin::BI__sync_bool_compare_and_swap_4:
2691   case Builtin::BI__sync_bool_compare_and_swap_8:
2692   case Builtin::BI__sync_bool_compare_and_swap_16:
2693     BuiltinIndex = 13;
2694     NumFixed = 2;
2695     ResultType = Context.BoolTy;
2696     break;
2697 
2698   case Builtin::BI__sync_lock_test_and_set:
2699   case Builtin::BI__sync_lock_test_and_set_1:
2700   case Builtin::BI__sync_lock_test_and_set_2:
2701   case Builtin::BI__sync_lock_test_and_set_4:
2702   case Builtin::BI__sync_lock_test_and_set_8:
2703   case Builtin::BI__sync_lock_test_and_set_16:
2704     BuiltinIndex = 14;
2705     break;
2706 
2707   case Builtin::BI__sync_lock_release:
2708   case Builtin::BI__sync_lock_release_1:
2709   case Builtin::BI__sync_lock_release_2:
2710   case Builtin::BI__sync_lock_release_4:
2711   case Builtin::BI__sync_lock_release_8:
2712   case Builtin::BI__sync_lock_release_16:
2713     BuiltinIndex = 15;
2714     NumFixed = 0;
2715     ResultType = Context.VoidTy;
2716     break;
2717 
2718   case Builtin::BI__sync_swap:
2719   case Builtin::BI__sync_swap_1:
2720   case Builtin::BI__sync_swap_2:
2721   case Builtin::BI__sync_swap_4:
2722   case Builtin::BI__sync_swap_8:
2723   case Builtin::BI__sync_swap_16:
2724     BuiltinIndex = 16;
2725     break;
2726   }
2727 
2728   // Now that we know how many fixed arguments we expect, first check that we
2729   // have at least that many.
2730   if (TheCall->getNumArgs() < 1+NumFixed) {
2731     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
2732       << 0 << 1+NumFixed << TheCall->getNumArgs()
2733       << TheCall->getCallee()->getSourceRange();
2734     return ExprError();
2735   }
2736 
2737   if (WarnAboutSemanticsChange) {
2738     Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
2739       << TheCall->getCallee()->getSourceRange();
2740   }
2741 
2742   // Get the decl for the concrete builtin from this, we can tell what the
2743   // concrete integer type we should convert to is.
2744   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
2745   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
2746   FunctionDecl *NewBuiltinDecl;
2747   if (NewBuiltinID == BuiltinID)
2748     NewBuiltinDecl = FDecl;
2749   else {
2750     // Perform builtin lookup to avoid redeclaring it.
2751     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
2752     LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
2753     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
2754     assert(Res.getFoundDecl());
2755     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
2756     if (!NewBuiltinDecl)
2757       return ExprError();
2758   }
2759 
2760   // The first argument --- the pointer --- has a fixed type; we
2761   // deduce the types of the rest of the arguments accordingly.  Walk
2762   // the remaining arguments, converting them to the deduced value type.
2763   for (unsigned i = 0; i != NumFixed; ++i) {
2764     ExprResult Arg = TheCall->getArg(i+1);
2765 
2766     // GCC does an implicit conversion to the pointer or integer ValType.  This
2767     // can fail in some cases (1i -> int**), check for this error case now.
2768     // Initialize the argument.
2769     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
2770                                                    ValType, /*consume*/ false);
2771     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2772     if (Arg.isInvalid())
2773       return ExprError();
2774 
2775     // Okay, we have something that *can* be converted to the right type.  Check
2776     // to see if there is a potentially weird extension going on here.  This can
2777     // happen when you do an atomic operation on something like an char* and
2778     // pass in 42.  The 42 gets converted to char.  This is even more strange
2779     // for things like 45.123 -> char, etc.
2780     // FIXME: Do this check.
2781     TheCall->setArg(i+1, Arg.get());
2782   }
2783 
2784   ASTContext& Context = this->getASTContext();
2785 
2786   // Create a new DeclRefExpr to refer to the new decl.
2787   DeclRefExpr* NewDRE = DeclRefExpr::Create(
2788       Context,
2789       DRE->getQualifierLoc(),
2790       SourceLocation(),
2791       NewBuiltinDecl,
2792       /*enclosing*/ false,
2793       DRE->getLocation(),
2794       Context.BuiltinFnTy,
2795       DRE->getValueKind());
2796 
2797   // Set the callee in the CallExpr.
2798   // FIXME: This loses syntactic information.
2799   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
2800   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
2801                                               CK_BuiltinFnToFnPtr);
2802   TheCall->setCallee(PromotedCall.get());
2803 
2804   // Change the result type of the call to match the original value type. This
2805   // is arbitrary, but the codegen for these builtins ins design to handle it
2806   // gracefully.
2807   TheCall->setType(ResultType);
2808 
2809   return TheCallResult;
2810 }
2811 
2812 /// SemaBuiltinNontemporalOverloaded - We have a call to
2813 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
2814 /// overloaded function based on the pointer type of its last argument.
2815 ///
2816 /// This function goes through and does final semantic checking for these
2817 /// builtins.
2818 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
2819   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
2820   DeclRefExpr *DRE =
2821       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2822   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2823   unsigned BuiltinID = FDecl->getBuiltinID();
2824   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
2825           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
2826          "Unexpected nontemporal load/store builtin!");
2827   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
2828   unsigned numArgs = isStore ? 2 : 1;
2829 
2830   // Ensure that we have the proper number of arguments.
2831   if (checkArgCount(*this, TheCall, numArgs))
2832     return ExprError();
2833 
2834   // Inspect the last argument of the nontemporal builtin.  This should always
2835   // be a pointer type, from which we imply the type of the memory access.
2836   // Because it is a pointer type, we don't have to worry about any implicit
2837   // casts here.
2838   Expr *PointerArg = TheCall->getArg(numArgs - 1);
2839   ExprResult PointerArgResult =
2840       DefaultFunctionArrayLvalueConversion(PointerArg);
2841 
2842   if (PointerArgResult.isInvalid())
2843     return ExprError();
2844   PointerArg = PointerArgResult.get();
2845   TheCall->setArg(numArgs - 1, PointerArg);
2846 
2847   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
2848   if (!pointerType) {
2849     Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
2850         << PointerArg->getType() << PointerArg->getSourceRange();
2851     return ExprError();
2852   }
2853 
2854   QualType ValType = pointerType->getPointeeType();
2855 
2856   // Strip any qualifiers off ValType.
2857   ValType = ValType.getUnqualifiedType();
2858   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2859       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
2860       !ValType->isVectorType()) {
2861     Diag(DRE->getLocStart(),
2862          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
2863         << PointerArg->getType() << PointerArg->getSourceRange();
2864     return ExprError();
2865   }
2866 
2867   if (!isStore) {
2868     TheCall->setType(ValType);
2869     return TheCallResult;
2870   }
2871 
2872   ExprResult ValArg = TheCall->getArg(0);
2873   InitializedEntity Entity = InitializedEntity::InitializeParameter(
2874       Context, ValType, /*consume*/ false);
2875   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
2876   if (ValArg.isInvalid())
2877     return ExprError();
2878 
2879   TheCall->setArg(0, ValArg.get());
2880   TheCall->setType(Context.VoidTy);
2881   return TheCallResult;
2882 }
2883 
2884 /// CheckObjCString - Checks that the argument to the builtin
2885 /// CFString constructor is correct
2886 /// Note: It might also make sense to do the UTF-16 conversion here (would
2887 /// simplify the backend).
2888 bool Sema::CheckObjCString(Expr *Arg) {
2889   Arg = Arg->IgnoreParenCasts();
2890   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
2891 
2892   if (!Literal || !Literal->isAscii()) {
2893     Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
2894       << Arg->getSourceRange();
2895     return true;
2896   }
2897 
2898   if (Literal->containsNonAsciiOrNull()) {
2899     StringRef String = Literal->getString();
2900     unsigned NumBytes = String.size();
2901     SmallVector<UTF16, 128> ToBuf(NumBytes);
2902     const UTF8 *FromPtr = (const UTF8 *)String.data();
2903     UTF16 *ToPtr = &ToBuf[0];
2904 
2905     ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
2906                                                  &ToPtr, ToPtr + NumBytes,
2907                                                  strictConversion);
2908     // Check for conversion failure.
2909     if (Result != conversionOK)
2910       Diag(Arg->getLocStart(),
2911            diag::warn_cfstring_truncated) << Arg->getSourceRange();
2912   }
2913   return false;
2914 }
2915 
2916 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
2917 /// for validity.  Emit an error and return true on failure; return false
2918 /// on success.
2919 bool Sema::SemaBuiltinVAStartImpl(CallExpr *TheCall) {
2920   Expr *Fn = TheCall->getCallee();
2921   if (TheCall->getNumArgs() > 2) {
2922     Diag(TheCall->getArg(2)->getLocStart(),
2923          diag::err_typecheck_call_too_many_args)
2924       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2925       << Fn->getSourceRange()
2926       << SourceRange(TheCall->getArg(2)->getLocStart(),
2927                      (*(TheCall->arg_end()-1))->getLocEnd());
2928     return true;
2929   }
2930 
2931   if (TheCall->getNumArgs() < 2) {
2932     return Diag(TheCall->getLocEnd(),
2933       diag::err_typecheck_call_too_few_args_at_least)
2934       << 0 /*function call*/ << 2 << TheCall->getNumArgs();
2935   }
2936 
2937   // Type-check the first argument normally.
2938   if (checkBuiltinArgument(*this, TheCall, 0))
2939     return true;
2940 
2941   // Determine whether the current function is variadic or not.
2942   BlockScopeInfo *CurBlock = getCurBlock();
2943   bool isVariadic;
2944   if (CurBlock)
2945     isVariadic = CurBlock->TheDecl->isVariadic();
2946   else if (FunctionDecl *FD = getCurFunctionDecl())
2947     isVariadic = FD->isVariadic();
2948   else
2949     isVariadic = getCurMethodDecl()->isVariadic();
2950 
2951   if (!isVariadic) {
2952     Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2953     return true;
2954   }
2955 
2956   // Verify that the second argument to the builtin is the last argument of the
2957   // current function or method.
2958   bool SecondArgIsLastNamedArgument = false;
2959   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
2960 
2961   // These are valid if SecondArgIsLastNamedArgument is false after the next
2962   // block.
2963   QualType Type;
2964   SourceLocation ParamLoc;
2965   bool IsCRegister = false;
2966 
2967   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
2968     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
2969       // FIXME: This isn't correct for methods (results in bogus warning).
2970       // Get the last formal in the current function.
2971       const ParmVarDecl *LastArg;
2972       if (CurBlock)
2973         LastArg = *(CurBlock->TheDecl->param_end()-1);
2974       else if (FunctionDecl *FD = getCurFunctionDecl())
2975         LastArg = *(FD->param_end()-1);
2976       else
2977         LastArg = *(getCurMethodDecl()->param_end()-1);
2978       SecondArgIsLastNamedArgument = PV == LastArg;
2979 
2980       Type = PV->getType();
2981       ParamLoc = PV->getLocation();
2982       IsCRegister =
2983           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
2984     }
2985   }
2986 
2987   if (!SecondArgIsLastNamedArgument)
2988     Diag(TheCall->getArg(1)->getLocStart(),
2989          diag::warn_second_arg_of_va_start_not_last_named_param);
2990   else if (IsCRegister || Type->isReferenceType() ||
2991            Type->isPromotableIntegerType() ||
2992            Type->isSpecificBuiltinType(BuiltinType::Float)) {
2993     unsigned Reason = 0;
2994     if (Type->isReferenceType())  Reason = 1;
2995     else if (IsCRegister)         Reason = 2;
2996     Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
2997     Diag(ParamLoc, diag::note_parameter_type) << Type;
2998   }
2999 
3000   TheCall->setType(Context.VoidTy);
3001   return false;
3002 }
3003 
3004 /// Check the arguments to '__builtin_va_start' for validity, and that
3005 /// it was called from a function of the native ABI.
3006 /// Emit an error and return true on failure; return false on success.
3007 bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
3008   // On x86-64 Unix, don't allow this in Win64 ABI functions.
3009   // On x64 Windows, don't allow this in System V ABI functions.
3010   // (Yes, that means there's no corresponding way to support variadic
3011   // System V ABI functions on Windows.)
3012   if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64) {
3013     unsigned OS = Context.getTargetInfo().getTriple().getOS();
3014     clang::CallingConv CC = CC_C;
3015     if (const FunctionDecl *FD = getCurFunctionDecl())
3016       CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3017     if ((OS == llvm::Triple::Win32 && CC == CC_X86_64SysV) ||
3018         (OS != llvm::Triple::Win32 && CC == CC_X86_64Win64))
3019       return Diag(TheCall->getCallee()->getLocStart(),
3020                   diag::err_va_start_used_in_wrong_abi_function)
3021              << (OS != llvm::Triple::Win32);
3022   }
3023   return SemaBuiltinVAStartImpl(TheCall);
3024 }
3025 
3026 /// Check the arguments to '__builtin_ms_va_start' for validity, and that
3027 /// it was called from a Win64 ABI function.
3028 /// Emit an error and return true on failure; return false on success.
3029 bool Sema::SemaBuiltinMSVAStart(CallExpr *TheCall) {
3030   // This only makes sense for x86-64.
3031   const llvm::Triple &TT = Context.getTargetInfo().getTriple();
3032   Expr *Callee = TheCall->getCallee();
3033   if (TT.getArch() != llvm::Triple::x86_64)
3034     return Diag(Callee->getLocStart(), diag::err_x86_builtin_32_bit_tgt);
3035   // Don't allow this in System V ABI functions.
3036   clang::CallingConv CC = CC_C;
3037   if (const FunctionDecl *FD = getCurFunctionDecl())
3038     CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3039   if (CC == CC_X86_64SysV ||
3040       (TT.getOS() != llvm::Triple::Win32 && CC != CC_X86_64Win64))
3041     return Diag(Callee->getLocStart(),
3042                 diag::err_ms_va_start_used_in_sysv_function);
3043   return SemaBuiltinVAStartImpl(TheCall);
3044 }
3045 
3046 bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
3047   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
3048   //                 const char *named_addr);
3049 
3050   Expr *Func = Call->getCallee();
3051 
3052   if (Call->getNumArgs() < 3)
3053     return Diag(Call->getLocEnd(),
3054                 diag::err_typecheck_call_too_few_args_at_least)
3055            << 0 /*function call*/ << 3 << Call->getNumArgs();
3056 
3057   // Determine whether the current function is variadic or not.
3058   bool IsVariadic;
3059   if (BlockScopeInfo *CurBlock = getCurBlock())
3060     IsVariadic = CurBlock->TheDecl->isVariadic();
3061   else if (FunctionDecl *FD = getCurFunctionDecl())
3062     IsVariadic = FD->isVariadic();
3063   else if (ObjCMethodDecl *MD = getCurMethodDecl())
3064     IsVariadic = MD->isVariadic();
3065   else
3066     llvm_unreachable("unexpected statement type");
3067 
3068   if (!IsVariadic) {
3069     Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
3070     return true;
3071   }
3072 
3073   // Type-check the first argument normally.
3074   if (checkBuiltinArgument(*this, Call, 0))
3075     return true;
3076 
3077   const struct {
3078     unsigned ArgNo;
3079     QualType Type;
3080   } ArgumentTypes[] = {
3081     { 1, Context.getPointerType(Context.CharTy.withConst()) },
3082     { 2, Context.getSizeType() },
3083   };
3084 
3085   for (const auto &AT : ArgumentTypes) {
3086     const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
3087     if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
3088       continue;
3089     Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
3090       << Arg->getType() << AT.Type << 1 /* different class */
3091       << 0 /* qualifier difference */ << 3 /* parameter mismatch */
3092       << AT.ArgNo + 1 << Arg->getType() << AT.Type;
3093   }
3094 
3095   return false;
3096 }
3097 
3098 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
3099 /// friends.  This is declared to take (...), so we have to check everything.
3100 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
3101   if (TheCall->getNumArgs() < 2)
3102     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
3103       << 0 << 2 << TheCall->getNumArgs()/*function call*/;
3104   if (TheCall->getNumArgs() > 2)
3105     return Diag(TheCall->getArg(2)->getLocStart(),
3106                 diag::err_typecheck_call_too_many_args)
3107       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3108       << SourceRange(TheCall->getArg(2)->getLocStart(),
3109                      (*(TheCall->arg_end()-1))->getLocEnd());
3110 
3111   ExprResult OrigArg0 = TheCall->getArg(0);
3112   ExprResult OrigArg1 = TheCall->getArg(1);
3113 
3114   // Do standard promotions between the two arguments, returning their common
3115   // type.
3116   QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
3117   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
3118     return true;
3119 
3120   // Make sure any conversions are pushed back into the call; this is
3121   // type safe since unordered compare builtins are declared as "_Bool
3122   // foo(...)".
3123   TheCall->setArg(0, OrigArg0.get());
3124   TheCall->setArg(1, OrigArg1.get());
3125 
3126   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
3127     return false;
3128 
3129   // If the common type isn't a real floating type, then the arguments were
3130   // invalid for this operation.
3131   if (Res.isNull() || !Res->isRealFloatingType())
3132     return Diag(OrigArg0.get()->getLocStart(),
3133                 diag::err_typecheck_call_invalid_ordered_compare)
3134       << OrigArg0.get()->getType() << OrigArg1.get()->getType()
3135       << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
3136 
3137   return false;
3138 }
3139 
3140 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
3141 /// __builtin_isnan and friends.  This is declared to take (...), so we have
3142 /// to check everything. We expect the last argument to be a floating point
3143 /// value.
3144 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
3145   if (TheCall->getNumArgs() < NumArgs)
3146     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
3147       << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
3148   if (TheCall->getNumArgs() > NumArgs)
3149     return Diag(TheCall->getArg(NumArgs)->getLocStart(),
3150                 diag::err_typecheck_call_too_many_args)
3151       << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
3152       << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
3153                      (*(TheCall->arg_end()-1))->getLocEnd());
3154 
3155   Expr *OrigArg = TheCall->getArg(NumArgs-1);
3156 
3157   if (OrigArg->isTypeDependent())
3158     return false;
3159 
3160   // This operation requires a non-_Complex floating-point number.
3161   if (!OrigArg->getType()->isRealFloatingType())
3162     return Diag(OrigArg->getLocStart(),
3163                 diag::err_typecheck_call_invalid_unary_fp)
3164       << OrigArg->getType() << OrigArg->getSourceRange();
3165 
3166   // If this is an implicit conversion from float -> double, remove it.
3167   if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
3168     Expr *CastArg = Cast->getSubExpr();
3169     if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
3170       assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
3171              "promotion from float to double is the only expected cast here");
3172       Cast->setSubExpr(nullptr);
3173       TheCall->setArg(NumArgs-1, CastArg);
3174     }
3175   }
3176 
3177   return false;
3178 }
3179 
3180 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
3181 // This is declared to take (...), so we have to check everything.
3182 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
3183   if (TheCall->getNumArgs() < 2)
3184     return ExprError(Diag(TheCall->getLocEnd(),
3185                           diag::err_typecheck_call_too_few_args_at_least)
3186                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3187                      << TheCall->getSourceRange());
3188 
3189   // Determine which of the following types of shufflevector we're checking:
3190   // 1) unary, vector mask: (lhs, mask)
3191   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
3192   QualType resType = TheCall->getArg(0)->getType();
3193   unsigned numElements = 0;
3194 
3195   if (!TheCall->getArg(0)->isTypeDependent() &&
3196       !TheCall->getArg(1)->isTypeDependent()) {
3197     QualType LHSType = TheCall->getArg(0)->getType();
3198     QualType RHSType = TheCall->getArg(1)->getType();
3199 
3200     if (!LHSType->isVectorType() || !RHSType->isVectorType())
3201       return ExprError(Diag(TheCall->getLocStart(),
3202                             diag::err_shufflevector_non_vector)
3203                        << SourceRange(TheCall->getArg(0)->getLocStart(),
3204                                       TheCall->getArg(1)->getLocEnd()));
3205 
3206     numElements = LHSType->getAs<VectorType>()->getNumElements();
3207     unsigned numResElements = TheCall->getNumArgs() - 2;
3208 
3209     // Check to see if we have a call with 2 vector arguments, the unary shuffle
3210     // with mask.  If so, verify that RHS is an integer vector type with the
3211     // same number of elts as lhs.
3212     if (TheCall->getNumArgs() == 2) {
3213       if (!RHSType->hasIntegerRepresentation() ||
3214           RHSType->getAs<VectorType>()->getNumElements() != numElements)
3215         return ExprError(Diag(TheCall->getLocStart(),
3216                               diag::err_shufflevector_incompatible_vector)
3217                          << SourceRange(TheCall->getArg(1)->getLocStart(),
3218                                         TheCall->getArg(1)->getLocEnd()));
3219     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
3220       return ExprError(Diag(TheCall->getLocStart(),
3221                             diag::err_shufflevector_incompatible_vector)
3222                        << SourceRange(TheCall->getArg(0)->getLocStart(),
3223                                       TheCall->getArg(1)->getLocEnd()));
3224     } else if (numElements != numResElements) {
3225       QualType eltType = LHSType->getAs<VectorType>()->getElementType();
3226       resType = Context.getVectorType(eltType, numResElements,
3227                                       VectorType::GenericVector);
3228     }
3229   }
3230 
3231   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
3232     if (TheCall->getArg(i)->isTypeDependent() ||
3233         TheCall->getArg(i)->isValueDependent())
3234       continue;
3235 
3236     llvm::APSInt Result(32);
3237     if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
3238       return ExprError(Diag(TheCall->getLocStart(),
3239                             diag::err_shufflevector_nonconstant_argument)
3240                        << TheCall->getArg(i)->getSourceRange());
3241 
3242     // Allow -1 which will be translated to undef in the IR.
3243     if (Result.isSigned() && Result.isAllOnesValue())
3244       continue;
3245 
3246     if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
3247       return ExprError(Diag(TheCall->getLocStart(),
3248                             diag::err_shufflevector_argument_too_large)
3249                        << TheCall->getArg(i)->getSourceRange());
3250   }
3251 
3252   SmallVector<Expr*, 32> exprs;
3253 
3254   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
3255     exprs.push_back(TheCall->getArg(i));
3256     TheCall->setArg(i, nullptr);
3257   }
3258 
3259   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
3260                                          TheCall->getCallee()->getLocStart(),
3261                                          TheCall->getRParenLoc());
3262 }
3263 
3264 /// SemaConvertVectorExpr - Handle __builtin_convertvector
3265 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
3266                                        SourceLocation BuiltinLoc,
3267                                        SourceLocation RParenLoc) {
3268   ExprValueKind VK = VK_RValue;
3269   ExprObjectKind OK = OK_Ordinary;
3270   QualType DstTy = TInfo->getType();
3271   QualType SrcTy = E->getType();
3272 
3273   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
3274     return ExprError(Diag(BuiltinLoc,
3275                           diag::err_convertvector_non_vector)
3276                      << E->getSourceRange());
3277   if (!DstTy->isVectorType() && !DstTy->isDependentType())
3278     return ExprError(Diag(BuiltinLoc,
3279                           diag::err_convertvector_non_vector_type));
3280 
3281   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
3282     unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
3283     unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
3284     if (SrcElts != DstElts)
3285       return ExprError(Diag(BuiltinLoc,
3286                             diag::err_convertvector_incompatible_vector)
3287                        << E->getSourceRange());
3288   }
3289 
3290   return new (Context)
3291       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
3292 }
3293 
3294 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
3295 // This is declared to take (const void*, ...) and can take two
3296 // optional constant int args.
3297 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
3298   unsigned NumArgs = TheCall->getNumArgs();
3299 
3300   if (NumArgs > 3)
3301     return Diag(TheCall->getLocEnd(),
3302              diag::err_typecheck_call_too_many_args_at_most)
3303              << 0 /*function call*/ << 3 << NumArgs
3304              << TheCall->getSourceRange();
3305 
3306   // Argument 0 is checked for us and the remaining arguments must be
3307   // constant integers.
3308   for (unsigned i = 1; i != NumArgs; ++i)
3309     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
3310       return true;
3311 
3312   return false;
3313 }
3314 
3315 /// SemaBuiltinAssume - Handle __assume (MS Extension).
3316 // __assume does not evaluate its arguments, and should warn if its argument
3317 // has side effects.
3318 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
3319   Expr *Arg = TheCall->getArg(0);
3320   if (Arg->isInstantiationDependent()) return false;
3321 
3322   if (Arg->HasSideEffects(Context))
3323     Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
3324       << Arg->getSourceRange()
3325       << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
3326 
3327   return false;
3328 }
3329 
3330 /// Handle __builtin_assume_aligned. This is declared
3331 /// as (const void*, size_t, ...) and can take one optional constant int arg.
3332 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
3333   unsigned NumArgs = TheCall->getNumArgs();
3334 
3335   if (NumArgs > 3)
3336     return Diag(TheCall->getLocEnd(),
3337              diag::err_typecheck_call_too_many_args_at_most)
3338              << 0 /*function call*/ << 3 << NumArgs
3339              << TheCall->getSourceRange();
3340 
3341   // The alignment must be a constant integer.
3342   Expr *Arg = TheCall->getArg(1);
3343 
3344   // We can't check the value of a dependent argument.
3345   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
3346     llvm::APSInt Result;
3347     if (SemaBuiltinConstantArg(TheCall, 1, Result))
3348       return true;
3349 
3350     if (!Result.isPowerOf2())
3351       return Diag(TheCall->getLocStart(),
3352                   diag::err_alignment_not_power_of_two)
3353            << Arg->getSourceRange();
3354   }
3355 
3356   if (NumArgs > 2) {
3357     ExprResult Arg(TheCall->getArg(2));
3358     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3359       Context.getSizeType(), false);
3360     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3361     if (Arg.isInvalid()) return true;
3362     TheCall->setArg(2, Arg.get());
3363   }
3364 
3365   return false;
3366 }
3367 
3368 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
3369 /// TheCall is a constant expression.
3370 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
3371                                   llvm::APSInt &Result) {
3372   Expr *Arg = TheCall->getArg(ArgNum);
3373   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3374   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3375 
3376   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
3377 
3378   if (!Arg->isIntegerConstantExpr(Result, Context))
3379     return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
3380                 << FDecl->getDeclName() <<  Arg->getSourceRange();
3381 
3382   return false;
3383 }
3384 
3385 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
3386 /// TheCall is a constant expression in the range [Low, High].
3387 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
3388                                        int Low, int High) {
3389   llvm::APSInt Result;
3390 
3391   // We can't check the value of a dependent argument.
3392   Expr *Arg = TheCall->getArg(ArgNum);
3393   if (Arg->isTypeDependent() || Arg->isValueDependent())
3394     return false;
3395 
3396   // Check constant-ness first.
3397   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3398     return true;
3399 
3400   if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
3401     return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
3402       << Low << High << Arg->getSourceRange();
3403 
3404   return false;
3405 }
3406 
3407 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
3408 /// TheCall is an ARM/AArch64 special register string literal.
3409 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
3410                                     int ArgNum, unsigned ExpectedFieldNum,
3411                                     bool AllowName) {
3412   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
3413                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
3414                       BuiltinID == ARM::BI__builtin_arm_rsr ||
3415                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
3416                       BuiltinID == ARM::BI__builtin_arm_wsr ||
3417                       BuiltinID == ARM::BI__builtin_arm_wsrp;
3418   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
3419                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
3420                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
3421                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
3422                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
3423                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
3424   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
3425 
3426   // We can't check the value of a dependent argument.
3427   Expr *Arg = TheCall->getArg(ArgNum);
3428   if (Arg->isTypeDependent() || Arg->isValueDependent())
3429     return false;
3430 
3431   // Check if the argument is a string literal.
3432   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3433     return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
3434            << Arg->getSourceRange();
3435 
3436   // Check the type of special register given.
3437   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3438   SmallVector<StringRef, 6> Fields;
3439   Reg.split(Fields, ":");
3440 
3441   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
3442     return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
3443            << Arg->getSourceRange();
3444 
3445   // If the string is the name of a register then we cannot check that it is
3446   // valid here but if the string is of one the forms described in ACLE then we
3447   // can check that the supplied fields are integers and within the valid
3448   // ranges.
3449   if (Fields.size() > 1) {
3450     bool FiveFields = Fields.size() == 5;
3451 
3452     bool ValidString = true;
3453     if (IsARMBuiltin) {
3454       ValidString &= Fields[0].startswith_lower("cp") ||
3455                      Fields[0].startswith_lower("p");
3456       if (ValidString)
3457         Fields[0] =
3458           Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
3459 
3460       ValidString &= Fields[2].startswith_lower("c");
3461       if (ValidString)
3462         Fields[2] = Fields[2].drop_front(1);
3463 
3464       if (FiveFields) {
3465         ValidString &= Fields[3].startswith_lower("c");
3466         if (ValidString)
3467           Fields[3] = Fields[3].drop_front(1);
3468       }
3469     }
3470 
3471     SmallVector<int, 5> Ranges;
3472     if (FiveFields)
3473       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 7, 15, 15});
3474     else
3475       Ranges.append({15, 7, 15});
3476 
3477     for (unsigned i=0; i<Fields.size(); ++i) {
3478       int IntField;
3479       ValidString &= !Fields[i].getAsInteger(10, IntField);
3480       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
3481     }
3482 
3483     if (!ValidString)
3484       return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
3485              << Arg->getSourceRange();
3486 
3487   } else if (IsAArch64Builtin && Fields.size() == 1) {
3488     // If the register name is one of those that appear in the condition below
3489     // and the special register builtin being used is one of the write builtins,
3490     // then we require that the argument provided for writing to the register
3491     // is an integer constant expression. This is because it will be lowered to
3492     // an MSR (immediate) instruction, so we need to know the immediate at
3493     // compile time.
3494     if (TheCall->getNumArgs() != 2)
3495       return false;
3496 
3497     std::string RegLower = Reg.lower();
3498     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
3499         RegLower != "pan" && RegLower != "uao")
3500       return false;
3501 
3502     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
3503   }
3504 
3505   return false;
3506 }
3507 
3508 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
3509 /// This checks that the target supports __builtin_longjmp and
3510 /// that val is a constant 1.
3511 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
3512   if (!Context.getTargetInfo().hasSjLjLowering())
3513     return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
3514              << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
3515 
3516   Expr *Arg = TheCall->getArg(1);
3517   llvm::APSInt Result;
3518 
3519   // TODO: This is less than ideal. Overload this to take a value.
3520   if (SemaBuiltinConstantArg(TheCall, 1, Result))
3521     return true;
3522 
3523   if (Result != 1)
3524     return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
3525              << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
3526 
3527   return false;
3528 }
3529 
3530 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
3531 /// This checks that the target supports __builtin_setjmp.
3532 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
3533   if (!Context.getTargetInfo().hasSjLjLowering())
3534     return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
3535              << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
3536   return false;
3537 }
3538 
3539 namespace {
3540 class UncoveredArgHandler {
3541   enum { Unknown = -1, AllCovered = -2 };
3542   signed FirstUncoveredArg;
3543   SmallVector<const Expr *, 4> DiagnosticExprs;
3544 
3545 public:
3546   UncoveredArgHandler() : FirstUncoveredArg(Unknown) { }
3547 
3548   bool hasUncoveredArg() const {
3549     return (FirstUncoveredArg >= 0);
3550   }
3551 
3552   unsigned getUncoveredArg() const {
3553     assert(hasUncoveredArg() && "no uncovered argument");
3554     return FirstUncoveredArg;
3555   }
3556 
3557   void setAllCovered() {
3558     // A string has been found with all arguments covered, so clear out
3559     // the diagnostics.
3560     DiagnosticExprs.clear();
3561     FirstUncoveredArg = AllCovered;
3562   }
3563 
3564   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
3565     assert(NewFirstUncoveredArg >= 0 && "Outside range");
3566 
3567     // Don't update if a previous string covers all arguments.
3568     if (FirstUncoveredArg == AllCovered)
3569       return;
3570 
3571     // UncoveredArgHandler tracks the highest uncovered argument index
3572     // and with it all the strings that match this index.
3573     if (NewFirstUncoveredArg == FirstUncoveredArg)
3574       DiagnosticExprs.push_back(StrExpr);
3575     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
3576       DiagnosticExprs.clear();
3577       DiagnosticExprs.push_back(StrExpr);
3578       FirstUncoveredArg = NewFirstUncoveredArg;
3579     }
3580   }
3581 
3582   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
3583 };
3584 
3585 enum StringLiteralCheckType {
3586   SLCT_NotALiteral,
3587   SLCT_UncheckedLiteral,
3588   SLCT_CheckedLiteral
3589 };
3590 } // end anonymous namespace
3591 
3592 static void CheckFormatString(Sema &S, const StringLiteral *FExpr,
3593                               const Expr *OrigFormatExpr,
3594                               ArrayRef<const Expr *> Args,
3595                               bool HasVAListArg, unsigned format_idx,
3596                               unsigned firstDataArg,
3597                               Sema::FormatStringType Type,
3598                               bool inFunctionCall,
3599                               Sema::VariadicCallType CallType,
3600                               llvm::SmallBitVector &CheckedVarArgs,
3601                               UncoveredArgHandler &UncoveredArg);
3602 
3603 // Determine if an expression is a string literal or constant string.
3604 // If this function returns false on the arguments to a function expecting a
3605 // format string, we will usually need to emit a warning.
3606 // True string literals are then checked by CheckFormatString.
3607 static StringLiteralCheckType
3608 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
3609                       bool HasVAListArg, unsigned format_idx,
3610                       unsigned firstDataArg, Sema::FormatStringType Type,
3611                       Sema::VariadicCallType CallType, bool InFunctionCall,
3612                       llvm::SmallBitVector &CheckedVarArgs,
3613                       UncoveredArgHandler &UncoveredArg) {
3614  tryAgain:
3615   if (E->isTypeDependent() || E->isValueDependent())
3616     return SLCT_NotALiteral;
3617 
3618   E = E->IgnoreParenCasts();
3619 
3620   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
3621     // Technically -Wformat-nonliteral does not warn about this case.
3622     // The behavior of printf and friends in this case is implementation
3623     // dependent.  Ideally if the format string cannot be null then
3624     // it should have a 'nonnull' attribute in the function prototype.
3625     return SLCT_UncheckedLiteral;
3626 
3627   switch (E->getStmtClass()) {
3628   case Stmt::BinaryConditionalOperatorClass:
3629   case Stmt::ConditionalOperatorClass: {
3630     // The expression is a literal if both sub-expressions were, and it was
3631     // completely checked only if both sub-expressions were checked.
3632     const AbstractConditionalOperator *C =
3633         cast<AbstractConditionalOperator>(E);
3634 
3635     // Determine whether it is necessary to check both sub-expressions, for
3636     // example, because the condition expression is a constant that can be
3637     // evaluated at compile time.
3638     bool CheckLeft = true, CheckRight = true;
3639 
3640     bool Cond;
3641     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
3642       if (Cond)
3643         CheckRight = false;
3644       else
3645         CheckLeft = false;
3646     }
3647 
3648     StringLiteralCheckType Left;
3649     if (!CheckLeft)
3650       Left = SLCT_UncheckedLiteral;
3651     else {
3652       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
3653                                    HasVAListArg, format_idx, firstDataArg,
3654                                    Type, CallType, InFunctionCall,
3655                                    CheckedVarArgs, UncoveredArg);
3656       if (Left == SLCT_NotALiteral || !CheckRight)
3657         return Left;
3658     }
3659 
3660     StringLiteralCheckType Right =
3661         checkFormatStringExpr(S, C->getFalseExpr(), Args,
3662                               HasVAListArg, format_idx, firstDataArg,
3663                               Type, CallType, InFunctionCall, CheckedVarArgs,
3664                               UncoveredArg);
3665 
3666     return (CheckLeft && Left < Right) ? Left : Right;
3667   }
3668 
3669   case Stmt::ImplicitCastExprClass: {
3670     E = cast<ImplicitCastExpr>(E)->getSubExpr();
3671     goto tryAgain;
3672   }
3673 
3674   case Stmt::OpaqueValueExprClass:
3675     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
3676       E = src;
3677       goto tryAgain;
3678     }
3679     return SLCT_NotALiteral;
3680 
3681   case Stmt::PredefinedExprClass:
3682     // While __func__, etc., are technically not string literals, they
3683     // cannot contain format specifiers and thus are not a security
3684     // liability.
3685     return SLCT_UncheckedLiteral;
3686 
3687   case Stmt::DeclRefExprClass: {
3688     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
3689 
3690     // As an exception, do not flag errors for variables binding to
3691     // const string literals.
3692     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
3693       bool isConstant = false;
3694       QualType T = DR->getType();
3695 
3696       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
3697         isConstant = AT->getElementType().isConstant(S.Context);
3698       } else if (const PointerType *PT = T->getAs<PointerType>()) {
3699         isConstant = T.isConstant(S.Context) &&
3700                      PT->getPointeeType().isConstant(S.Context);
3701       } else if (T->isObjCObjectPointerType()) {
3702         // In ObjC, there is usually no "const ObjectPointer" type,
3703         // so don't check if the pointee type is constant.
3704         isConstant = T.isConstant(S.Context);
3705       }
3706 
3707       if (isConstant) {
3708         if (const Expr *Init = VD->getAnyInitializer()) {
3709           // Look through initializers like const char c[] = { "foo" }
3710           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
3711             if (InitList->isStringLiteralInit())
3712               Init = InitList->getInit(0)->IgnoreParenImpCasts();
3713           }
3714           return checkFormatStringExpr(S, Init, Args,
3715                                        HasVAListArg, format_idx,
3716                                        firstDataArg, Type, CallType,
3717                                        /*InFunctionCall*/false, CheckedVarArgs,
3718                                        UncoveredArg);
3719         }
3720       }
3721 
3722       // For vprintf* functions (i.e., HasVAListArg==true), we add a
3723       // special check to see if the format string is a function parameter
3724       // of the function calling the printf function.  If the function
3725       // has an attribute indicating it is a printf-like function, then we
3726       // should suppress warnings concerning non-literals being used in a call
3727       // to a vprintf function.  For example:
3728       //
3729       // void
3730       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
3731       //      va_list ap;
3732       //      va_start(ap, fmt);
3733       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
3734       //      ...
3735       // }
3736       if (HasVAListArg) {
3737         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
3738           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
3739             int PVIndex = PV->getFunctionScopeIndex() + 1;
3740             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
3741               // adjust for implicit parameter
3742               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
3743                 if (MD->isInstance())
3744                   ++PVIndex;
3745               // We also check if the formats are compatible.
3746               // We can't pass a 'scanf' string to a 'printf' function.
3747               if (PVIndex == PVFormat->getFormatIdx() &&
3748                   Type == S.GetFormatStringType(PVFormat))
3749                 return SLCT_UncheckedLiteral;
3750             }
3751           }
3752         }
3753       }
3754     }
3755 
3756     return SLCT_NotALiteral;
3757   }
3758 
3759   case Stmt::CallExprClass:
3760   case Stmt::CXXMemberCallExprClass: {
3761     const CallExpr *CE = cast<CallExpr>(E);
3762     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
3763       if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
3764         unsigned ArgIndex = FA->getFormatIdx();
3765         if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
3766           if (MD->isInstance())
3767             --ArgIndex;
3768         const Expr *Arg = CE->getArg(ArgIndex - 1);
3769 
3770         return checkFormatStringExpr(S, Arg, Args,
3771                                      HasVAListArg, format_idx, firstDataArg,
3772                                      Type, CallType, InFunctionCall,
3773                                      CheckedVarArgs, UncoveredArg);
3774       } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
3775         unsigned BuiltinID = FD->getBuiltinID();
3776         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
3777             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
3778           const Expr *Arg = CE->getArg(0);
3779           return checkFormatStringExpr(S, Arg, Args,
3780                                        HasVAListArg, format_idx,
3781                                        firstDataArg, Type, CallType,
3782                                        InFunctionCall, CheckedVarArgs,
3783                                        UncoveredArg);
3784         }
3785       }
3786     }
3787 
3788     return SLCT_NotALiteral;
3789   }
3790   case Stmt::ObjCStringLiteralClass:
3791   case Stmt::StringLiteralClass: {
3792     const StringLiteral *StrE = nullptr;
3793 
3794     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
3795       StrE = ObjCFExpr->getString();
3796     else
3797       StrE = cast<StringLiteral>(E);
3798 
3799     if (StrE) {
3800       CheckFormatString(S, StrE, E, Args, HasVAListArg, format_idx,
3801                         firstDataArg, Type, InFunctionCall, CallType,
3802                         CheckedVarArgs, UncoveredArg);
3803       return SLCT_CheckedLiteral;
3804     }
3805 
3806     return SLCT_NotALiteral;
3807   }
3808 
3809   default:
3810     return SLCT_NotALiteral;
3811   }
3812 }
3813 
3814 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
3815   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
3816   .Case("scanf", FST_Scanf)
3817   .Cases("printf", "printf0", FST_Printf)
3818   .Cases("NSString", "CFString", FST_NSString)
3819   .Case("strftime", FST_Strftime)
3820   .Case("strfmon", FST_Strfmon)
3821   .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
3822   .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
3823   .Case("os_trace", FST_OSTrace)
3824   .Default(FST_Unknown);
3825 }
3826 
3827 /// CheckFormatArguments - Check calls to printf and scanf (and similar
3828 /// functions) for correct use of format strings.
3829 /// Returns true if a format string has been fully checked.
3830 bool Sema::CheckFormatArguments(const FormatAttr *Format,
3831                                 ArrayRef<const Expr *> Args,
3832                                 bool IsCXXMember,
3833                                 VariadicCallType CallType,
3834                                 SourceLocation Loc, SourceRange Range,
3835                                 llvm::SmallBitVector &CheckedVarArgs) {
3836   FormatStringInfo FSI;
3837   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
3838     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
3839                                 FSI.FirstDataArg, GetFormatStringType(Format),
3840                                 CallType, Loc, Range, CheckedVarArgs);
3841   return false;
3842 }
3843 
3844 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
3845                                 bool HasVAListArg, unsigned format_idx,
3846                                 unsigned firstDataArg, FormatStringType Type,
3847                                 VariadicCallType CallType,
3848                                 SourceLocation Loc, SourceRange Range,
3849                                 llvm::SmallBitVector &CheckedVarArgs) {
3850   // CHECK: printf/scanf-like function is called with no format string.
3851   if (format_idx >= Args.size()) {
3852     Diag(Loc, diag::warn_missing_format_string) << Range;
3853     return false;
3854   }
3855 
3856   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
3857 
3858   // CHECK: format string is not a string literal.
3859   //
3860   // Dynamically generated format strings are difficult to
3861   // automatically vet at compile time.  Requiring that format strings
3862   // are string literals: (1) permits the checking of format strings by
3863   // the compiler and thereby (2) can practically remove the source of
3864   // many format string exploits.
3865 
3866   // Format string can be either ObjC string (e.g. @"%d") or
3867   // C string (e.g. "%d")
3868   // ObjC string uses the same format specifiers as C string, so we can use
3869   // the same format string checking logic for both ObjC and C strings.
3870   UncoveredArgHandler UncoveredArg;
3871   StringLiteralCheckType CT =
3872       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
3873                             format_idx, firstDataArg, Type, CallType,
3874                             /*IsFunctionCall*/true, CheckedVarArgs,
3875                             UncoveredArg);
3876 
3877   // Generate a diagnostic where an uncovered argument is detected.
3878   if (UncoveredArg.hasUncoveredArg()) {
3879     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
3880     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
3881     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
3882   }
3883 
3884   if (CT != SLCT_NotALiteral)
3885     // Literal format string found, check done!
3886     return CT == SLCT_CheckedLiteral;
3887 
3888   // Strftime is particular as it always uses a single 'time' argument,
3889   // so it is safe to pass a non-literal string.
3890   if (Type == FST_Strftime)
3891     return false;
3892 
3893   // Do not emit diag when the string param is a macro expansion and the
3894   // format is either NSString or CFString. This is a hack to prevent
3895   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
3896   // which are usually used in place of NS and CF string literals.
3897   SourceLocation FormatLoc = Args[format_idx]->getLocStart();
3898   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
3899     return false;
3900 
3901   // If there are no arguments specified, warn with -Wformat-security, otherwise
3902   // warn only with -Wformat-nonliteral.
3903   if (Args.size() == firstDataArg) {
3904     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
3905       << OrigFormatExpr->getSourceRange();
3906     switch (Type) {
3907     default:
3908       break;
3909     case FST_Kprintf:
3910     case FST_FreeBSDKPrintf:
3911     case FST_Printf:
3912       Diag(FormatLoc, diag::note_format_security_fixit)
3913         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
3914       break;
3915     case FST_NSString:
3916       Diag(FormatLoc, diag::note_format_security_fixit)
3917         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
3918       break;
3919     }
3920   } else {
3921     Diag(FormatLoc, diag::warn_format_nonliteral)
3922       << OrigFormatExpr->getSourceRange();
3923   }
3924   return false;
3925 }
3926 
3927 namespace {
3928 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
3929 protected:
3930   Sema &S;
3931   const StringLiteral *FExpr;
3932   const Expr *OrigFormatExpr;
3933   const unsigned FirstDataArg;
3934   const unsigned NumDataArgs;
3935   const char *Beg; // Start of format string.
3936   const bool HasVAListArg;
3937   ArrayRef<const Expr *> Args;
3938   unsigned FormatIdx;
3939   llvm::SmallBitVector CoveredArgs;
3940   bool usesPositionalArgs;
3941   bool atFirstArg;
3942   bool inFunctionCall;
3943   Sema::VariadicCallType CallType;
3944   llvm::SmallBitVector &CheckedVarArgs;
3945   UncoveredArgHandler &UncoveredArg;
3946 
3947 public:
3948   CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
3949                      const Expr *origFormatExpr, unsigned firstDataArg,
3950                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
3951                      ArrayRef<const Expr *> Args,
3952                      unsigned formatIdx, bool inFunctionCall,
3953                      Sema::VariadicCallType callType,
3954                      llvm::SmallBitVector &CheckedVarArgs,
3955                      UncoveredArgHandler &UncoveredArg)
3956     : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
3957       FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
3958       Beg(beg), HasVAListArg(hasVAListArg),
3959       Args(Args), FormatIdx(formatIdx),
3960       usesPositionalArgs(false), atFirstArg(true),
3961       inFunctionCall(inFunctionCall), CallType(callType),
3962       CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
3963     CoveredArgs.resize(numDataArgs);
3964     CoveredArgs.reset();
3965   }
3966 
3967   void DoneProcessing();
3968 
3969   void HandleIncompleteSpecifier(const char *startSpecifier,
3970                                  unsigned specifierLen) override;
3971 
3972   void HandleInvalidLengthModifier(
3973                            const analyze_format_string::FormatSpecifier &FS,
3974                            const analyze_format_string::ConversionSpecifier &CS,
3975                            const char *startSpecifier, unsigned specifierLen,
3976                            unsigned DiagID);
3977 
3978   void HandleNonStandardLengthModifier(
3979                     const analyze_format_string::FormatSpecifier &FS,
3980                     const char *startSpecifier, unsigned specifierLen);
3981 
3982   void HandleNonStandardConversionSpecifier(
3983                     const analyze_format_string::ConversionSpecifier &CS,
3984                     const char *startSpecifier, unsigned specifierLen);
3985 
3986   void HandlePosition(const char *startPos, unsigned posLen) override;
3987 
3988   void HandleInvalidPosition(const char *startSpecifier,
3989                              unsigned specifierLen,
3990                              analyze_format_string::PositionContext p) override;
3991 
3992   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
3993 
3994   void HandleNullChar(const char *nullCharacter) override;
3995 
3996   template <typename Range>
3997   static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
3998                                    const Expr *ArgumentExpr,
3999                                    PartialDiagnostic PDiag,
4000                                    SourceLocation StringLoc,
4001                                    bool IsStringLocation, Range StringRange,
4002                                    ArrayRef<FixItHint> Fixit = None);
4003 
4004 protected:
4005   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
4006                                         const char *startSpec,
4007                                         unsigned specifierLen,
4008                                         const char *csStart, unsigned csLen);
4009 
4010   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
4011                                          const char *startSpec,
4012                                          unsigned specifierLen);
4013 
4014   SourceRange getFormatStringRange();
4015   CharSourceRange getSpecifierRange(const char *startSpecifier,
4016                                     unsigned specifierLen);
4017   SourceLocation getLocationOfByte(const char *x);
4018 
4019   const Expr *getDataArg(unsigned i) const;
4020 
4021   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
4022                     const analyze_format_string::ConversionSpecifier &CS,
4023                     const char *startSpecifier, unsigned specifierLen,
4024                     unsigned argIndex);
4025 
4026   template <typename Range>
4027   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
4028                             bool IsStringLocation, Range StringRange,
4029                             ArrayRef<FixItHint> Fixit = None);
4030 };
4031 } // end anonymous namespace
4032 
4033 SourceRange CheckFormatHandler::getFormatStringRange() {
4034   return OrigFormatExpr->getSourceRange();
4035 }
4036 
4037 CharSourceRange CheckFormatHandler::
4038 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
4039   SourceLocation Start = getLocationOfByte(startSpecifier);
4040   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
4041 
4042   // Advance the end SourceLocation by one due to half-open ranges.
4043   End = End.getLocWithOffset(1);
4044 
4045   return CharSourceRange::getCharRange(Start, End);
4046 }
4047 
4048 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
4049   return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
4050 }
4051 
4052 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
4053                                                    unsigned specifierLen){
4054   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
4055                        getLocationOfByte(startSpecifier),
4056                        /*IsStringLocation*/true,
4057                        getSpecifierRange(startSpecifier, specifierLen));
4058 }
4059 
4060 void CheckFormatHandler::HandleInvalidLengthModifier(
4061     const analyze_format_string::FormatSpecifier &FS,
4062     const analyze_format_string::ConversionSpecifier &CS,
4063     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
4064   using namespace analyze_format_string;
4065 
4066   const LengthModifier &LM = FS.getLengthModifier();
4067   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
4068 
4069   // See if we know how to fix this length modifier.
4070   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
4071   if (FixedLM) {
4072     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
4073                          getLocationOfByte(LM.getStart()),
4074                          /*IsStringLocation*/true,
4075                          getSpecifierRange(startSpecifier, specifierLen));
4076 
4077     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
4078       << FixedLM->toString()
4079       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
4080 
4081   } else {
4082     FixItHint Hint;
4083     if (DiagID == diag::warn_format_nonsensical_length)
4084       Hint = FixItHint::CreateRemoval(LMRange);
4085 
4086     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
4087                          getLocationOfByte(LM.getStart()),
4088                          /*IsStringLocation*/true,
4089                          getSpecifierRange(startSpecifier, specifierLen),
4090                          Hint);
4091   }
4092 }
4093 
4094 void CheckFormatHandler::HandleNonStandardLengthModifier(
4095     const analyze_format_string::FormatSpecifier &FS,
4096     const char *startSpecifier, unsigned specifierLen) {
4097   using namespace analyze_format_string;
4098 
4099   const LengthModifier &LM = FS.getLengthModifier();
4100   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
4101 
4102   // See if we know how to fix this length modifier.
4103   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
4104   if (FixedLM) {
4105     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4106                            << LM.toString() << 0,
4107                          getLocationOfByte(LM.getStart()),
4108                          /*IsStringLocation*/true,
4109                          getSpecifierRange(startSpecifier, specifierLen));
4110 
4111     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
4112       << FixedLM->toString()
4113       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
4114 
4115   } else {
4116     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4117                            << LM.toString() << 0,
4118                          getLocationOfByte(LM.getStart()),
4119                          /*IsStringLocation*/true,
4120                          getSpecifierRange(startSpecifier, specifierLen));
4121   }
4122 }
4123 
4124 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
4125     const analyze_format_string::ConversionSpecifier &CS,
4126     const char *startSpecifier, unsigned specifierLen) {
4127   using namespace analyze_format_string;
4128 
4129   // See if we know how to fix this conversion specifier.
4130   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
4131   if (FixedCS) {
4132     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4133                           << CS.toString() << /*conversion specifier*/1,
4134                          getLocationOfByte(CS.getStart()),
4135                          /*IsStringLocation*/true,
4136                          getSpecifierRange(startSpecifier, specifierLen));
4137 
4138     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
4139     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
4140       << FixedCS->toString()
4141       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
4142   } else {
4143     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4144                           << CS.toString() << /*conversion specifier*/1,
4145                          getLocationOfByte(CS.getStart()),
4146                          /*IsStringLocation*/true,
4147                          getSpecifierRange(startSpecifier, specifierLen));
4148   }
4149 }
4150 
4151 void CheckFormatHandler::HandlePosition(const char *startPos,
4152                                         unsigned posLen) {
4153   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
4154                                getLocationOfByte(startPos),
4155                                /*IsStringLocation*/true,
4156                                getSpecifierRange(startPos, posLen));
4157 }
4158 
4159 void
4160 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
4161                                      analyze_format_string::PositionContext p) {
4162   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
4163                          << (unsigned) p,
4164                        getLocationOfByte(startPos), /*IsStringLocation*/true,
4165                        getSpecifierRange(startPos, posLen));
4166 }
4167 
4168 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
4169                                             unsigned posLen) {
4170   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
4171                                getLocationOfByte(startPos),
4172                                /*IsStringLocation*/true,
4173                                getSpecifierRange(startPos, posLen));
4174 }
4175 
4176 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
4177   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
4178     // The presence of a null character is likely an error.
4179     EmitFormatDiagnostic(
4180       S.PDiag(diag::warn_printf_format_string_contains_null_char),
4181       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
4182       getFormatStringRange());
4183   }
4184 }
4185 
4186 // Note that this may return NULL if there was an error parsing or building
4187 // one of the argument expressions.
4188 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
4189   return Args[FirstDataArg + i];
4190 }
4191 
4192 void CheckFormatHandler::DoneProcessing() {
4193   // Does the number of data arguments exceed the number of
4194   // format conversions in the format string?
4195   if (!HasVAListArg) {
4196       // Find any arguments that weren't covered.
4197     CoveredArgs.flip();
4198     signed notCoveredArg = CoveredArgs.find_first();
4199     if (notCoveredArg >= 0) {
4200       assert((unsigned)notCoveredArg < NumDataArgs);
4201       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
4202     } else {
4203       UncoveredArg.setAllCovered();
4204     }
4205   }
4206 }
4207 
4208 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
4209                                    const Expr *ArgExpr) {
4210   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
4211          "Invalid state");
4212 
4213   if (!ArgExpr)
4214     return;
4215 
4216   SourceLocation Loc = ArgExpr->getLocStart();
4217 
4218   if (S.getSourceManager().isInSystemMacro(Loc))
4219     return;
4220 
4221   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
4222   for (auto E : DiagnosticExprs)
4223     PDiag << E->getSourceRange();
4224 
4225   CheckFormatHandler::EmitFormatDiagnostic(
4226                                   S, IsFunctionCall, DiagnosticExprs[0],
4227                                   PDiag, Loc, /*IsStringLocation*/false,
4228                                   DiagnosticExprs[0]->getSourceRange());
4229 }
4230 
4231 bool
4232 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
4233                                                      SourceLocation Loc,
4234                                                      const char *startSpec,
4235                                                      unsigned specifierLen,
4236                                                      const char *csStart,
4237                                                      unsigned csLen) {
4238   bool keepGoing = true;
4239   if (argIndex < NumDataArgs) {
4240     // Consider the argument coverered, even though the specifier doesn't
4241     // make sense.
4242     CoveredArgs.set(argIndex);
4243   }
4244   else {
4245     // If argIndex exceeds the number of data arguments we
4246     // don't issue a warning because that is just a cascade of warnings (and
4247     // they may have intended '%%' anyway). We don't want to continue processing
4248     // the format string after this point, however, as we will like just get
4249     // gibberish when trying to match arguments.
4250     keepGoing = false;
4251   }
4252 
4253   StringRef Specifier(csStart, csLen);
4254 
4255   // If the specifier in non-printable, it could be the first byte of a UTF-8
4256   // sequence. In that case, print the UTF-8 code point. If not, print the byte
4257   // hex value.
4258   std::string CodePointStr;
4259   if (!llvm::sys::locale::isPrint(*csStart)) {
4260     UTF32 CodePoint;
4261     const UTF8 **B = reinterpret_cast<const UTF8 **>(&csStart);
4262     const UTF8 *E =
4263         reinterpret_cast<const UTF8 *>(csStart + csLen);
4264     ConversionResult Result =
4265         llvm::convertUTF8Sequence(B, E, &CodePoint, strictConversion);
4266 
4267     if (Result != conversionOK) {
4268       unsigned char FirstChar = *csStart;
4269       CodePoint = (UTF32)FirstChar;
4270     }
4271 
4272     llvm::raw_string_ostream OS(CodePointStr);
4273     if (CodePoint < 256)
4274       OS << "\\x" << llvm::format("%02x", CodePoint);
4275     else if (CodePoint <= 0xFFFF)
4276       OS << "\\u" << llvm::format("%04x", CodePoint);
4277     else
4278       OS << "\\U" << llvm::format("%08x", CodePoint);
4279     OS.flush();
4280     Specifier = CodePointStr;
4281   }
4282 
4283   EmitFormatDiagnostic(
4284       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
4285       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
4286 
4287   return keepGoing;
4288 }
4289 
4290 void
4291 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
4292                                                       const char *startSpec,
4293                                                       unsigned specifierLen) {
4294   EmitFormatDiagnostic(
4295     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
4296     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
4297 }
4298 
4299 bool
4300 CheckFormatHandler::CheckNumArgs(
4301   const analyze_format_string::FormatSpecifier &FS,
4302   const analyze_format_string::ConversionSpecifier &CS,
4303   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
4304 
4305   if (argIndex >= NumDataArgs) {
4306     PartialDiagnostic PDiag = FS.usesPositionalArg()
4307       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
4308            << (argIndex+1) << NumDataArgs)
4309       : S.PDiag(diag::warn_printf_insufficient_data_args);
4310     EmitFormatDiagnostic(
4311       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
4312       getSpecifierRange(startSpecifier, specifierLen));
4313 
4314     // Since more arguments than conversion tokens are given, by extension
4315     // all arguments are covered, so mark this as so.
4316     UncoveredArg.setAllCovered();
4317     return false;
4318   }
4319   return true;
4320 }
4321 
4322 template<typename Range>
4323 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
4324                                               SourceLocation Loc,
4325                                               bool IsStringLocation,
4326                                               Range StringRange,
4327                                               ArrayRef<FixItHint> FixIt) {
4328   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
4329                        Loc, IsStringLocation, StringRange, FixIt);
4330 }
4331 
4332 /// \brief If the format string is not within the funcion call, emit a note
4333 /// so that the function call and string are in diagnostic messages.
4334 ///
4335 /// \param InFunctionCall if true, the format string is within the function
4336 /// call and only one diagnostic message will be produced.  Otherwise, an
4337 /// extra note will be emitted pointing to location of the format string.
4338 ///
4339 /// \param ArgumentExpr the expression that is passed as the format string
4340 /// argument in the function call.  Used for getting locations when two
4341 /// diagnostics are emitted.
4342 ///
4343 /// \param PDiag the callee should already have provided any strings for the
4344 /// diagnostic message.  This function only adds locations and fixits
4345 /// to diagnostics.
4346 ///
4347 /// \param Loc primary location for diagnostic.  If two diagnostics are
4348 /// required, one will be at Loc and a new SourceLocation will be created for
4349 /// the other one.
4350 ///
4351 /// \param IsStringLocation if true, Loc points to the format string should be
4352 /// used for the note.  Otherwise, Loc points to the argument list and will
4353 /// be used with PDiag.
4354 ///
4355 /// \param StringRange some or all of the string to highlight.  This is
4356 /// templated so it can accept either a CharSourceRange or a SourceRange.
4357 ///
4358 /// \param FixIt optional fix it hint for the format string.
4359 template<typename Range>
4360 void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
4361                                               const Expr *ArgumentExpr,
4362                                               PartialDiagnostic PDiag,
4363                                               SourceLocation Loc,
4364                                               bool IsStringLocation,
4365                                               Range StringRange,
4366                                               ArrayRef<FixItHint> FixIt) {
4367   if (InFunctionCall) {
4368     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
4369     D << StringRange;
4370     D << FixIt;
4371   } else {
4372     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
4373       << ArgumentExpr->getSourceRange();
4374 
4375     const Sema::SemaDiagnosticBuilder &Note =
4376       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
4377              diag::note_format_string_defined);
4378 
4379     Note << StringRange;
4380     Note << FixIt;
4381   }
4382 }
4383 
4384 //===--- CHECK: Printf format string checking ------------------------------===//
4385 
4386 namespace {
4387 class CheckPrintfHandler : public CheckFormatHandler {
4388   bool ObjCContext;
4389 
4390 public:
4391   CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
4392                      const Expr *origFormatExpr, unsigned firstDataArg,
4393                      unsigned numDataArgs, bool isObjC,
4394                      const char *beg, bool hasVAListArg,
4395                      ArrayRef<const Expr *> Args,
4396                      unsigned formatIdx, bool inFunctionCall,
4397                      Sema::VariadicCallType CallType,
4398                      llvm::SmallBitVector &CheckedVarArgs,
4399                      UncoveredArgHandler &UncoveredArg)
4400     : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
4401                          numDataArgs, beg, hasVAListArg, Args,
4402                          formatIdx, inFunctionCall, CallType, CheckedVarArgs,
4403                          UncoveredArg),
4404       ObjCContext(isObjC)
4405   {}
4406 
4407   bool HandleInvalidPrintfConversionSpecifier(
4408                                       const analyze_printf::PrintfSpecifier &FS,
4409                                       const char *startSpecifier,
4410                                       unsigned specifierLen) override;
4411 
4412   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
4413                              const char *startSpecifier,
4414                              unsigned specifierLen) override;
4415   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
4416                        const char *StartSpecifier,
4417                        unsigned SpecifierLen,
4418                        const Expr *E);
4419 
4420   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
4421                     const char *startSpecifier, unsigned specifierLen);
4422   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
4423                            const analyze_printf::OptionalAmount &Amt,
4424                            unsigned type,
4425                            const char *startSpecifier, unsigned specifierLen);
4426   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
4427                   const analyze_printf::OptionalFlag &flag,
4428                   const char *startSpecifier, unsigned specifierLen);
4429   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
4430                          const analyze_printf::OptionalFlag &ignoredFlag,
4431                          const analyze_printf::OptionalFlag &flag,
4432                          const char *startSpecifier, unsigned specifierLen);
4433   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
4434                            const Expr *E);
4435 
4436   void HandleEmptyObjCModifierFlag(const char *startFlag,
4437                                    unsigned flagLen) override;
4438 
4439   void HandleInvalidObjCModifierFlag(const char *startFlag,
4440                                             unsigned flagLen) override;
4441 
4442   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
4443                                            const char *flagsEnd,
4444                                            const char *conversionPosition)
4445                                              override;
4446 };
4447 } // end anonymous namespace
4448 
4449 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
4450                                       const analyze_printf::PrintfSpecifier &FS,
4451                                       const char *startSpecifier,
4452                                       unsigned specifierLen) {
4453   const analyze_printf::PrintfConversionSpecifier &CS =
4454     FS.getConversionSpecifier();
4455 
4456   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
4457                                           getLocationOfByte(CS.getStart()),
4458                                           startSpecifier, specifierLen,
4459                                           CS.getStart(), CS.getLength());
4460 }
4461 
4462 bool CheckPrintfHandler::HandleAmount(
4463                                const analyze_format_string::OptionalAmount &Amt,
4464                                unsigned k, const char *startSpecifier,
4465                                unsigned specifierLen) {
4466   if (Amt.hasDataArgument()) {
4467     if (!HasVAListArg) {
4468       unsigned argIndex = Amt.getArgIndex();
4469       if (argIndex >= NumDataArgs) {
4470         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
4471                                << k,
4472                              getLocationOfByte(Amt.getStart()),
4473                              /*IsStringLocation*/true,
4474                              getSpecifierRange(startSpecifier, specifierLen));
4475         // Don't do any more checking.  We will just emit
4476         // spurious errors.
4477         return false;
4478       }
4479 
4480       // Type check the data argument.  It should be an 'int'.
4481       // Although not in conformance with C99, we also allow the argument to be
4482       // an 'unsigned int' as that is a reasonably safe case.  GCC also
4483       // doesn't emit a warning for that case.
4484       CoveredArgs.set(argIndex);
4485       const Expr *Arg = getDataArg(argIndex);
4486       if (!Arg)
4487         return false;
4488 
4489       QualType T = Arg->getType();
4490 
4491       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
4492       assert(AT.isValid());
4493 
4494       if (!AT.matchesType(S.Context, T)) {
4495         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
4496                                << k << AT.getRepresentativeTypeName(S.Context)
4497                                << T << Arg->getSourceRange(),
4498                              getLocationOfByte(Amt.getStart()),
4499                              /*IsStringLocation*/true,
4500                              getSpecifierRange(startSpecifier, specifierLen));
4501         // Don't do any more checking.  We will just emit
4502         // spurious errors.
4503         return false;
4504       }
4505     }
4506   }
4507   return true;
4508 }
4509 
4510 void CheckPrintfHandler::HandleInvalidAmount(
4511                                       const analyze_printf::PrintfSpecifier &FS,
4512                                       const analyze_printf::OptionalAmount &Amt,
4513                                       unsigned type,
4514                                       const char *startSpecifier,
4515                                       unsigned specifierLen) {
4516   const analyze_printf::PrintfConversionSpecifier &CS =
4517     FS.getConversionSpecifier();
4518 
4519   FixItHint fixit =
4520     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
4521       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
4522                                  Amt.getConstantLength()))
4523       : FixItHint();
4524 
4525   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
4526                          << type << CS.toString(),
4527                        getLocationOfByte(Amt.getStart()),
4528                        /*IsStringLocation*/true,
4529                        getSpecifierRange(startSpecifier, specifierLen),
4530                        fixit);
4531 }
4532 
4533 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
4534                                     const analyze_printf::OptionalFlag &flag,
4535                                     const char *startSpecifier,
4536                                     unsigned specifierLen) {
4537   // Warn about pointless flag with a fixit removal.
4538   const analyze_printf::PrintfConversionSpecifier &CS =
4539     FS.getConversionSpecifier();
4540   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
4541                          << flag.toString() << CS.toString(),
4542                        getLocationOfByte(flag.getPosition()),
4543                        /*IsStringLocation*/true,
4544                        getSpecifierRange(startSpecifier, specifierLen),
4545                        FixItHint::CreateRemoval(
4546                          getSpecifierRange(flag.getPosition(), 1)));
4547 }
4548 
4549 void CheckPrintfHandler::HandleIgnoredFlag(
4550                                 const analyze_printf::PrintfSpecifier &FS,
4551                                 const analyze_printf::OptionalFlag &ignoredFlag,
4552                                 const analyze_printf::OptionalFlag &flag,
4553                                 const char *startSpecifier,
4554                                 unsigned specifierLen) {
4555   // Warn about ignored flag with a fixit removal.
4556   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
4557                          << ignoredFlag.toString() << flag.toString(),
4558                        getLocationOfByte(ignoredFlag.getPosition()),
4559                        /*IsStringLocation*/true,
4560                        getSpecifierRange(startSpecifier, specifierLen),
4561                        FixItHint::CreateRemoval(
4562                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
4563 }
4564 
4565 //  void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
4566 //                            bool IsStringLocation, Range StringRange,
4567 //                            ArrayRef<FixItHint> Fixit = None);
4568 
4569 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
4570                                                      unsigned flagLen) {
4571   // Warn about an empty flag.
4572   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
4573                        getLocationOfByte(startFlag),
4574                        /*IsStringLocation*/true,
4575                        getSpecifierRange(startFlag, flagLen));
4576 }
4577 
4578 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
4579                                                        unsigned flagLen) {
4580   // Warn about an invalid flag.
4581   auto Range = getSpecifierRange(startFlag, flagLen);
4582   StringRef flag(startFlag, flagLen);
4583   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
4584                       getLocationOfByte(startFlag),
4585                       /*IsStringLocation*/true,
4586                       Range, FixItHint::CreateRemoval(Range));
4587 }
4588 
4589 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
4590     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
4591     // Warn about using '[...]' without a '@' conversion.
4592     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
4593     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
4594     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
4595                          getLocationOfByte(conversionPosition),
4596                          /*IsStringLocation*/true,
4597                          Range, FixItHint::CreateRemoval(Range));
4598 }
4599 
4600 // Determines if the specified is a C++ class or struct containing
4601 // a member with the specified name and kind (e.g. a CXXMethodDecl named
4602 // "c_str()").
4603 template<typename MemberKind>
4604 static llvm::SmallPtrSet<MemberKind*, 1>
4605 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
4606   const RecordType *RT = Ty->getAs<RecordType>();
4607   llvm::SmallPtrSet<MemberKind*, 1> Results;
4608 
4609   if (!RT)
4610     return Results;
4611   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
4612   if (!RD || !RD->getDefinition())
4613     return Results;
4614 
4615   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
4616                  Sema::LookupMemberName);
4617   R.suppressDiagnostics();
4618 
4619   // We just need to include all members of the right kind turned up by the
4620   // filter, at this point.
4621   if (S.LookupQualifiedName(R, RT->getDecl()))
4622     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
4623       NamedDecl *decl = (*I)->getUnderlyingDecl();
4624       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
4625         Results.insert(FK);
4626     }
4627   return Results;
4628 }
4629 
4630 /// Check if we could call '.c_str()' on an object.
4631 ///
4632 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
4633 /// allow the call, or if it would be ambiguous).
4634 bool Sema::hasCStrMethod(const Expr *E) {
4635   typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
4636   MethodSet Results =
4637       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
4638   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
4639        MI != ME; ++MI)
4640     if ((*MI)->getMinRequiredArguments() == 0)
4641       return true;
4642   return false;
4643 }
4644 
4645 // Check if a (w)string was passed when a (w)char* was needed, and offer a
4646 // better diagnostic if so. AT is assumed to be valid.
4647 // Returns true when a c_str() conversion method is found.
4648 bool CheckPrintfHandler::checkForCStrMembers(
4649     const analyze_printf::ArgType &AT, const Expr *E) {
4650   typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
4651 
4652   MethodSet Results =
4653       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
4654 
4655   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
4656        MI != ME; ++MI) {
4657     const CXXMethodDecl *Method = *MI;
4658     if (Method->getMinRequiredArguments() == 0 &&
4659         AT.matchesType(S.Context, Method->getReturnType())) {
4660       // FIXME: Suggest parens if the expression needs them.
4661       SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
4662       S.Diag(E->getLocStart(), diag::note_printf_c_str)
4663           << "c_str()"
4664           << FixItHint::CreateInsertion(EndLoc, ".c_str()");
4665       return true;
4666     }
4667   }
4668 
4669   return false;
4670 }
4671 
4672 bool
4673 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
4674                                             &FS,
4675                                           const char *startSpecifier,
4676                                           unsigned specifierLen) {
4677   using namespace analyze_format_string;
4678   using namespace analyze_printf;
4679   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
4680 
4681   if (FS.consumesDataArgument()) {
4682     if (atFirstArg) {
4683         atFirstArg = false;
4684         usesPositionalArgs = FS.usesPositionalArg();
4685     }
4686     else if (usesPositionalArgs != FS.usesPositionalArg()) {
4687       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
4688                                         startSpecifier, specifierLen);
4689       return false;
4690     }
4691   }
4692 
4693   // First check if the field width, precision, and conversion specifier
4694   // have matching data arguments.
4695   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
4696                     startSpecifier, specifierLen)) {
4697     return false;
4698   }
4699 
4700   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
4701                     startSpecifier, specifierLen)) {
4702     return false;
4703   }
4704 
4705   if (!CS.consumesDataArgument()) {
4706     // FIXME: Technically specifying a precision or field width here
4707     // makes no sense.  Worth issuing a warning at some point.
4708     return true;
4709   }
4710 
4711   // Consume the argument.
4712   unsigned argIndex = FS.getArgIndex();
4713   if (argIndex < NumDataArgs) {
4714     // The check to see if the argIndex is valid will come later.
4715     // We set the bit here because we may exit early from this
4716     // function if we encounter some other error.
4717     CoveredArgs.set(argIndex);
4718   }
4719 
4720   // FreeBSD kernel extensions.
4721   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
4722       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
4723     // We need at least two arguments.
4724     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
4725       return false;
4726 
4727     // Claim the second argument.
4728     CoveredArgs.set(argIndex + 1);
4729 
4730     // Type check the first argument (int for %b, pointer for %D)
4731     const Expr *Ex = getDataArg(argIndex);
4732     const analyze_printf::ArgType &AT =
4733       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
4734         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
4735     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
4736       EmitFormatDiagnostic(
4737         S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4738         << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
4739         << false << Ex->getSourceRange(),
4740         Ex->getLocStart(), /*IsStringLocation*/false,
4741         getSpecifierRange(startSpecifier, specifierLen));
4742 
4743     // Type check the second argument (char * for both %b and %D)
4744     Ex = getDataArg(argIndex + 1);
4745     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
4746     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
4747       EmitFormatDiagnostic(
4748         S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4749         << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
4750         << false << Ex->getSourceRange(),
4751         Ex->getLocStart(), /*IsStringLocation*/false,
4752         getSpecifierRange(startSpecifier, specifierLen));
4753 
4754      return true;
4755   }
4756 
4757   // Check for using an Objective-C specific conversion specifier
4758   // in a non-ObjC literal.
4759   if (!ObjCContext && CS.isObjCArg()) {
4760     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
4761                                                   specifierLen);
4762   }
4763 
4764   // Check for invalid use of field width
4765   if (!FS.hasValidFieldWidth()) {
4766     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
4767         startSpecifier, specifierLen);
4768   }
4769 
4770   // Check for invalid use of precision
4771   if (!FS.hasValidPrecision()) {
4772     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
4773         startSpecifier, specifierLen);
4774   }
4775 
4776   // Check each flag does not conflict with any other component.
4777   if (!FS.hasValidThousandsGroupingPrefix())
4778     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
4779   if (!FS.hasValidLeadingZeros())
4780     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
4781   if (!FS.hasValidPlusPrefix())
4782     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
4783   if (!FS.hasValidSpacePrefix())
4784     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
4785   if (!FS.hasValidAlternativeForm())
4786     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
4787   if (!FS.hasValidLeftJustified())
4788     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
4789 
4790   // Check that flags are not ignored by another flag
4791   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
4792     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
4793         startSpecifier, specifierLen);
4794   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
4795     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
4796             startSpecifier, specifierLen);
4797 
4798   // Check the length modifier is valid with the given conversion specifier.
4799   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
4800     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4801                                 diag::warn_format_nonsensical_length);
4802   else if (!FS.hasStandardLengthModifier())
4803     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
4804   else if (!FS.hasStandardLengthConversionCombination())
4805     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4806                                 diag::warn_format_non_standard_conversion_spec);
4807 
4808   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
4809     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
4810 
4811   // The remaining checks depend on the data arguments.
4812   if (HasVAListArg)
4813     return true;
4814 
4815   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
4816     return false;
4817 
4818   const Expr *Arg = getDataArg(argIndex);
4819   if (!Arg)
4820     return true;
4821 
4822   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
4823 }
4824 
4825 static bool requiresParensToAddCast(const Expr *E) {
4826   // FIXME: We should have a general way to reason about operator
4827   // precedence and whether parens are actually needed here.
4828   // Take care of a few common cases where they aren't.
4829   const Expr *Inside = E->IgnoreImpCasts();
4830   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
4831     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
4832 
4833   switch (Inside->getStmtClass()) {
4834   case Stmt::ArraySubscriptExprClass:
4835   case Stmt::CallExprClass:
4836   case Stmt::CharacterLiteralClass:
4837   case Stmt::CXXBoolLiteralExprClass:
4838   case Stmt::DeclRefExprClass:
4839   case Stmt::FloatingLiteralClass:
4840   case Stmt::IntegerLiteralClass:
4841   case Stmt::MemberExprClass:
4842   case Stmt::ObjCArrayLiteralClass:
4843   case Stmt::ObjCBoolLiteralExprClass:
4844   case Stmt::ObjCBoxedExprClass:
4845   case Stmt::ObjCDictionaryLiteralClass:
4846   case Stmt::ObjCEncodeExprClass:
4847   case Stmt::ObjCIvarRefExprClass:
4848   case Stmt::ObjCMessageExprClass:
4849   case Stmt::ObjCPropertyRefExprClass:
4850   case Stmt::ObjCStringLiteralClass:
4851   case Stmt::ObjCSubscriptRefExprClass:
4852   case Stmt::ParenExprClass:
4853   case Stmt::StringLiteralClass:
4854   case Stmt::UnaryOperatorClass:
4855     return false;
4856   default:
4857     return true;
4858   }
4859 }
4860 
4861 static std::pair<QualType, StringRef>
4862 shouldNotPrintDirectly(const ASTContext &Context,
4863                        QualType IntendedTy,
4864                        const Expr *E) {
4865   // Use a 'while' to peel off layers of typedefs.
4866   QualType TyTy = IntendedTy;
4867   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
4868     StringRef Name = UserTy->getDecl()->getName();
4869     QualType CastTy = llvm::StringSwitch<QualType>(Name)
4870       .Case("NSInteger", Context.LongTy)
4871       .Case("NSUInteger", Context.UnsignedLongTy)
4872       .Case("SInt32", Context.IntTy)
4873       .Case("UInt32", Context.UnsignedIntTy)
4874       .Default(QualType());
4875 
4876     if (!CastTy.isNull())
4877       return std::make_pair(CastTy, Name);
4878 
4879     TyTy = UserTy->desugar();
4880   }
4881 
4882   // Strip parens if necessary.
4883   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
4884     return shouldNotPrintDirectly(Context,
4885                                   PE->getSubExpr()->getType(),
4886                                   PE->getSubExpr());
4887 
4888   // If this is a conditional expression, then its result type is constructed
4889   // via usual arithmetic conversions and thus there might be no necessary
4890   // typedef sugar there.  Recurse to operands to check for NSInteger &
4891   // Co. usage condition.
4892   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
4893     QualType TrueTy, FalseTy;
4894     StringRef TrueName, FalseName;
4895 
4896     std::tie(TrueTy, TrueName) =
4897       shouldNotPrintDirectly(Context,
4898                              CO->getTrueExpr()->getType(),
4899                              CO->getTrueExpr());
4900     std::tie(FalseTy, FalseName) =
4901       shouldNotPrintDirectly(Context,
4902                              CO->getFalseExpr()->getType(),
4903                              CO->getFalseExpr());
4904 
4905     if (TrueTy == FalseTy)
4906       return std::make_pair(TrueTy, TrueName);
4907     else if (TrueTy.isNull())
4908       return std::make_pair(FalseTy, FalseName);
4909     else if (FalseTy.isNull())
4910       return std::make_pair(TrueTy, TrueName);
4911   }
4912 
4913   return std::make_pair(QualType(), StringRef());
4914 }
4915 
4916 bool
4917 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
4918                                     const char *StartSpecifier,
4919                                     unsigned SpecifierLen,
4920                                     const Expr *E) {
4921   using namespace analyze_format_string;
4922   using namespace analyze_printf;
4923   // Now type check the data expression that matches the
4924   // format specifier.
4925   const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
4926                                                     ObjCContext);
4927   if (!AT.isValid())
4928     return true;
4929 
4930   QualType ExprTy = E->getType();
4931   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
4932     ExprTy = TET->getUnderlyingExpr()->getType();
4933   }
4934 
4935   analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
4936 
4937   if (match == analyze_printf::ArgType::Match) {
4938     return true;
4939   }
4940 
4941   // Look through argument promotions for our error message's reported type.
4942   // This includes the integral and floating promotions, but excludes array
4943   // and function pointer decay; seeing that an argument intended to be a
4944   // string has type 'char [6]' is probably more confusing than 'char *'.
4945   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
4946     if (ICE->getCastKind() == CK_IntegralCast ||
4947         ICE->getCastKind() == CK_FloatingCast) {
4948       E = ICE->getSubExpr();
4949       ExprTy = E->getType();
4950 
4951       // Check if we didn't match because of an implicit cast from a 'char'
4952       // or 'short' to an 'int'.  This is done because printf is a varargs
4953       // function.
4954       if (ICE->getType() == S.Context.IntTy ||
4955           ICE->getType() == S.Context.UnsignedIntTy) {
4956         // All further checking is done on the subexpression.
4957         if (AT.matchesType(S.Context, ExprTy))
4958           return true;
4959       }
4960     }
4961   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
4962     // Special case for 'a', which has type 'int' in C.
4963     // Note, however, that we do /not/ want to treat multibyte constants like
4964     // 'MooV' as characters! This form is deprecated but still exists.
4965     if (ExprTy == S.Context.IntTy)
4966       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
4967         ExprTy = S.Context.CharTy;
4968   }
4969 
4970   // Look through enums to their underlying type.
4971   bool IsEnum = false;
4972   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
4973     ExprTy = EnumTy->getDecl()->getIntegerType();
4974     IsEnum = true;
4975   }
4976 
4977   // %C in an Objective-C context prints a unichar, not a wchar_t.
4978   // If the argument is an integer of some kind, believe the %C and suggest
4979   // a cast instead of changing the conversion specifier.
4980   QualType IntendedTy = ExprTy;
4981   if (ObjCContext &&
4982       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
4983     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
4984         !ExprTy->isCharType()) {
4985       // 'unichar' is defined as a typedef of unsigned short, but we should
4986       // prefer using the typedef if it is visible.
4987       IntendedTy = S.Context.UnsignedShortTy;
4988 
4989       // While we are here, check if the value is an IntegerLiteral that happens
4990       // to be within the valid range.
4991       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
4992         const llvm::APInt &V = IL->getValue();
4993         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
4994           return true;
4995       }
4996 
4997       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
4998                           Sema::LookupOrdinaryName);
4999       if (S.LookupName(Result, S.getCurScope())) {
5000         NamedDecl *ND = Result.getFoundDecl();
5001         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
5002           if (TD->getUnderlyingType() == IntendedTy)
5003             IntendedTy = S.Context.getTypedefType(TD);
5004       }
5005     }
5006   }
5007 
5008   // Special-case some of Darwin's platform-independence types by suggesting
5009   // casts to primitive types that are known to be large enough.
5010   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
5011   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
5012     QualType CastTy;
5013     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
5014     if (!CastTy.isNull()) {
5015       IntendedTy = CastTy;
5016       ShouldNotPrintDirectly = true;
5017     }
5018   }
5019 
5020   // We may be able to offer a FixItHint if it is a supported type.
5021   PrintfSpecifier fixedFS = FS;
5022   bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
5023                                  S.Context, ObjCContext);
5024 
5025   if (success) {
5026     // Get the fix string from the fixed format specifier
5027     SmallString<16> buf;
5028     llvm::raw_svector_ostream os(buf);
5029     fixedFS.toString(os);
5030 
5031     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
5032 
5033     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
5034       unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
5035       if (match == analyze_format_string::ArgType::NoMatchPedantic) {
5036         diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
5037       }
5038       // In this case, the specifier is wrong and should be changed to match
5039       // the argument.
5040       EmitFormatDiagnostic(S.PDiag(diag)
5041                                << AT.getRepresentativeTypeName(S.Context)
5042                                << IntendedTy << IsEnum << E->getSourceRange(),
5043                            E->getLocStart(),
5044                            /*IsStringLocation*/ false, SpecRange,
5045                            FixItHint::CreateReplacement(SpecRange, os.str()));
5046     } else {
5047       // The canonical type for formatting this value is different from the
5048       // actual type of the expression. (This occurs, for example, with Darwin's
5049       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
5050       // should be printed as 'long' for 64-bit compatibility.)
5051       // Rather than emitting a normal format/argument mismatch, we want to
5052       // add a cast to the recommended type (and correct the format string
5053       // if necessary).
5054       SmallString<16> CastBuf;
5055       llvm::raw_svector_ostream CastFix(CastBuf);
5056       CastFix << "(";
5057       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
5058       CastFix << ")";
5059 
5060       SmallVector<FixItHint,4> Hints;
5061       if (!AT.matchesType(S.Context, IntendedTy))
5062         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
5063 
5064       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
5065         // If there's already a cast present, just replace it.
5066         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
5067         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
5068 
5069       } else if (!requiresParensToAddCast(E)) {
5070         // If the expression has high enough precedence,
5071         // just write the C-style cast.
5072         Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
5073                                                    CastFix.str()));
5074       } else {
5075         // Otherwise, add parens around the expression as well as the cast.
5076         CastFix << "(";
5077         Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
5078                                                    CastFix.str()));
5079 
5080         SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
5081         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
5082       }
5083 
5084       if (ShouldNotPrintDirectly) {
5085         // The expression has a type that should not be printed directly.
5086         // We extract the name from the typedef because we don't want to show
5087         // the underlying type in the diagnostic.
5088         StringRef Name;
5089         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
5090           Name = TypedefTy->getDecl()->getName();
5091         else
5092           Name = CastTyName;
5093         EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
5094                                << Name << IntendedTy << IsEnum
5095                                << E->getSourceRange(),
5096                              E->getLocStart(), /*IsStringLocation=*/false,
5097                              SpecRange, Hints);
5098       } else {
5099         // In this case, the expression could be printed using a different
5100         // specifier, but we've decided that the specifier is probably correct
5101         // and we should cast instead. Just use the normal warning message.
5102         EmitFormatDiagnostic(
5103           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5104             << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
5105             << E->getSourceRange(),
5106           E->getLocStart(), /*IsStringLocation*/false,
5107           SpecRange, Hints);
5108       }
5109     }
5110   } else {
5111     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
5112                                                    SpecifierLen);
5113     // Since the warning for passing non-POD types to variadic functions
5114     // was deferred until now, we emit a warning for non-POD
5115     // arguments here.
5116     switch (S.isValidVarArgType(ExprTy)) {
5117     case Sema::VAK_Valid:
5118     case Sema::VAK_ValidInCXX11: {
5119       unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
5120       if (match == analyze_printf::ArgType::NoMatchPedantic) {
5121         diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
5122       }
5123 
5124       EmitFormatDiagnostic(
5125           S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
5126                         << IsEnum << CSR << E->getSourceRange(),
5127           E->getLocStart(), /*IsStringLocation*/ false, CSR);
5128       break;
5129     }
5130     case Sema::VAK_Undefined:
5131     case Sema::VAK_MSVCUndefined:
5132       EmitFormatDiagnostic(
5133         S.PDiag(diag::warn_non_pod_vararg_with_format_string)
5134           << S.getLangOpts().CPlusPlus11
5135           << ExprTy
5136           << CallType
5137           << AT.getRepresentativeTypeName(S.Context)
5138           << CSR
5139           << E->getSourceRange(),
5140         E->getLocStart(), /*IsStringLocation*/false, CSR);
5141       checkForCStrMembers(AT, E);
5142       break;
5143 
5144     case Sema::VAK_Invalid:
5145       if (ExprTy->isObjCObjectType())
5146         EmitFormatDiagnostic(
5147           S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
5148             << S.getLangOpts().CPlusPlus11
5149             << ExprTy
5150             << CallType
5151             << AT.getRepresentativeTypeName(S.Context)
5152             << CSR
5153             << E->getSourceRange(),
5154           E->getLocStart(), /*IsStringLocation*/false, CSR);
5155       else
5156         // FIXME: If this is an initializer list, suggest removing the braces
5157         // or inserting a cast to the target type.
5158         S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
5159           << isa<InitListExpr>(E) << ExprTy << CallType
5160           << AT.getRepresentativeTypeName(S.Context)
5161           << E->getSourceRange();
5162       break;
5163     }
5164 
5165     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
5166            "format string specifier index out of range");
5167     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
5168   }
5169 
5170   return true;
5171 }
5172 
5173 //===--- CHECK: Scanf format string checking ------------------------------===//
5174 
5175 namespace {
5176 class CheckScanfHandler : public CheckFormatHandler {
5177 public:
5178   CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
5179                     const Expr *origFormatExpr, unsigned firstDataArg,
5180                     unsigned numDataArgs, const char *beg, bool hasVAListArg,
5181                     ArrayRef<const Expr *> Args,
5182                     unsigned formatIdx, bool inFunctionCall,
5183                     Sema::VariadicCallType CallType,
5184                     llvm::SmallBitVector &CheckedVarArgs,
5185                     UncoveredArgHandler &UncoveredArg)
5186     : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
5187                          numDataArgs, beg, hasVAListArg,
5188                          Args, formatIdx, inFunctionCall, CallType,
5189                          CheckedVarArgs, UncoveredArg)
5190   {}
5191 
5192   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
5193                             const char *startSpecifier,
5194                             unsigned specifierLen) override;
5195 
5196   bool HandleInvalidScanfConversionSpecifier(
5197           const analyze_scanf::ScanfSpecifier &FS,
5198           const char *startSpecifier,
5199           unsigned specifierLen) override;
5200 
5201   void HandleIncompleteScanList(const char *start, const char *end) override;
5202 };
5203 } // end anonymous namespace
5204 
5205 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
5206                                                  const char *end) {
5207   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
5208                        getLocationOfByte(end), /*IsStringLocation*/true,
5209                        getSpecifierRange(start, end - start));
5210 }
5211 
5212 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
5213                                         const analyze_scanf::ScanfSpecifier &FS,
5214                                         const char *startSpecifier,
5215                                         unsigned specifierLen) {
5216 
5217   const analyze_scanf::ScanfConversionSpecifier &CS =
5218     FS.getConversionSpecifier();
5219 
5220   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
5221                                           getLocationOfByte(CS.getStart()),
5222                                           startSpecifier, specifierLen,
5223                                           CS.getStart(), CS.getLength());
5224 }
5225 
5226 bool CheckScanfHandler::HandleScanfSpecifier(
5227                                        const analyze_scanf::ScanfSpecifier &FS,
5228                                        const char *startSpecifier,
5229                                        unsigned specifierLen) {
5230   using namespace analyze_scanf;
5231   using namespace analyze_format_string;
5232 
5233   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
5234 
5235   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
5236   // be used to decide if we are using positional arguments consistently.
5237   if (FS.consumesDataArgument()) {
5238     if (atFirstArg) {
5239       atFirstArg = false;
5240       usesPositionalArgs = FS.usesPositionalArg();
5241     }
5242     else if (usesPositionalArgs != FS.usesPositionalArg()) {
5243       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
5244                                         startSpecifier, specifierLen);
5245       return false;
5246     }
5247   }
5248 
5249   // Check if the field with is non-zero.
5250   const OptionalAmount &Amt = FS.getFieldWidth();
5251   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
5252     if (Amt.getConstantAmount() == 0) {
5253       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
5254                                                    Amt.getConstantLength());
5255       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
5256                            getLocationOfByte(Amt.getStart()),
5257                            /*IsStringLocation*/true, R,
5258                            FixItHint::CreateRemoval(R));
5259     }
5260   }
5261 
5262   if (!FS.consumesDataArgument()) {
5263     // FIXME: Technically specifying a precision or field width here
5264     // makes no sense.  Worth issuing a warning at some point.
5265     return true;
5266   }
5267 
5268   // Consume the argument.
5269   unsigned argIndex = FS.getArgIndex();
5270   if (argIndex < NumDataArgs) {
5271       // The check to see if the argIndex is valid will come later.
5272       // We set the bit here because we may exit early from this
5273       // function if we encounter some other error.
5274     CoveredArgs.set(argIndex);
5275   }
5276 
5277   // Check the length modifier is valid with the given conversion specifier.
5278   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
5279     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5280                                 diag::warn_format_nonsensical_length);
5281   else if (!FS.hasStandardLengthModifier())
5282     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
5283   else if (!FS.hasStandardLengthConversionCombination())
5284     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5285                                 diag::warn_format_non_standard_conversion_spec);
5286 
5287   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
5288     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
5289 
5290   // The remaining checks depend on the data arguments.
5291   if (HasVAListArg)
5292     return true;
5293 
5294   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
5295     return false;
5296 
5297   // Check that the argument type matches the format specifier.
5298   const Expr *Ex = getDataArg(argIndex);
5299   if (!Ex)
5300     return true;
5301 
5302   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
5303 
5304   if (!AT.isValid()) {
5305     return true;
5306   }
5307 
5308   analyze_format_string::ArgType::MatchKind match =
5309       AT.matchesType(S.Context, Ex->getType());
5310   if (match == analyze_format_string::ArgType::Match) {
5311     return true;
5312   }
5313 
5314   ScanfSpecifier fixedFS = FS;
5315   bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
5316                                  S.getLangOpts(), S.Context);
5317 
5318   unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
5319   if (match == analyze_format_string::ArgType::NoMatchPedantic) {
5320     diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
5321   }
5322 
5323   if (success) {
5324     // Get the fix string from the fixed format specifier.
5325     SmallString<128> buf;
5326     llvm::raw_svector_ostream os(buf);
5327     fixedFS.toString(os);
5328 
5329     EmitFormatDiagnostic(
5330         S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
5331                       << Ex->getType() << false << Ex->getSourceRange(),
5332         Ex->getLocStart(),
5333         /*IsStringLocation*/ false,
5334         getSpecifierRange(startSpecifier, specifierLen),
5335         FixItHint::CreateReplacement(
5336             getSpecifierRange(startSpecifier, specifierLen), os.str()));
5337   } else {
5338     EmitFormatDiagnostic(S.PDiag(diag)
5339                              << AT.getRepresentativeTypeName(S.Context)
5340                              << Ex->getType() << false << Ex->getSourceRange(),
5341                          Ex->getLocStart(),
5342                          /*IsStringLocation*/ false,
5343                          getSpecifierRange(startSpecifier, specifierLen));
5344   }
5345 
5346   return true;
5347 }
5348 
5349 static void CheckFormatString(Sema &S, const StringLiteral *FExpr,
5350                               const Expr *OrigFormatExpr,
5351                               ArrayRef<const Expr *> Args,
5352                               bool HasVAListArg, unsigned format_idx,
5353                               unsigned firstDataArg,
5354                               Sema::FormatStringType Type,
5355                               bool inFunctionCall,
5356                               Sema::VariadicCallType CallType,
5357                               llvm::SmallBitVector &CheckedVarArgs,
5358                               UncoveredArgHandler &UncoveredArg) {
5359   // CHECK: is the format string a wide literal?
5360   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
5361     CheckFormatHandler::EmitFormatDiagnostic(
5362       S, inFunctionCall, Args[format_idx],
5363       S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
5364       /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
5365     return;
5366   }
5367 
5368   // Str - The format string.  NOTE: this is NOT null-terminated!
5369   StringRef StrRef = FExpr->getString();
5370   const char *Str = StrRef.data();
5371   // Account for cases where the string literal is truncated in a declaration.
5372   const ConstantArrayType *T =
5373     S.Context.getAsConstantArrayType(FExpr->getType());
5374   assert(T && "String literal not of constant array type!");
5375   size_t TypeSize = T->getSize().getZExtValue();
5376   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
5377   const unsigned numDataArgs = Args.size() - firstDataArg;
5378 
5379   // Emit a warning if the string literal is truncated and does not contain an
5380   // embedded null character.
5381   if (TypeSize <= StrRef.size() &&
5382       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
5383     CheckFormatHandler::EmitFormatDiagnostic(
5384         S, inFunctionCall, Args[format_idx],
5385         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
5386         FExpr->getLocStart(),
5387         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
5388     return;
5389   }
5390 
5391   // CHECK: empty format string?
5392   if (StrLen == 0 && numDataArgs > 0) {
5393     CheckFormatHandler::EmitFormatDiagnostic(
5394       S, inFunctionCall, Args[format_idx],
5395       S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
5396       /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
5397     return;
5398   }
5399 
5400   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
5401       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSTrace) {
5402     CheckPrintfHandler H(S, FExpr, OrigFormatExpr, firstDataArg,
5403                          numDataArgs, (Type == Sema::FST_NSString ||
5404                                        Type == Sema::FST_OSTrace),
5405                          Str, HasVAListArg, Args, format_idx,
5406                          inFunctionCall, CallType, CheckedVarArgs,
5407                          UncoveredArg);
5408 
5409     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
5410                                                   S.getLangOpts(),
5411                                                   S.Context.getTargetInfo(),
5412                                             Type == Sema::FST_FreeBSDKPrintf))
5413       H.DoneProcessing();
5414   } else if (Type == Sema::FST_Scanf) {
5415     CheckScanfHandler H(S, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
5416                         Str, HasVAListArg, Args, format_idx,
5417                         inFunctionCall, CallType, CheckedVarArgs,
5418                         UncoveredArg);
5419 
5420     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
5421                                                  S.getLangOpts(),
5422                                                  S.Context.getTargetInfo()))
5423       H.DoneProcessing();
5424   } // TODO: handle other formats
5425 }
5426 
5427 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
5428   // Str - The format string.  NOTE: this is NOT null-terminated!
5429   StringRef StrRef = FExpr->getString();
5430   const char *Str = StrRef.data();
5431   // Account for cases where the string literal is truncated in a declaration.
5432   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
5433   assert(T && "String literal not of constant array type!");
5434   size_t TypeSize = T->getSize().getZExtValue();
5435   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
5436   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
5437                                                          getLangOpts(),
5438                                                          Context.getTargetInfo());
5439 }
5440 
5441 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
5442 
5443 // Returns the related absolute value function that is larger, of 0 if one
5444 // does not exist.
5445 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
5446   switch (AbsFunction) {
5447   default:
5448     return 0;
5449 
5450   case Builtin::BI__builtin_abs:
5451     return Builtin::BI__builtin_labs;
5452   case Builtin::BI__builtin_labs:
5453     return Builtin::BI__builtin_llabs;
5454   case Builtin::BI__builtin_llabs:
5455     return 0;
5456 
5457   case Builtin::BI__builtin_fabsf:
5458     return Builtin::BI__builtin_fabs;
5459   case Builtin::BI__builtin_fabs:
5460     return Builtin::BI__builtin_fabsl;
5461   case Builtin::BI__builtin_fabsl:
5462     return 0;
5463 
5464   case Builtin::BI__builtin_cabsf:
5465     return Builtin::BI__builtin_cabs;
5466   case Builtin::BI__builtin_cabs:
5467     return Builtin::BI__builtin_cabsl;
5468   case Builtin::BI__builtin_cabsl:
5469     return 0;
5470 
5471   case Builtin::BIabs:
5472     return Builtin::BIlabs;
5473   case Builtin::BIlabs:
5474     return Builtin::BIllabs;
5475   case Builtin::BIllabs:
5476     return 0;
5477 
5478   case Builtin::BIfabsf:
5479     return Builtin::BIfabs;
5480   case Builtin::BIfabs:
5481     return Builtin::BIfabsl;
5482   case Builtin::BIfabsl:
5483     return 0;
5484 
5485   case Builtin::BIcabsf:
5486    return Builtin::BIcabs;
5487   case Builtin::BIcabs:
5488     return Builtin::BIcabsl;
5489   case Builtin::BIcabsl:
5490     return 0;
5491   }
5492 }
5493 
5494 // Returns the argument type of the absolute value function.
5495 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
5496                                              unsigned AbsType) {
5497   if (AbsType == 0)
5498     return QualType();
5499 
5500   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
5501   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
5502   if (Error != ASTContext::GE_None)
5503     return QualType();
5504 
5505   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
5506   if (!FT)
5507     return QualType();
5508 
5509   if (FT->getNumParams() != 1)
5510     return QualType();
5511 
5512   return FT->getParamType(0);
5513 }
5514 
5515 // Returns the best absolute value function, or zero, based on type and
5516 // current absolute value function.
5517 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
5518                                    unsigned AbsFunctionKind) {
5519   unsigned BestKind = 0;
5520   uint64_t ArgSize = Context.getTypeSize(ArgType);
5521   for (unsigned Kind = AbsFunctionKind; Kind != 0;
5522        Kind = getLargerAbsoluteValueFunction(Kind)) {
5523     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
5524     if (Context.getTypeSize(ParamType) >= ArgSize) {
5525       if (BestKind == 0)
5526         BestKind = Kind;
5527       else if (Context.hasSameType(ParamType, ArgType)) {
5528         BestKind = Kind;
5529         break;
5530       }
5531     }
5532   }
5533   return BestKind;
5534 }
5535 
5536 enum AbsoluteValueKind {
5537   AVK_Integer,
5538   AVK_Floating,
5539   AVK_Complex
5540 };
5541 
5542 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
5543   if (T->isIntegralOrEnumerationType())
5544     return AVK_Integer;
5545   if (T->isRealFloatingType())
5546     return AVK_Floating;
5547   if (T->isAnyComplexType())
5548     return AVK_Complex;
5549 
5550   llvm_unreachable("Type not integer, floating, or complex");
5551 }
5552 
5553 // Changes the absolute value function to a different type.  Preserves whether
5554 // the function is a builtin.
5555 static unsigned changeAbsFunction(unsigned AbsKind,
5556                                   AbsoluteValueKind ValueKind) {
5557   switch (ValueKind) {
5558   case AVK_Integer:
5559     switch (AbsKind) {
5560     default:
5561       return 0;
5562     case Builtin::BI__builtin_fabsf:
5563     case Builtin::BI__builtin_fabs:
5564     case Builtin::BI__builtin_fabsl:
5565     case Builtin::BI__builtin_cabsf:
5566     case Builtin::BI__builtin_cabs:
5567     case Builtin::BI__builtin_cabsl:
5568       return Builtin::BI__builtin_abs;
5569     case Builtin::BIfabsf:
5570     case Builtin::BIfabs:
5571     case Builtin::BIfabsl:
5572     case Builtin::BIcabsf:
5573     case Builtin::BIcabs:
5574     case Builtin::BIcabsl:
5575       return Builtin::BIabs;
5576     }
5577   case AVK_Floating:
5578     switch (AbsKind) {
5579     default:
5580       return 0;
5581     case Builtin::BI__builtin_abs:
5582     case Builtin::BI__builtin_labs:
5583     case Builtin::BI__builtin_llabs:
5584     case Builtin::BI__builtin_cabsf:
5585     case Builtin::BI__builtin_cabs:
5586     case Builtin::BI__builtin_cabsl:
5587       return Builtin::BI__builtin_fabsf;
5588     case Builtin::BIabs:
5589     case Builtin::BIlabs:
5590     case Builtin::BIllabs:
5591     case Builtin::BIcabsf:
5592     case Builtin::BIcabs:
5593     case Builtin::BIcabsl:
5594       return Builtin::BIfabsf;
5595     }
5596   case AVK_Complex:
5597     switch (AbsKind) {
5598     default:
5599       return 0;
5600     case Builtin::BI__builtin_abs:
5601     case Builtin::BI__builtin_labs:
5602     case Builtin::BI__builtin_llabs:
5603     case Builtin::BI__builtin_fabsf:
5604     case Builtin::BI__builtin_fabs:
5605     case Builtin::BI__builtin_fabsl:
5606       return Builtin::BI__builtin_cabsf;
5607     case Builtin::BIabs:
5608     case Builtin::BIlabs:
5609     case Builtin::BIllabs:
5610     case Builtin::BIfabsf:
5611     case Builtin::BIfabs:
5612     case Builtin::BIfabsl:
5613       return Builtin::BIcabsf;
5614     }
5615   }
5616   llvm_unreachable("Unable to convert function");
5617 }
5618 
5619 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
5620   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
5621   if (!FnInfo)
5622     return 0;
5623 
5624   switch (FDecl->getBuiltinID()) {
5625   default:
5626     return 0;
5627   case Builtin::BI__builtin_abs:
5628   case Builtin::BI__builtin_fabs:
5629   case Builtin::BI__builtin_fabsf:
5630   case Builtin::BI__builtin_fabsl:
5631   case Builtin::BI__builtin_labs:
5632   case Builtin::BI__builtin_llabs:
5633   case Builtin::BI__builtin_cabs:
5634   case Builtin::BI__builtin_cabsf:
5635   case Builtin::BI__builtin_cabsl:
5636   case Builtin::BIabs:
5637   case Builtin::BIlabs:
5638   case Builtin::BIllabs:
5639   case Builtin::BIfabs:
5640   case Builtin::BIfabsf:
5641   case Builtin::BIfabsl:
5642   case Builtin::BIcabs:
5643   case Builtin::BIcabsf:
5644   case Builtin::BIcabsl:
5645     return FDecl->getBuiltinID();
5646   }
5647   llvm_unreachable("Unknown Builtin type");
5648 }
5649 
5650 // If the replacement is valid, emit a note with replacement function.
5651 // Additionally, suggest including the proper header if not already included.
5652 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
5653                             unsigned AbsKind, QualType ArgType) {
5654   bool EmitHeaderHint = true;
5655   const char *HeaderName = nullptr;
5656   const char *FunctionName = nullptr;
5657   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
5658     FunctionName = "std::abs";
5659     if (ArgType->isIntegralOrEnumerationType()) {
5660       HeaderName = "cstdlib";
5661     } else if (ArgType->isRealFloatingType()) {
5662       HeaderName = "cmath";
5663     } else {
5664       llvm_unreachable("Invalid Type");
5665     }
5666 
5667     // Lookup all std::abs
5668     if (NamespaceDecl *Std = S.getStdNamespace()) {
5669       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
5670       R.suppressDiagnostics();
5671       S.LookupQualifiedName(R, Std);
5672 
5673       for (const auto *I : R) {
5674         const FunctionDecl *FDecl = nullptr;
5675         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
5676           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
5677         } else {
5678           FDecl = dyn_cast<FunctionDecl>(I);
5679         }
5680         if (!FDecl)
5681           continue;
5682 
5683         // Found std::abs(), check that they are the right ones.
5684         if (FDecl->getNumParams() != 1)
5685           continue;
5686 
5687         // Check that the parameter type can handle the argument.
5688         QualType ParamType = FDecl->getParamDecl(0)->getType();
5689         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
5690             S.Context.getTypeSize(ArgType) <=
5691                 S.Context.getTypeSize(ParamType)) {
5692           // Found a function, don't need the header hint.
5693           EmitHeaderHint = false;
5694           break;
5695         }
5696       }
5697     }
5698   } else {
5699     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
5700     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
5701 
5702     if (HeaderName) {
5703       DeclarationName DN(&S.Context.Idents.get(FunctionName));
5704       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
5705       R.suppressDiagnostics();
5706       S.LookupName(R, S.getCurScope());
5707 
5708       if (R.isSingleResult()) {
5709         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
5710         if (FD && FD->getBuiltinID() == AbsKind) {
5711           EmitHeaderHint = false;
5712         } else {
5713           return;
5714         }
5715       } else if (!R.empty()) {
5716         return;
5717       }
5718     }
5719   }
5720 
5721   S.Diag(Loc, diag::note_replace_abs_function)
5722       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
5723 
5724   if (!HeaderName)
5725     return;
5726 
5727   if (!EmitHeaderHint)
5728     return;
5729 
5730   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
5731                                                     << FunctionName;
5732 }
5733 
5734 static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
5735   if (!FDecl)
5736     return false;
5737 
5738   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
5739     return false;
5740 
5741   const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
5742 
5743   while (ND && ND->isInlineNamespace()) {
5744     ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
5745   }
5746 
5747   if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
5748     return false;
5749 
5750   if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
5751     return false;
5752 
5753   return true;
5754 }
5755 
5756 // Warn when using the wrong abs() function.
5757 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
5758                                       const FunctionDecl *FDecl,
5759                                       IdentifierInfo *FnInfo) {
5760   if (Call->getNumArgs() != 1)
5761     return;
5762 
5763   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
5764   bool IsStdAbs = IsFunctionStdAbs(FDecl);
5765   if (AbsKind == 0 && !IsStdAbs)
5766     return;
5767 
5768   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
5769   QualType ParamType = Call->getArg(0)->getType();
5770 
5771   // Unsigned types cannot be negative.  Suggest removing the absolute value
5772   // function call.
5773   if (ArgType->isUnsignedIntegerType()) {
5774     const char *FunctionName =
5775         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
5776     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
5777     Diag(Call->getExprLoc(), diag::note_remove_abs)
5778         << FunctionName
5779         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
5780     return;
5781   }
5782 
5783   // Taking the absolute value of a pointer is very suspicious, they probably
5784   // wanted to index into an array, dereference a pointer, call a function, etc.
5785   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
5786     unsigned DiagType = 0;
5787     if (ArgType->isFunctionType())
5788       DiagType = 1;
5789     else if (ArgType->isArrayType())
5790       DiagType = 2;
5791 
5792     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
5793     return;
5794   }
5795 
5796   // std::abs has overloads which prevent most of the absolute value problems
5797   // from occurring.
5798   if (IsStdAbs)
5799     return;
5800 
5801   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
5802   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
5803 
5804   // The argument and parameter are the same kind.  Check if they are the right
5805   // size.
5806   if (ArgValueKind == ParamValueKind) {
5807     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
5808       return;
5809 
5810     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
5811     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
5812         << FDecl << ArgType << ParamType;
5813 
5814     if (NewAbsKind == 0)
5815       return;
5816 
5817     emitReplacement(*this, Call->getExprLoc(),
5818                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
5819     return;
5820   }
5821 
5822   // ArgValueKind != ParamValueKind
5823   // The wrong type of absolute value function was used.  Attempt to find the
5824   // proper one.
5825   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
5826   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
5827   if (NewAbsKind == 0)
5828     return;
5829 
5830   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
5831       << FDecl << ParamValueKind << ArgValueKind;
5832 
5833   emitReplacement(*this, Call->getExprLoc(),
5834                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
5835 }
5836 
5837 //===--- CHECK: Standard memory functions ---------------------------------===//
5838 
5839 /// \brief Takes the expression passed to the size_t parameter of functions
5840 /// such as memcmp, strncat, etc and warns if it's a comparison.
5841 ///
5842 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
5843 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
5844                                            IdentifierInfo *FnName,
5845                                            SourceLocation FnLoc,
5846                                            SourceLocation RParenLoc) {
5847   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
5848   if (!Size)
5849     return false;
5850 
5851   // if E is binop and op is >, <, >=, <=, ==, &&, ||:
5852   if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
5853     return false;
5854 
5855   SourceRange SizeRange = Size->getSourceRange();
5856   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
5857       << SizeRange << FnName;
5858   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
5859       << FnName << FixItHint::CreateInsertion(
5860                        S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
5861       << FixItHint::CreateRemoval(RParenLoc);
5862   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
5863       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
5864       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
5865                                     ")");
5866 
5867   return true;
5868 }
5869 
5870 /// \brief Determine whether the given type is or contains a dynamic class type
5871 /// (e.g., whether it has a vtable).
5872 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
5873                                                      bool &IsContained) {
5874   // Look through array types while ignoring qualifiers.
5875   const Type *Ty = T->getBaseElementTypeUnsafe();
5876   IsContained = false;
5877 
5878   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
5879   RD = RD ? RD->getDefinition() : nullptr;
5880   if (!RD || RD->isInvalidDecl())
5881     return nullptr;
5882 
5883   if (RD->isDynamicClass())
5884     return RD;
5885 
5886   // Check all the fields.  If any bases were dynamic, the class is dynamic.
5887   // It's impossible for a class to transitively contain itself by value, so
5888   // infinite recursion is impossible.
5889   for (auto *FD : RD->fields()) {
5890     bool SubContained;
5891     if (const CXXRecordDecl *ContainedRD =
5892             getContainedDynamicClass(FD->getType(), SubContained)) {
5893       IsContained = true;
5894       return ContainedRD;
5895     }
5896   }
5897 
5898   return nullptr;
5899 }
5900 
5901 /// \brief If E is a sizeof expression, returns its argument expression,
5902 /// otherwise returns NULL.
5903 static const Expr *getSizeOfExprArg(const Expr *E) {
5904   if (const UnaryExprOrTypeTraitExpr *SizeOf =
5905       dyn_cast<UnaryExprOrTypeTraitExpr>(E))
5906     if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
5907       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
5908 
5909   return nullptr;
5910 }
5911 
5912 /// \brief If E is a sizeof expression, returns its argument type.
5913 static QualType getSizeOfArgType(const Expr *E) {
5914   if (const UnaryExprOrTypeTraitExpr *SizeOf =
5915       dyn_cast<UnaryExprOrTypeTraitExpr>(E))
5916     if (SizeOf->getKind() == clang::UETT_SizeOf)
5917       return SizeOf->getTypeOfArgument();
5918 
5919   return QualType();
5920 }
5921 
5922 /// \brief Check for dangerous or invalid arguments to memset().
5923 ///
5924 /// This issues warnings on known problematic, dangerous or unspecified
5925 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
5926 /// function calls.
5927 ///
5928 /// \param Call The call expression to diagnose.
5929 void Sema::CheckMemaccessArguments(const CallExpr *Call,
5930                                    unsigned BId,
5931                                    IdentifierInfo *FnName) {
5932   assert(BId != 0);
5933 
5934   // It is possible to have a non-standard definition of memset.  Validate
5935   // we have enough arguments, and if not, abort further checking.
5936   unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
5937   if (Call->getNumArgs() < ExpectedNumArgs)
5938     return;
5939 
5940   unsigned LastArg = (BId == Builtin::BImemset ||
5941                       BId == Builtin::BIstrndup ? 1 : 2);
5942   unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
5943   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
5944 
5945   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
5946                                      Call->getLocStart(), Call->getRParenLoc()))
5947     return;
5948 
5949   // We have special checking when the length is a sizeof expression.
5950   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
5951   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
5952   llvm::FoldingSetNodeID SizeOfArgID;
5953 
5954   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
5955     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
5956     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
5957 
5958     QualType DestTy = Dest->getType();
5959     QualType PointeeTy;
5960     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
5961       PointeeTy = DestPtrTy->getPointeeType();
5962 
5963       // Never warn about void type pointers. This can be used to suppress
5964       // false positives.
5965       if (PointeeTy->isVoidType())
5966         continue;
5967 
5968       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
5969       // actually comparing the expressions for equality. Because computing the
5970       // expression IDs can be expensive, we only do this if the diagnostic is
5971       // enabled.
5972       if (SizeOfArg &&
5973           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
5974                            SizeOfArg->getExprLoc())) {
5975         // We only compute IDs for expressions if the warning is enabled, and
5976         // cache the sizeof arg's ID.
5977         if (SizeOfArgID == llvm::FoldingSetNodeID())
5978           SizeOfArg->Profile(SizeOfArgID, Context, true);
5979         llvm::FoldingSetNodeID DestID;
5980         Dest->Profile(DestID, Context, true);
5981         if (DestID == SizeOfArgID) {
5982           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
5983           //       over sizeof(src) as well.
5984           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
5985           StringRef ReadableName = FnName->getName();
5986 
5987           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
5988             if (UnaryOp->getOpcode() == UO_AddrOf)
5989               ActionIdx = 1; // If its an address-of operator, just remove it.
5990           if (!PointeeTy->isIncompleteType() &&
5991               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
5992             ActionIdx = 2; // If the pointee's size is sizeof(char),
5993                            // suggest an explicit length.
5994 
5995           // If the function is defined as a builtin macro, do not show macro
5996           // expansion.
5997           SourceLocation SL = SizeOfArg->getExprLoc();
5998           SourceRange DSR = Dest->getSourceRange();
5999           SourceRange SSR = SizeOfArg->getSourceRange();
6000           SourceManager &SM = getSourceManager();
6001 
6002           if (SM.isMacroArgExpansion(SL)) {
6003             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
6004             SL = SM.getSpellingLoc(SL);
6005             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
6006                              SM.getSpellingLoc(DSR.getEnd()));
6007             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
6008                              SM.getSpellingLoc(SSR.getEnd()));
6009           }
6010 
6011           DiagRuntimeBehavior(SL, SizeOfArg,
6012                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
6013                                 << ReadableName
6014                                 << PointeeTy
6015                                 << DestTy
6016                                 << DSR
6017                                 << SSR);
6018           DiagRuntimeBehavior(SL, SizeOfArg,
6019                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
6020                                 << ActionIdx
6021                                 << SSR);
6022 
6023           break;
6024         }
6025       }
6026 
6027       // Also check for cases where the sizeof argument is the exact same
6028       // type as the memory argument, and where it points to a user-defined
6029       // record type.
6030       if (SizeOfArgTy != QualType()) {
6031         if (PointeeTy->isRecordType() &&
6032             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
6033           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
6034                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
6035                                 << FnName << SizeOfArgTy << ArgIdx
6036                                 << PointeeTy << Dest->getSourceRange()
6037                                 << LenExpr->getSourceRange());
6038           break;
6039         }
6040       }
6041     } else if (DestTy->isArrayType()) {
6042       PointeeTy = DestTy;
6043     }
6044 
6045     if (PointeeTy == QualType())
6046       continue;
6047 
6048     // Always complain about dynamic classes.
6049     bool IsContained;
6050     if (const CXXRecordDecl *ContainedRD =
6051             getContainedDynamicClass(PointeeTy, IsContained)) {
6052 
6053       unsigned OperationType = 0;
6054       // "overwritten" if we're warning about the destination for any call
6055       // but memcmp; otherwise a verb appropriate to the call.
6056       if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
6057         if (BId == Builtin::BImemcpy)
6058           OperationType = 1;
6059         else if(BId == Builtin::BImemmove)
6060           OperationType = 2;
6061         else if (BId == Builtin::BImemcmp)
6062           OperationType = 3;
6063       }
6064 
6065       DiagRuntimeBehavior(
6066         Dest->getExprLoc(), Dest,
6067         PDiag(diag::warn_dyn_class_memaccess)
6068           << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
6069           << FnName << IsContained << ContainedRD << OperationType
6070           << Call->getCallee()->getSourceRange());
6071     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
6072              BId != Builtin::BImemset)
6073       DiagRuntimeBehavior(
6074         Dest->getExprLoc(), Dest,
6075         PDiag(diag::warn_arc_object_memaccess)
6076           << ArgIdx << FnName << PointeeTy
6077           << Call->getCallee()->getSourceRange());
6078     else
6079       continue;
6080 
6081     DiagRuntimeBehavior(
6082       Dest->getExprLoc(), Dest,
6083       PDiag(diag::note_bad_memaccess_silence)
6084         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
6085     break;
6086   }
6087 }
6088 
6089 // A little helper routine: ignore addition and subtraction of integer literals.
6090 // This intentionally does not ignore all integer constant expressions because
6091 // we don't want to remove sizeof().
6092 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
6093   Ex = Ex->IgnoreParenCasts();
6094 
6095   for (;;) {
6096     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
6097     if (!BO || !BO->isAdditiveOp())
6098       break;
6099 
6100     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
6101     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
6102 
6103     if (isa<IntegerLiteral>(RHS))
6104       Ex = LHS;
6105     else if (isa<IntegerLiteral>(LHS))
6106       Ex = RHS;
6107     else
6108       break;
6109   }
6110 
6111   return Ex;
6112 }
6113 
6114 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
6115                                                       ASTContext &Context) {
6116   // Only handle constant-sized or VLAs, but not flexible members.
6117   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
6118     // Only issue the FIXIT for arrays of size > 1.
6119     if (CAT->getSize().getSExtValue() <= 1)
6120       return false;
6121   } else if (!Ty->isVariableArrayType()) {
6122     return false;
6123   }
6124   return true;
6125 }
6126 
6127 // Warn if the user has made the 'size' argument to strlcpy or strlcat
6128 // be the size of the source, instead of the destination.
6129 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
6130                                     IdentifierInfo *FnName) {
6131 
6132   // Don't crash if the user has the wrong number of arguments
6133   unsigned NumArgs = Call->getNumArgs();
6134   if ((NumArgs != 3) && (NumArgs != 4))
6135     return;
6136 
6137   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
6138   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
6139   const Expr *CompareWithSrc = nullptr;
6140 
6141   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
6142                                      Call->getLocStart(), Call->getRParenLoc()))
6143     return;
6144 
6145   // Look for 'strlcpy(dst, x, sizeof(x))'
6146   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
6147     CompareWithSrc = Ex;
6148   else {
6149     // Look for 'strlcpy(dst, x, strlen(x))'
6150     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
6151       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
6152           SizeCall->getNumArgs() == 1)
6153         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
6154     }
6155   }
6156 
6157   if (!CompareWithSrc)
6158     return;
6159 
6160   // Determine if the argument to sizeof/strlen is equal to the source
6161   // argument.  In principle there's all kinds of things you could do
6162   // here, for instance creating an == expression and evaluating it with
6163   // EvaluateAsBooleanCondition, but this uses a more direct technique:
6164   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
6165   if (!SrcArgDRE)
6166     return;
6167 
6168   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
6169   if (!CompareWithSrcDRE ||
6170       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
6171     return;
6172 
6173   const Expr *OriginalSizeArg = Call->getArg(2);
6174   Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
6175     << OriginalSizeArg->getSourceRange() << FnName;
6176 
6177   // Output a FIXIT hint if the destination is an array (rather than a
6178   // pointer to an array).  This could be enhanced to handle some
6179   // pointers if we know the actual size, like if DstArg is 'array+2'
6180   // we could say 'sizeof(array)-2'.
6181   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
6182   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
6183     return;
6184 
6185   SmallString<128> sizeString;
6186   llvm::raw_svector_ostream OS(sizeString);
6187   OS << "sizeof(";
6188   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
6189   OS << ")";
6190 
6191   Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
6192     << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
6193                                     OS.str());
6194 }
6195 
6196 /// Check if two expressions refer to the same declaration.
6197 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
6198   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
6199     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
6200       return D1->getDecl() == D2->getDecl();
6201   return false;
6202 }
6203 
6204 static const Expr *getStrlenExprArg(const Expr *E) {
6205   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
6206     const FunctionDecl *FD = CE->getDirectCallee();
6207     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
6208       return nullptr;
6209     return CE->getArg(0)->IgnoreParenCasts();
6210   }
6211   return nullptr;
6212 }
6213 
6214 // Warn on anti-patterns as the 'size' argument to strncat.
6215 // The correct size argument should look like following:
6216 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
6217 void Sema::CheckStrncatArguments(const CallExpr *CE,
6218                                  IdentifierInfo *FnName) {
6219   // Don't crash if the user has the wrong number of arguments.
6220   if (CE->getNumArgs() < 3)
6221     return;
6222   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
6223   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
6224   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
6225 
6226   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
6227                                      CE->getRParenLoc()))
6228     return;
6229 
6230   // Identify common expressions, which are wrongly used as the size argument
6231   // to strncat and may lead to buffer overflows.
6232   unsigned PatternType = 0;
6233   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
6234     // - sizeof(dst)
6235     if (referToTheSameDecl(SizeOfArg, DstArg))
6236       PatternType = 1;
6237     // - sizeof(src)
6238     else if (referToTheSameDecl(SizeOfArg, SrcArg))
6239       PatternType = 2;
6240   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
6241     if (BE->getOpcode() == BO_Sub) {
6242       const Expr *L = BE->getLHS()->IgnoreParenCasts();
6243       const Expr *R = BE->getRHS()->IgnoreParenCasts();
6244       // - sizeof(dst) - strlen(dst)
6245       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
6246           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
6247         PatternType = 1;
6248       // - sizeof(src) - (anything)
6249       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
6250         PatternType = 2;
6251     }
6252   }
6253 
6254   if (PatternType == 0)
6255     return;
6256 
6257   // Generate the diagnostic.
6258   SourceLocation SL = LenArg->getLocStart();
6259   SourceRange SR = LenArg->getSourceRange();
6260   SourceManager &SM = getSourceManager();
6261 
6262   // If the function is defined as a builtin macro, do not show macro expansion.
6263   if (SM.isMacroArgExpansion(SL)) {
6264     SL = SM.getSpellingLoc(SL);
6265     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
6266                      SM.getSpellingLoc(SR.getEnd()));
6267   }
6268 
6269   // Check if the destination is an array (rather than a pointer to an array).
6270   QualType DstTy = DstArg->getType();
6271   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
6272                                                                     Context);
6273   if (!isKnownSizeArray) {
6274     if (PatternType == 1)
6275       Diag(SL, diag::warn_strncat_wrong_size) << SR;
6276     else
6277       Diag(SL, diag::warn_strncat_src_size) << SR;
6278     return;
6279   }
6280 
6281   if (PatternType == 1)
6282     Diag(SL, diag::warn_strncat_large_size) << SR;
6283   else
6284     Diag(SL, diag::warn_strncat_src_size) << SR;
6285 
6286   SmallString<128> sizeString;
6287   llvm::raw_svector_ostream OS(sizeString);
6288   OS << "sizeof(";
6289   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
6290   OS << ") - ";
6291   OS << "strlen(";
6292   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
6293   OS << ") - 1";
6294 
6295   Diag(SL, diag::note_strncat_wrong_size)
6296     << FixItHint::CreateReplacement(SR, OS.str());
6297 }
6298 
6299 //===--- CHECK: Return Address of Stack Variable --------------------------===//
6300 
6301 static const Expr *EvalVal(const Expr *E,
6302                            SmallVectorImpl<const DeclRefExpr *> &refVars,
6303                            const Decl *ParentDecl);
6304 static const Expr *EvalAddr(const Expr *E,
6305                             SmallVectorImpl<const DeclRefExpr *> &refVars,
6306                             const Decl *ParentDecl);
6307 
6308 /// CheckReturnStackAddr - Check if a return statement returns the address
6309 ///   of a stack variable.
6310 static void
6311 CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
6312                      SourceLocation ReturnLoc) {
6313 
6314   const Expr *stackE = nullptr;
6315   SmallVector<const DeclRefExpr *, 8> refVars;
6316 
6317   // Perform checking for returned stack addresses, local blocks,
6318   // label addresses or references to temporaries.
6319   if (lhsType->isPointerType() ||
6320       (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
6321     stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
6322   } else if (lhsType->isReferenceType()) {
6323     stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
6324   }
6325 
6326   if (!stackE)
6327     return; // Nothing suspicious was found.
6328 
6329   SourceLocation diagLoc;
6330   SourceRange diagRange;
6331   if (refVars.empty()) {
6332     diagLoc = stackE->getLocStart();
6333     diagRange = stackE->getSourceRange();
6334   } else {
6335     // We followed through a reference variable. 'stackE' contains the
6336     // problematic expression but we will warn at the return statement pointing
6337     // at the reference variable. We will later display the "trail" of
6338     // reference variables using notes.
6339     diagLoc = refVars[0]->getLocStart();
6340     diagRange = refVars[0]->getSourceRange();
6341   }
6342 
6343   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
6344     // address of local var
6345     S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
6346      << DR->getDecl()->getDeclName() << diagRange;
6347   } else if (isa<BlockExpr>(stackE)) { // local block.
6348     S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
6349   } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
6350     S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
6351   } else { // local temporary.
6352     S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
6353      << lhsType->isReferenceType() << diagRange;
6354   }
6355 
6356   // Display the "trail" of reference variables that we followed until we
6357   // found the problematic expression using notes.
6358   for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
6359     const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
6360     // If this var binds to another reference var, show the range of the next
6361     // var, otherwise the var binds to the problematic expression, in which case
6362     // show the range of the expression.
6363     SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
6364                                     : stackE->getSourceRange();
6365     S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
6366         << VD->getDeclName() << range;
6367   }
6368 }
6369 
6370 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
6371 ///  check if the expression in a return statement evaluates to an address
6372 ///  to a location on the stack, a local block, an address of a label, or a
6373 ///  reference to local temporary. The recursion is used to traverse the
6374 ///  AST of the return expression, with recursion backtracking when we
6375 ///  encounter a subexpression that (1) clearly does not lead to one of the
6376 ///  above problematic expressions (2) is something we cannot determine leads to
6377 ///  a problematic expression based on such local checking.
6378 ///
6379 ///  Both EvalAddr and EvalVal follow through reference variables to evaluate
6380 ///  the expression that they point to. Such variables are added to the
6381 ///  'refVars' vector so that we know what the reference variable "trail" was.
6382 ///
6383 ///  EvalAddr processes expressions that are pointers that are used as
6384 ///  references (and not L-values).  EvalVal handles all other values.
6385 ///  At the base case of the recursion is a check for the above problematic
6386 ///  expressions.
6387 ///
6388 ///  This implementation handles:
6389 ///
6390 ///   * pointer-to-pointer casts
6391 ///   * implicit conversions from array references to pointers
6392 ///   * taking the address of fields
6393 ///   * arbitrary interplay between "&" and "*" operators
6394 ///   * pointer arithmetic from an address of a stack variable
6395 ///   * taking the address of an array element where the array is on the stack
6396 static const Expr *EvalAddr(const Expr *E,
6397                             SmallVectorImpl<const DeclRefExpr *> &refVars,
6398                             const Decl *ParentDecl) {
6399   if (E->isTypeDependent())
6400     return nullptr;
6401 
6402   // We should only be called for evaluating pointer expressions.
6403   assert((E->getType()->isAnyPointerType() ||
6404           E->getType()->isBlockPointerType() ||
6405           E->getType()->isObjCQualifiedIdType()) &&
6406          "EvalAddr only works on pointers");
6407 
6408   E = E->IgnoreParens();
6409 
6410   // Our "symbolic interpreter" is just a dispatch off the currently
6411   // viewed AST node.  We then recursively traverse the AST by calling
6412   // EvalAddr and EvalVal appropriately.
6413   switch (E->getStmtClass()) {
6414   case Stmt::DeclRefExprClass: {
6415     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
6416 
6417     // If we leave the immediate function, the lifetime isn't about to end.
6418     if (DR->refersToEnclosingVariableOrCapture())
6419       return nullptr;
6420 
6421     if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
6422       // If this is a reference variable, follow through to the expression that
6423       // it points to.
6424       if (V->hasLocalStorage() &&
6425           V->getType()->isReferenceType() && V->hasInit()) {
6426         // Add the reference variable to the "trail".
6427         refVars.push_back(DR);
6428         return EvalAddr(V->getInit(), refVars, ParentDecl);
6429       }
6430 
6431     return nullptr;
6432   }
6433 
6434   case Stmt::UnaryOperatorClass: {
6435     // The only unary operator that make sense to handle here
6436     // is AddrOf.  All others don't make sense as pointers.
6437     const UnaryOperator *U = cast<UnaryOperator>(E);
6438 
6439     if (U->getOpcode() == UO_AddrOf)
6440       return EvalVal(U->getSubExpr(), refVars, ParentDecl);
6441     return nullptr;
6442   }
6443 
6444   case Stmt::BinaryOperatorClass: {
6445     // Handle pointer arithmetic.  All other binary operators are not valid
6446     // in this context.
6447     const BinaryOperator *B = cast<BinaryOperator>(E);
6448     BinaryOperatorKind op = B->getOpcode();
6449 
6450     if (op != BO_Add && op != BO_Sub)
6451       return nullptr;
6452 
6453     const Expr *Base = B->getLHS();
6454 
6455     // Determine which argument is the real pointer base.  It could be
6456     // the RHS argument instead of the LHS.
6457     if (!Base->getType()->isPointerType())
6458       Base = B->getRHS();
6459 
6460     assert(Base->getType()->isPointerType());
6461     return EvalAddr(Base, refVars, ParentDecl);
6462   }
6463 
6464   // For conditional operators we need to see if either the LHS or RHS are
6465   // valid DeclRefExpr*s.  If one of them is valid, we return it.
6466   case Stmt::ConditionalOperatorClass: {
6467     const ConditionalOperator *C = cast<ConditionalOperator>(E);
6468 
6469     // Handle the GNU extension for missing LHS.
6470     // FIXME: That isn't a ConditionalOperator, so doesn't get here.
6471     if (const Expr *LHSExpr = C->getLHS()) {
6472       // In C++, we can have a throw-expression, which has 'void' type.
6473       if (!LHSExpr->getType()->isVoidType())
6474         if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
6475           return LHS;
6476     }
6477 
6478     // In C++, we can have a throw-expression, which has 'void' type.
6479     if (C->getRHS()->getType()->isVoidType())
6480       return nullptr;
6481 
6482     return EvalAddr(C->getRHS(), refVars, ParentDecl);
6483   }
6484 
6485   case Stmt::BlockExprClass:
6486     if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
6487       return E; // local block.
6488     return nullptr;
6489 
6490   case Stmt::AddrLabelExprClass:
6491     return E; // address of label.
6492 
6493   case Stmt::ExprWithCleanupsClass:
6494     return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
6495                     ParentDecl);
6496 
6497   // For casts, we need to handle conversions from arrays to
6498   // pointer values, and pointer-to-pointer conversions.
6499   case Stmt::ImplicitCastExprClass:
6500   case Stmt::CStyleCastExprClass:
6501   case Stmt::CXXFunctionalCastExprClass:
6502   case Stmt::ObjCBridgedCastExprClass:
6503   case Stmt::CXXStaticCastExprClass:
6504   case Stmt::CXXDynamicCastExprClass:
6505   case Stmt::CXXConstCastExprClass:
6506   case Stmt::CXXReinterpretCastExprClass: {
6507     const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
6508     switch (cast<CastExpr>(E)->getCastKind()) {
6509     case CK_LValueToRValue:
6510     case CK_NoOp:
6511     case CK_BaseToDerived:
6512     case CK_DerivedToBase:
6513     case CK_UncheckedDerivedToBase:
6514     case CK_Dynamic:
6515     case CK_CPointerToObjCPointerCast:
6516     case CK_BlockPointerToObjCPointerCast:
6517     case CK_AnyPointerToBlockPointerCast:
6518       return EvalAddr(SubExpr, refVars, ParentDecl);
6519 
6520     case CK_ArrayToPointerDecay:
6521       return EvalVal(SubExpr, refVars, ParentDecl);
6522 
6523     case CK_BitCast:
6524       if (SubExpr->getType()->isAnyPointerType() ||
6525           SubExpr->getType()->isBlockPointerType() ||
6526           SubExpr->getType()->isObjCQualifiedIdType())
6527         return EvalAddr(SubExpr, refVars, ParentDecl);
6528       else
6529         return nullptr;
6530 
6531     default:
6532       return nullptr;
6533     }
6534   }
6535 
6536   case Stmt::MaterializeTemporaryExprClass:
6537     if (const Expr *Result =
6538             EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
6539                      refVars, ParentDecl))
6540       return Result;
6541     return E;
6542 
6543   // Everything else: we simply don't reason about them.
6544   default:
6545     return nullptr;
6546   }
6547 }
6548 
6549 ///  EvalVal - This function is complements EvalAddr in the mutual recursion.
6550 ///   See the comments for EvalAddr for more details.
6551 static const Expr *EvalVal(const Expr *E,
6552                            SmallVectorImpl<const DeclRefExpr *> &refVars,
6553                            const Decl *ParentDecl) {
6554   do {
6555     // We should only be called for evaluating non-pointer expressions, or
6556     // expressions with a pointer type that are not used as references but
6557     // instead
6558     // are l-values (e.g., DeclRefExpr with a pointer type).
6559 
6560     // Our "symbolic interpreter" is just a dispatch off the currently
6561     // viewed AST node.  We then recursively traverse the AST by calling
6562     // EvalAddr and EvalVal appropriately.
6563 
6564     E = E->IgnoreParens();
6565     switch (E->getStmtClass()) {
6566     case Stmt::ImplicitCastExprClass: {
6567       const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
6568       if (IE->getValueKind() == VK_LValue) {
6569         E = IE->getSubExpr();
6570         continue;
6571       }
6572       return nullptr;
6573     }
6574 
6575     case Stmt::ExprWithCleanupsClass:
6576       return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
6577                      ParentDecl);
6578 
6579     case Stmt::DeclRefExprClass: {
6580       // When we hit a DeclRefExpr we are looking at code that refers to a
6581       // variable's name. If it's not a reference variable we check if it has
6582       // local storage within the function, and if so, return the expression.
6583       const DeclRefExpr *DR = cast<DeclRefExpr>(E);
6584 
6585       // If we leave the immediate function, the lifetime isn't about to end.
6586       if (DR->refersToEnclosingVariableOrCapture())
6587         return nullptr;
6588 
6589       if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
6590         // Check if it refers to itself, e.g. "int& i = i;".
6591         if (V == ParentDecl)
6592           return DR;
6593 
6594         if (V->hasLocalStorage()) {
6595           if (!V->getType()->isReferenceType())
6596             return DR;
6597 
6598           // Reference variable, follow through to the expression that
6599           // it points to.
6600           if (V->hasInit()) {
6601             // Add the reference variable to the "trail".
6602             refVars.push_back(DR);
6603             return EvalVal(V->getInit(), refVars, V);
6604           }
6605         }
6606       }
6607 
6608       return nullptr;
6609     }
6610 
6611     case Stmt::UnaryOperatorClass: {
6612       // The only unary operator that make sense to handle here
6613       // is Deref.  All others don't resolve to a "name."  This includes
6614       // handling all sorts of rvalues passed to a unary operator.
6615       const UnaryOperator *U = cast<UnaryOperator>(E);
6616 
6617       if (U->getOpcode() == UO_Deref)
6618         return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
6619 
6620       return nullptr;
6621     }
6622 
6623     case Stmt::ArraySubscriptExprClass: {
6624       // Array subscripts are potential references to data on the stack.  We
6625       // retrieve the DeclRefExpr* for the array variable if it indeed
6626       // has local storage.
6627       const auto *ASE = cast<ArraySubscriptExpr>(E);
6628       if (ASE->isTypeDependent())
6629         return nullptr;
6630       return EvalAddr(ASE->getBase(), refVars, ParentDecl);
6631     }
6632 
6633     case Stmt::OMPArraySectionExprClass: {
6634       return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
6635                       ParentDecl);
6636     }
6637 
6638     case Stmt::ConditionalOperatorClass: {
6639       // For conditional operators we need to see if either the LHS or RHS are
6640       // non-NULL Expr's.  If one is non-NULL, we return it.
6641       const ConditionalOperator *C = cast<ConditionalOperator>(E);
6642 
6643       // Handle the GNU extension for missing LHS.
6644       if (const Expr *LHSExpr = C->getLHS()) {
6645         // In C++, we can have a throw-expression, which has 'void' type.
6646         if (!LHSExpr->getType()->isVoidType())
6647           if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
6648             return LHS;
6649       }
6650 
6651       // In C++, we can have a throw-expression, which has 'void' type.
6652       if (C->getRHS()->getType()->isVoidType())
6653         return nullptr;
6654 
6655       return EvalVal(C->getRHS(), refVars, ParentDecl);
6656     }
6657 
6658     // Accesses to members are potential references to data on the stack.
6659     case Stmt::MemberExprClass: {
6660       const MemberExpr *M = cast<MemberExpr>(E);
6661 
6662       // Check for indirect access.  We only want direct field accesses.
6663       if (M->isArrow())
6664         return nullptr;
6665 
6666       // Check whether the member type is itself a reference, in which case
6667       // we're not going to refer to the member, but to what the member refers
6668       // to.
6669       if (M->getMemberDecl()->getType()->isReferenceType())
6670         return nullptr;
6671 
6672       return EvalVal(M->getBase(), refVars, ParentDecl);
6673     }
6674 
6675     case Stmt::MaterializeTemporaryExprClass:
6676       if (const Expr *Result =
6677               EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
6678                       refVars, ParentDecl))
6679         return Result;
6680       return E;
6681 
6682     default:
6683       // Check that we don't return or take the address of a reference to a
6684       // temporary. This is only useful in C++.
6685       if (!E->isTypeDependent() && E->isRValue())
6686         return E;
6687 
6688       // Everything else: we simply don't reason about them.
6689       return nullptr;
6690     }
6691   } while (true);
6692 }
6693 
6694 void
6695 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
6696                          SourceLocation ReturnLoc,
6697                          bool isObjCMethod,
6698                          const AttrVec *Attrs,
6699                          const FunctionDecl *FD) {
6700   CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
6701 
6702   // Check if the return value is null but should not be.
6703   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
6704        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
6705       CheckNonNullExpr(*this, RetValExp))
6706     Diag(ReturnLoc, diag::warn_null_ret)
6707       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
6708 
6709   // C++11 [basic.stc.dynamic.allocation]p4:
6710   //   If an allocation function declared with a non-throwing
6711   //   exception-specification fails to allocate storage, it shall return
6712   //   a null pointer. Any other allocation function that fails to allocate
6713   //   storage shall indicate failure only by throwing an exception [...]
6714   if (FD) {
6715     OverloadedOperatorKind Op = FD->getOverloadedOperator();
6716     if (Op == OO_New || Op == OO_Array_New) {
6717       const FunctionProtoType *Proto
6718         = FD->getType()->castAs<FunctionProtoType>();
6719       if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
6720           CheckNonNullExpr(*this, RetValExp))
6721         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
6722           << FD << getLangOpts().CPlusPlus11;
6723     }
6724   }
6725 }
6726 
6727 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
6728 
6729 /// Check for comparisons of floating point operands using != and ==.
6730 /// Issue a warning if these are no self-comparisons, as they are not likely
6731 /// to do what the programmer intended.
6732 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
6733   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
6734   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
6735 
6736   // Special case: check for x == x (which is OK).
6737   // Do not emit warnings for such cases.
6738   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
6739     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
6740       if (DRL->getDecl() == DRR->getDecl())
6741         return;
6742 
6743   // Special case: check for comparisons against literals that can be exactly
6744   //  represented by APFloat.  In such cases, do not emit a warning.  This
6745   //  is a heuristic: often comparison against such literals are used to
6746   //  detect if a value in a variable has not changed.  This clearly can
6747   //  lead to false negatives.
6748   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
6749     if (FLL->isExact())
6750       return;
6751   } else
6752     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
6753       if (FLR->isExact())
6754         return;
6755 
6756   // Check for comparisons with builtin types.
6757   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
6758     if (CL->getBuiltinCallee())
6759       return;
6760 
6761   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
6762     if (CR->getBuiltinCallee())
6763       return;
6764 
6765   // Emit the diagnostic.
6766   Diag(Loc, diag::warn_floatingpoint_eq)
6767     << LHS->getSourceRange() << RHS->getSourceRange();
6768 }
6769 
6770 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
6771 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
6772 
6773 namespace {
6774 
6775 /// Structure recording the 'active' range of an integer-valued
6776 /// expression.
6777 struct IntRange {
6778   /// The number of bits active in the int.
6779   unsigned Width;
6780 
6781   /// True if the int is known not to have negative values.
6782   bool NonNegative;
6783 
6784   IntRange(unsigned Width, bool NonNegative)
6785     : Width(Width), NonNegative(NonNegative)
6786   {}
6787 
6788   /// Returns the range of the bool type.
6789   static IntRange forBoolType() {
6790     return IntRange(1, true);
6791   }
6792 
6793   /// Returns the range of an opaque value of the given integral type.
6794   static IntRange forValueOfType(ASTContext &C, QualType T) {
6795     return forValueOfCanonicalType(C,
6796                           T->getCanonicalTypeInternal().getTypePtr());
6797   }
6798 
6799   /// Returns the range of an opaque value of a canonical integral type.
6800   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
6801     assert(T->isCanonicalUnqualified());
6802 
6803     if (const VectorType *VT = dyn_cast<VectorType>(T))
6804       T = VT->getElementType().getTypePtr();
6805     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
6806       T = CT->getElementType().getTypePtr();
6807     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
6808       T = AT->getValueType().getTypePtr();
6809 
6810     // For enum types, use the known bit width of the enumerators.
6811     if (const EnumType *ET = dyn_cast<EnumType>(T)) {
6812       EnumDecl *Enum = ET->getDecl();
6813       if (!Enum->isCompleteDefinition())
6814         return IntRange(C.getIntWidth(QualType(T, 0)), false);
6815 
6816       unsigned NumPositive = Enum->getNumPositiveBits();
6817       unsigned NumNegative = Enum->getNumNegativeBits();
6818 
6819       if (NumNegative == 0)
6820         return IntRange(NumPositive, true/*NonNegative*/);
6821       else
6822         return IntRange(std::max(NumPositive + 1, NumNegative),
6823                         false/*NonNegative*/);
6824     }
6825 
6826     const BuiltinType *BT = cast<BuiltinType>(T);
6827     assert(BT->isInteger());
6828 
6829     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
6830   }
6831 
6832   /// Returns the "target" range of a canonical integral type, i.e.
6833   /// the range of values expressible in the type.
6834   ///
6835   /// This matches forValueOfCanonicalType except that enums have the
6836   /// full range of their type, not the range of their enumerators.
6837   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
6838     assert(T->isCanonicalUnqualified());
6839 
6840     if (const VectorType *VT = dyn_cast<VectorType>(T))
6841       T = VT->getElementType().getTypePtr();
6842     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
6843       T = CT->getElementType().getTypePtr();
6844     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
6845       T = AT->getValueType().getTypePtr();
6846     if (const EnumType *ET = dyn_cast<EnumType>(T))
6847       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
6848 
6849     const BuiltinType *BT = cast<BuiltinType>(T);
6850     assert(BT->isInteger());
6851 
6852     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
6853   }
6854 
6855   /// Returns the supremum of two ranges: i.e. their conservative merge.
6856   static IntRange join(IntRange L, IntRange R) {
6857     return IntRange(std::max(L.Width, R.Width),
6858                     L.NonNegative && R.NonNegative);
6859   }
6860 
6861   /// Returns the infinum of two ranges: i.e. their aggressive merge.
6862   static IntRange meet(IntRange L, IntRange R) {
6863     return IntRange(std::min(L.Width, R.Width),
6864                     L.NonNegative || R.NonNegative);
6865   }
6866 };
6867 
6868 IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
6869   if (value.isSigned() && value.isNegative())
6870     return IntRange(value.getMinSignedBits(), false);
6871 
6872   if (value.getBitWidth() > MaxWidth)
6873     value = value.trunc(MaxWidth);
6874 
6875   // isNonNegative() just checks the sign bit without considering
6876   // signedness.
6877   return IntRange(value.getActiveBits(), true);
6878 }
6879 
6880 IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
6881                        unsigned MaxWidth) {
6882   if (result.isInt())
6883     return GetValueRange(C, result.getInt(), MaxWidth);
6884 
6885   if (result.isVector()) {
6886     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
6887     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
6888       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
6889       R = IntRange::join(R, El);
6890     }
6891     return R;
6892   }
6893 
6894   if (result.isComplexInt()) {
6895     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
6896     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
6897     return IntRange::join(R, I);
6898   }
6899 
6900   // This can happen with lossless casts to intptr_t of "based" lvalues.
6901   // Assume it might use arbitrary bits.
6902   // FIXME: The only reason we need to pass the type in here is to get
6903   // the sign right on this one case.  It would be nice if APValue
6904   // preserved this.
6905   assert(result.isLValue() || result.isAddrLabelDiff());
6906   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
6907 }
6908 
6909 QualType GetExprType(const Expr *E) {
6910   QualType Ty = E->getType();
6911   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
6912     Ty = AtomicRHS->getValueType();
6913   return Ty;
6914 }
6915 
6916 /// Pseudo-evaluate the given integer expression, estimating the
6917 /// range of values it might take.
6918 ///
6919 /// \param MaxWidth - the width to which the value will be truncated
6920 IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
6921   E = E->IgnoreParens();
6922 
6923   // Try a full evaluation first.
6924   Expr::EvalResult result;
6925   if (E->EvaluateAsRValue(result, C))
6926     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
6927 
6928   // I think we only want to look through implicit casts here; if the
6929   // user has an explicit widening cast, we should treat the value as
6930   // being of the new, wider type.
6931   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
6932     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
6933       return GetExprRange(C, CE->getSubExpr(), MaxWidth);
6934 
6935     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
6936 
6937     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
6938                          CE->getCastKind() == CK_BooleanToSignedIntegral;
6939 
6940     // Assume that non-integer casts can span the full range of the type.
6941     if (!isIntegerCast)
6942       return OutputTypeRange;
6943 
6944     IntRange SubRange
6945       = GetExprRange(C, CE->getSubExpr(),
6946                      std::min(MaxWidth, OutputTypeRange.Width));
6947 
6948     // Bail out if the subexpr's range is as wide as the cast type.
6949     if (SubRange.Width >= OutputTypeRange.Width)
6950       return OutputTypeRange;
6951 
6952     // Otherwise, we take the smaller width, and we're non-negative if
6953     // either the output type or the subexpr is.
6954     return IntRange(SubRange.Width,
6955                     SubRange.NonNegative || OutputTypeRange.NonNegative);
6956   }
6957 
6958   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
6959     // If we can fold the condition, just take that operand.
6960     bool CondResult;
6961     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
6962       return GetExprRange(C, CondResult ? CO->getTrueExpr()
6963                                         : CO->getFalseExpr(),
6964                           MaxWidth);
6965 
6966     // Otherwise, conservatively merge.
6967     IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
6968     IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
6969     return IntRange::join(L, R);
6970   }
6971 
6972   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
6973     switch (BO->getOpcode()) {
6974 
6975     // Boolean-valued operations are single-bit and positive.
6976     case BO_LAnd:
6977     case BO_LOr:
6978     case BO_LT:
6979     case BO_GT:
6980     case BO_LE:
6981     case BO_GE:
6982     case BO_EQ:
6983     case BO_NE:
6984       return IntRange::forBoolType();
6985 
6986     // The type of the assignments is the type of the LHS, so the RHS
6987     // is not necessarily the same type.
6988     case BO_MulAssign:
6989     case BO_DivAssign:
6990     case BO_RemAssign:
6991     case BO_AddAssign:
6992     case BO_SubAssign:
6993     case BO_XorAssign:
6994     case BO_OrAssign:
6995       // TODO: bitfields?
6996       return IntRange::forValueOfType(C, GetExprType(E));
6997 
6998     // Simple assignments just pass through the RHS, which will have
6999     // been coerced to the LHS type.
7000     case BO_Assign:
7001       // TODO: bitfields?
7002       return GetExprRange(C, BO->getRHS(), MaxWidth);
7003 
7004     // Operations with opaque sources are black-listed.
7005     case BO_PtrMemD:
7006     case BO_PtrMemI:
7007       return IntRange::forValueOfType(C, GetExprType(E));
7008 
7009     // Bitwise-and uses the *infinum* of the two source ranges.
7010     case BO_And:
7011     case BO_AndAssign:
7012       return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
7013                             GetExprRange(C, BO->getRHS(), MaxWidth));
7014 
7015     // Left shift gets black-listed based on a judgement call.
7016     case BO_Shl:
7017       // ...except that we want to treat '1 << (blah)' as logically
7018       // positive.  It's an important idiom.
7019       if (IntegerLiteral *I
7020             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
7021         if (I->getValue() == 1) {
7022           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
7023           return IntRange(R.Width, /*NonNegative*/ true);
7024         }
7025       }
7026       // fallthrough
7027 
7028     case BO_ShlAssign:
7029       return IntRange::forValueOfType(C, GetExprType(E));
7030 
7031     // Right shift by a constant can narrow its left argument.
7032     case BO_Shr:
7033     case BO_ShrAssign: {
7034       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
7035 
7036       // If the shift amount is a positive constant, drop the width by
7037       // that much.
7038       llvm::APSInt shift;
7039       if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
7040           shift.isNonNegative()) {
7041         unsigned zext = shift.getZExtValue();
7042         if (zext >= L.Width)
7043           L.Width = (L.NonNegative ? 0 : 1);
7044         else
7045           L.Width -= zext;
7046       }
7047 
7048       return L;
7049     }
7050 
7051     // Comma acts as its right operand.
7052     case BO_Comma:
7053       return GetExprRange(C, BO->getRHS(), MaxWidth);
7054 
7055     // Black-list pointer subtractions.
7056     case BO_Sub:
7057       if (BO->getLHS()->getType()->isPointerType())
7058         return IntRange::forValueOfType(C, GetExprType(E));
7059       break;
7060 
7061     // The width of a division result is mostly determined by the size
7062     // of the LHS.
7063     case BO_Div: {
7064       // Don't 'pre-truncate' the operands.
7065       unsigned opWidth = C.getIntWidth(GetExprType(E));
7066       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
7067 
7068       // If the divisor is constant, use that.
7069       llvm::APSInt divisor;
7070       if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
7071         unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
7072         if (log2 >= L.Width)
7073           L.Width = (L.NonNegative ? 0 : 1);
7074         else
7075           L.Width = std::min(L.Width - log2, MaxWidth);
7076         return L;
7077       }
7078 
7079       // Otherwise, just use the LHS's width.
7080       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
7081       return IntRange(L.Width, L.NonNegative && R.NonNegative);
7082     }
7083 
7084     // The result of a remainder can't be larger than the result of
7085     // either side.
7086     case BO_Rem: {
7087       // Don't 'pre-truncate' the operands.
7088       unsigned opWidth = C.getIntWidth(GetExprType(E));
7089       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
7090       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
7091 
7092       IntRange meet = IntRange::meet(L, R);
7093       meet.Width = std::min(meet.Width, MaxWidth);
7094       return meet;
7095     }
7096 
7097     // The default behavior is okay for these.
7098     case BO_Mul:
7099     case BO_Add:
7100     case BO_Xor:
7101     case BO_Or:
7102       break;
7103     }
7104 
7105     // The default case is to treat the operation as if it were closed
7106     // on the narrowest type that encompasses both operands.
7107     IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
7108     IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
7109     return IntRange::join(L, R);
7110   }
7111 
7112   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
7113     switch (UO->getOpcode()) {
7114     // Boolean-valued operations are white-listed.
7115     case UO_LNot:
7116       return IntRange::forBoolType();
7117 
7118     // Operations with opaque sources are black-listed.
7119     case UO_Deref:
7120     case UO_AddrOf: // should be impossible
7121       return IntRange::forValueOfType(C, GetExprType(E));
7122 
7123     default:
7124       return GetExprRange(C, UO->getSubExpr(), MaxWidth);
7125     }
7126   }
7127 
7128   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
7129     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
7130 
7131   if (const auto *BitField = E->getSourceBitField())
7132     return IntRange(BitField->getBitWidthValue(C),
7133                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
7134 
7135   return IntRange::forValueOfType(C, GetExprType(E));
7136 }
7137 
7138 IntRange GetExprRange(ASTContext &C, const Expr *E) {
7139   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
7140 }
7141 
7142 /// Checks whether the given value, which currently has the given
7143 /// source semantics, has the same value when coerced through the
7144 /// target semantics.
7145 bool IsSameFloatAfterCast(const llvm::APFloat &value,
7146                           const llvm::fltSemantics &Src,
7147                           const llvm::fltSemantics &Tgt) {
7148   llvm::APFloat truncated = value;
7149 
7150   bool ignored;
7151   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
7152   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
7153 
7154   return truncated.bitwiseIsEqual(value);
7155 }
7156 
7157 /// Checks whether the given value, which currently has the given
7158 /// source semantics, has the same value when coerced through the
7159 /// target semantics.
7160 ///
7161 /// The value might be a vector of floats (or a complex number).
7162 bool IsSameFloatAfterCast(const APValue &value,
7163                           const llvm::fltSemantics &Src,
7164                           const llvm::fltSemantics &Tgt) {
7165   if (value.isFloat())
7166     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
7167 
7168   if (value.isVector()) {
7169     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
7170       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
7171         return false;
7172     return true;
7173   }
7174 
7175   assert(value.isComplexFloat());
7176   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
7177           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
7178 }
7179 
7180 void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
7181 
7182 bool IsZero(Sema &S, Expr *E) {
7183   // Suppress cases where we are comparing against an enum constant.
7184   if (const DeclRefExpr *DR =
7185       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
7186     if (isa<EnumConstantDecl>(DR->getDecl()))
7187       return false;
7188 
7189   // Suppress cases where the '0' value is expanded from a macro.
7190   if (E->getLocStart().isMacroID())
7191     return false;
7192 
7193   llvm::APSInt Value;
7194   return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
7195 }
7196 
7197 bool HasEnumType(Expr *E) {
7198   // Strip off implicit integral promotions.
7199   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
7200     if (ICE->getCastKind() != CK_IntegralCast &&
7201         ICE->getCastKind() != CK_NoOp)
7202       break;
7203     E = ICE->getSubExpr();
7204   }
7205 
7206   return E->getType()->isEnumeralType();
7207 }
7208 
7209 void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
7210   // Disable warning in template instantiations.
7211   if (!S.ActiveTemplateInstantiations.empty())
7212     return;
7213 
7214   BinaryOperatorKind op = E->getOpcode();
7215   if (E->isValueDependent())
7216     return;
7217 
7218   if (op == BO_LT && IsZero(S, E->getRHS())) {
7219     S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
7220       << "< 0" << "false" << HasEnumType(E->getLHS())
7221       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
7222   } else if (op == BO_GE && IsZero(S, E->getRHS())) {
7223     S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
7224       << ">= 0" << "true" << HasEnumType(E->getLHS())
7225       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
7226   } else if (op == BO_GT && IsZero(S, E->getLHS())) {
7227     S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
7228       << "0 >" << "false" << HasEnumType(E->getRHS())
7229       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
7230   } else if (op == BO_LE && IsZero(S, E->getLHS())) {
7231     S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
7232       << "0 <=" << "true" << HasEnumType(E->getRHS())
7233       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
7234   }
7235 }
7236 
7237 void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
7238                                   Expr *Constant, Expr *Other,
7239                                   llvm::APSInt Value,
7240                                   bool RhsConstant) {
7241   // Disable warning in template instantiations.
7242   if (!S.ActiveTemplateInstantiations.empty())
7243     return;
7244 
7245   // TODO: Investigate using GetExprRange() to get tighter bounds
7246   // on the bit ranges.
7247   QualType OtherT = Other->getType();
7248   if (const auto *AT = OtherT->getAs<AtomicType>())
7249     OtherT = AT->getValueType();
7250   IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
7251   unsigned OtherWidth = OtherRange.Width;
7252 
7253   bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
7254 
7255   // 0 values are handled later by CheckTrivialUnsignedComparison().
7256   if ((Value == 0) && (!OtherIsBooleanType))
7257     return;
7258 
7259   BinaryOperatorKind op = E->getOpcode();
7260   bool IsTrue = true;
7261 
7262   // Used for diagnostic printout.
7263   enum {
7264     LiteralConstant = 0,
7265     CXXBoolLiteralTrue,
7266     CXXBoolLiteralFalse
7267   } LiteralOrBoolConstant = LiteralConstant;
7268 
7269   if (!OtherIsBooleanType) {
7270     QualType ConstantT = Constant->getType();
7271     QualType CommonT = E->getLHS()->getType();
7272 
7273     if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
7274       return;
7275     assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
7276            "comparison with non-integer type");
7277 
7278     bool ConstantSigned = ConstantT->isSignedIntegerType();
7279     bool CommonSigned = CommonT->isSignedIntegerType();
7280 
7281     bool EqualityOnly = false;
7282 
7283     if (CommonSigned) {
7284       // The common type is signed, therefore no signed to unsigned conversion.
7285       if (!OtherRange.NonNegative) {
7286         // Check that the constant is representable in type OtherT.
7287         if (ConstantSigned) {
7288           if (OtherWidth >= Value.getMinSignedBits())
7289             return;
7290         } else { // !ConstantSigned
7291           if (OtherWidth >= Value.getActiveBits() + 1)
7292             return;
7293         }
7294       } else { // !OtherSigned
7295                // Check that the constant is representable in type OtherT.
7296         // Negative values are out of range.
7297         if (ConstantSigned) {
7298           if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
7299             return;
7300         } else { // !ConstantSigned
7301           if (OtherWidth >= Value.getActiveBits())
7302             return;
7303         }
7304       }
7305     } else { // !CommonSigned
7306       if (OtherRange.NonNegative) {
7307         if (OtherWidth >= Value.getActiveBits())
7308           return;
7309       } else { // OtherSigned
7310         assert(!ConstantSigned &&
7311                "Two signed types converted to unsigned types.");
7312         // Check to see if the constant is representable in OtherT.
7313         if (OtherWidth > Value.getActiveBits())
7314           return;
7315         // Check to see if the constant is equivalent to a negative value
7316         // cast to CommonT.
7317         if (S.Context.getIntWidth(ConstantT) ==
7318                 S.Context.getIntWidth(CommonT) &&
7319             Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
7320           return;
7321         // The constant value rests between values that OtherT can represent
7322         // after conversion.  Relational comparison still works, but equality
7323         // comparisons will be tautological.
7324         EqualityOnly = true;
7325       }
7326     }
7327 
7328     bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
7329 
7330     if (op == BO_EQ || op == BO_NE) {
7331       IsTrue = op == BO_NE;
7332     } else if (EqualityOnly) {
7333       return;
7334     } else if (RhsConstant) {
7335       if (op == BO_GT || op == BO_GE)
7336         IsTrue = !PositiveConstant;
7337       else // op == BO_LT || op == BO_LE
7338         IsTrue = PositiveConstant;
7339     } else {
7340       if (op == BO_LT || op == BO_LE)
7341         IsTrue = !PositiveConstant;
7342       else // op == BO_GT || op == BO_GE
7343         IsTrue = PositiveConstant;
7344     }
7345   } else {
7346     // Other isKnownToHaveBooleanValue
7347     enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
7348     enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
7349     enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
7350 
7351     static const struct LinkedConditions {
7352       CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
7353       CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
7354       CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
7355       CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
7356       CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
7357       CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
7358 
7359     } TruthTable = {
7360         // Constant on LHS.              | Constant on RHS.              |
7361         // LT_Zero| Zero  | One   |GT_One| LT_Zero| Zero  | One   |GT_One|
7362         { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
7363         { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
7364         { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
7365         { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
7366         { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
7367         { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
7368       };
7369 
7370     bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
7371 
7372     enum ConstantValue ConstVal = Zero;
7373     if (Value.isUnsigned() || Value.isNonNegative()) {
7374       if (Value == 0) {
7375         LiteralOrBoolConstant =
7376             ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
7377         ConstVal = Zero;
7378       } else if (Value == 1) {
7379         LiteralOrBoolConstant =
7380             ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
7381         ConstVal = One;
7382       } else {
7383         LiteralOrBoolConstant = LiteralConstant;
7384         ConstVal = GT_One;
7385       }
7386     } else {
7387       ConstVal = LT_Zero;
7388     }
7389 
7390     CompareBoolWithConstantResult CmpRes;
7391 
7392     switch (op) {
7393     case BO_LT:
7394       CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
7395       break;
7396     case BO_GT:
7397       CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
7398       break;
7399     case BO_LE:
7400       CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
7401       break;
7402     case BO_GE:
7403       CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
7404       break;
7405     case BO_EQ:
7406       CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
7407       break;
7408     case BO_NE:
7409       CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
7410       break;
7411     default:
7412       CmpRes = Unkwn;
7413       break;
7414     }
7415 
7416     if (CmpRes == AFals) {
7417       IsTrue = false;
7418     } else if (CmpRes == ATrue) {
7419       IsTrue = true;
7420     } else {
7421       return;
7422     }
7423   }
7424 
7425   // If this is a comparison to an enum constant, include that
7426   // constant in the diagnostic.
7427   const EnumConstantDecl *ED = nullptr;
7428   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
7429     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
7430 
7431   SmallString<64> PrettySourceValue;
7432   llvm::raw_svector_ostream OS(PrettySourceValue);
7433   if (ED)
7434     OS << '\'' << *ED << "' (" << Value << ")";
7435   else
7436     OS << Value;
7437 
7438   S.DiagRuntimeBehavior(
7439     E->getOperatorLoc(), E,
7440     S.PDiag(diag::warn_out_of_range_compare)
7441         << OS.str() << LiteralOrBoolConstant
7442         << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
7443         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
7444 }
7445 
7446 /// Analyze the operands of the given comparison.  Implements the
7447 /// fallback case from AnalyzeComparison.
7448 void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
7449   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
7450   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
7451 }
7452 
7453 /// \brief Implements -Wsign-compare.
7454 ///
7455 /// \param E the binary operator to check for warnings
7456 void AnalyzeComparison(Sema &S, BinaryOperator *E) {
7457   // The type the comparison is being performed in.
7458   QualType T = E->getLHS()->getType();
7459 
7460   // Only analyze comparison operators where both sides have been converted to
7461   // the same type.
7462   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
7463     return AnalyzeImpConvsInComparison(S, E);
7464 
7465   // Don't analyze value-dependent comparisons directly.
7466   if (E->isValueDependent())
7467     return AnalyzeImpConvsInComparison(S, E);
7468 
7469   Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
7470   Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
7471 
7472   bool IsComparisonConstant = false;
7473 
7474   // Check whether an integer constant comparison results in a value
7475   // of 'true' or 'false'.
7476   if (T->isIntegralType(S.Context)) {
7477     llvm::APSInt RHSValue;
7478     bool IsRHSIntegralLiteral =
7479       RHS->isIntegerConstantExpr(RHSValue, S.Context);
7480     llvm::APSInt LHSValue;
7481     bool IsLHSIntegralLiteral =
7482       LHS->isIntegerConstantExpr(LHSValue, S.Context);
7483     if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
7484         DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
7485     else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
7486       DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
7487     else
7488       IsComparisonConstant =
7489         (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
7490   } else if (!T->hasUnsignedIntegerRepresentation())
7491       IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
7492 
7493   // We don't do anything special if this isn't an unsigned integral
7494   // comparison:  we're only interested in integral comparisons, and
7495   // signed comparisons only happen in cases we don't care to warn about.
7496   //
7497   // We also don't care about value-dependent expressions or expressions
7498   // whose result is a constant.
7499   if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
7500     return AnalyzeImpConvsInComparison(S, E);
7501 
7502   // Check to see if one of the (unmodified) operands is of different
7503   // signedness.
7504   Expr *signedOperand, *unsignedOperand;
7505   if (LHS->getType()->hasSignedIntegerRepresentation()) {
7506     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
7507            "unsigned comparison between two signed integer expressions?");
7508     signedOperand = LHS;
7509     unsignedOperand = RHS;
7510   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
7511     signedOperand = RHS;
7512     unsignedOperand = LHS;
7513   } else {
7514     CheckTrivialUnsignedComparison(S, E);
7515     return AnalyzeImpConvsInComparison(S, E);
7516   }
7517 
7518   // Otherwise, calculate the effective range of the signed operand.
7519   IntRange signedRange = GetExprRange(S.Context, signedOperand);
7520 
7521   // Go ahead and analyze implicit conversions in the operands.  Note
7522   // that we skip the implicit conversions on both sides.
7523   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
7524   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
7525 
7526   // If the signed range is non-negative, -Wsign-compare won't fire,
7527   // but we should still check for comparisons which are always true
7528   // or false.
7529   if (signedRange.NonNegative)
7530     return CheckTrivialUnsignedComparison(S, E);
7531 
7532   // For (in)equality comparisons, if the unsigned operand is a
7533   // constant which cannot collide with a overflowed signed operand,
7534   // then reinterpreting the signed operand as unsigned will not
7535   // change the result of the comparison.
7536   if (E->isEqualityOp()) {
7537     unsigned comparisonWidth = S.Context.getIntWidth(T);
7538     IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
7539 
7540     // We should never be unable to prove that the unsigned operand is
7541     // non-negative.
7542     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
7543 
7544     if (unsignedRange.Width < comparisonWidth)
7545       return;
7546   }
7547 
7548   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
7549     S.PDiag(diag::warn_mixed_sign_comparison)
7550       << LHS->getType() << RHS->getType()
7551       << LHS->getSourceRange() << RHS->getSourceRange());
7552 }
7553 
7554 /// Analyzes an attempt to assign the given value to a bitfield.
7555 ///
7556 /// Returns true if there was something fishy about the attempt.
7557 bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
7558                                SourceLocation InitLoc) {
7559   assert(Bitfield->isBitField());
7560   if (Bitfield->isInvalidDecl())
7561     return false;
7562 
7563   // White-list bool bitfields.
7564   if (Bitfield->getType()->isBooleanType())
7565     return false;
7566 
7567   // Ignore value- or type-dependent expressions.
7568   if (Bitfield->getBitWidth()->isValueDependent() ||
7569       Bitfield->getBitWidth()->isTypeDependent() ||
7570       Init->isValueDependent() ||
7571       Init->isTypeDependent())
7572     return false;
7573 
7574   Expr *OriginalInit = Init->IgnoreParenImpCasts();
7575 
7576   llvm::APSInt Value;
7577   if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
7578     return false;
7579 
7580   unsigned OriginalWidth = Value.getBitWidth();
7581   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
7582 
7583   if (OriginalWidth <= FieldWidth)
7584     return false;
7585 
7586   // Compute the value which the bitfield will contain.
7587   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
7588   TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
7589 
7590   // Check whether the stored value is equal to the original value.
7591   TruncatedValue = TruncatedValue.extend(OriginalWidth);
7592   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
7593     return false;
7594 
7595   // Special-case bitfields of width 1: booleans are naturally 0/1, and
7596   // therefore don't strictly fit into a signed bitfield of width 1.
7597   if (FieldWidth == 1 && Value == 1)
7598     return false;
7599 
7600   std::string PrettyValue = Value.toString(10);
7601   std::string PrettyTrunc = TruncatedValue.toString(10);
7602 
7603   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
7604     << PrettyValue << PrettyTrunc << OriginalInit->getType()
7605     << Init->getSourceRange();
7606 
7607   return true;
7608 }
7609 
7610 /// Analyze the given simple or compound assignment for warning-worthy
7611 /// operations.
7612 void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
7613   // Just recurse on the LHS.
7614   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
7615 
7616   // We want to recurse on the RHS as normal unless we're assigning to
7617   // a bitfield.
7618   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
7619     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
7620                                   E->getOperatorLoc())) {
7621       // Recurse, ignoring any implicit conversions on the RHS.
7622       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
7623                                         E->getOperatorLoc());
7624     }
7625   }
7626 
7627   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
7628 }
7629 
7630 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
7631 void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
7632                      SourceLocation CContext, unsigned diag,
7633                      bool pruneControlFlow = false) {
7634   if (pruneControlFlow) {
7635     S.DiagRuntimeBehavior(E->getExprLoc(), E,
7636                           S.PDiag(diag)
7637                             << SourceType << T << E->getSourceRange()
7638                             << SourceRange(CContext));
7639     return;
7640   }
7641   S.Diag(E->getExprLoc(), diag)
7642     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
7643 }
7644 
7645 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
7646 void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
7647                      unsigned diag, bool pruneControlFlow = false) {
7648   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
7649 }
7650 
7651 
7652 /// Diagnose an implicit cast from a floating point value to an integer value.
7653 void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
7654 
7655                              SourceLocation CContext) {
7656   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
7657   const bool PruneWarnings = !S.ActiveTemplateInstantiations.empty();
7658 
7659   Expr *InnerE = E->IgnoreParenImpCasts();
7660   // We also want to warn on, e.g., "int i = -1.234"
7661   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
7662     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
7663       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
7664 
7665   const bool IsLiteral =
7666       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
7667 
7668   llvm::APFloat Value(0.0);
7669   bool IsConstant =
7670     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
7671   if (!IsConstant) {
7672     return DiagnoseImpCast(S, E, T, CContext,
7673                            diag::warn_impcast_float_integer, PruneWarnings);
7674   }
7675 
7676   bool isExact = false;
7677 
7678   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
7679                             T->hasUnsignedIntegerRepresentation());
7680   if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero,
7681                              &isExact) == llvm::APFloat::opOK &&
7682       isExact) {
7683     if (IsLiteral) return;
7684     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
7685                            PruneWarnings);
7686   }
7687 
7688   unsigned DiagID = 0;
7689   if (IsLiteral) {
7690     // Warn on floating point literal to integer.
7691     DiagID = diag::warn_impcast_literal_float_to_integer;
7692   } else if (IntegerValue == 0) {
7693     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
7694       return DiagnoseImpCast(S, E, T, CContext,
7695                              diag::warn_impcast_float_integer, PruneWarnings);
7696     }
7697     // Warn on non-zero to zero conversion.
7698     DiagID = diag::warn_impcast_float_to_integer_zero;
7699   } else {
7700     if (IntegerValue.isUnsigned()) {
7701       if (!IntegerValue.isMaxValue()) {
7702         return DiagnoseImpCast(S, E, T, CContext,
7703                                diag::warn_impcast_float_integer, PruneWarnings);
7704       }
7705     } else {  // IntegerValue.isSigned()
7706       if (!IntegerValue.isMaxSignedValue() &&
7707           !IntegerValue.isMinSignedValue()) {
7708         return DiagnoseImpCast(S, E, T, CContext,
7709                                diag::warn_impcast_float_integer, PruneWarnings);
7710       }
7711     }
7712     // Warn on evaluatable floating point expression to integer conversion.
7713     DiagID = diag::warn_impcast_float_to_integer;
7714   }
7715 
7716   // FIXME: Force the precision of the source value down so we don't print
7717   // digits which are usually useless (we don't really care here if we
7718   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
7719   // would automatically print the shortest representation, but it's a bit
7720   // tricky to implement.
7721   SmallString<16> PrettySourceValue;
7722   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
7723   precision = (precision * 59 + 195) / 196;
7724   Value.toString(PrettySourceValue, precision);
7725 
7726   SmallString<16> PrettyTargetValue;
7727   if (IsBool)
7728     PrettyTargetValue = Value.isZero() ? "false" : "true";
7729   else
7730     IntegerValue.toString(PrettyTargetValue);
7731 
7732   if (PruneWarnings) {
7733     S.DiagRuntimeBehavior(E->getExprLoc(), E,
7734                           S.PDiag(DiagID)
7735                               << E->getType() << T.getUnqualifiedType()
7736                               << PrettySourceValue << PrettyTargetValue
7737                               << E->getSourceRange() << SourceRange(CContext));
7738   } else {
7739     S.Diag(E->getExprLoc(), DiagID)
7740         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
7741         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
7742   }
7743 }
7744 
7745 std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
7746   if (!Range.Width) return "0";
7747 
7748   llvm::APSInt ValueInRange = Value;
7749   ValueInRange.setIsSigned(!Range.NonNegative);
7750   ValueInRange = ValueInRange.trunc(Range.Width);
7751   return ValueInRange.toString(10);
7752 }
7753 
7754 bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
7755   if (!isa<ImplicitCastExpr>(Ex))
7756     return false;
7757 
7758   Expr *InnerE = Ex->IgnoreParenImpCasts();
7759   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
7760   const Type *Source =
7761     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
7762   if (Target->isDependentType())
7763     return false;
7764 
7765   const BuiltinType *FloatCandidateBT =
7766     dyn_cast<BuiltinType>(ToBool ? Source : Target);
7767   const Type *BoolCandidateType = ToBool ? Target : Source;
7768 
7769   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
7770           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
7771 }
7772 
7773 void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
7774                                       SourceLocation CC) {
7775   unsigned NumArgs = TheCall->getNumArgs();
7776   for (unsigned i = 0; i < NumArgs; ++i) {
7777     Expr *CurrA = TheCall->getArg(i);
7778     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
7779       continue;
7780 
7781     bool IsSwapped = ((i > 0) &&
7782         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
7783     IsSwapped |= ((i < (NumArgs - 1)) &&
7784         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
7785     if (IsSwapped) {
7786       // Warn on this floating-point to bool conversion.
7787       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
7788                       CurrA->getType(), CC,
7789                       diag::warn_impcast_floating_point_to_bool);
7790     }
7791   }
7792 }
7793 
7794 void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) {
7795   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
7796                         E->getExprLoc()))
7797     return;
7798 
7799   // Don't warn on functions which have return type nullptr_t.
7800   if (isa<CallExpr>(E))
7801     return;
7802 
7803   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
7804   const Expr::NullPointerConstantKind NullKind =
7805       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
7806   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
7807     return;
7808 
7809   // Return if target type is a safe conversion.
7810   if (T->isAnyPointerType() || T->isBlockPointerType() ||
7811       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
7812     return;
7813 
7814   SourceLocation Loc = E->getSourceRange().getBegin();
7815 
7816   // Venture through the macro stacks to get to the source of macro arguments.
7817   // The new location is a better location than the complete location that was
7818   // passed in.
7819   while (S.SourceMgr.isMacroArgExpansion(Loc))
7820     Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc);
7821 
7822   while (S.SourceMgr.isMacroArgExpansion(CC))
7823     CC = S.SourceMgr.getImmediateMacroCallerLoc(CC);
7824 
7825   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
7826   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
7827     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
7828         Loc, S.SourceMgr, S.getLangOpts());
7829     if (MacroName == "NULL")
7830       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
7831   }
7832 
7833   // Only warn if the null and context location are in the same macro expansion.
7834   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
7835     return;
7836 
7837   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
7838       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
7839       << FixItHint::CreateReplacement(Loc,
7840                                       S.getFixItZeroLiteralForType(T, Loc));
7841 }
7842 
7843 void checkObjCArrayLiteral(Sema &S, QualType TargetType,
7844                            ObjCArrayLiteral *ArrayLiteral);
7845 void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
7846                                 ObjCDictionaryLiteral *DictionaryLiteral);
7847 
7848 /// Check a single element within a collection literal against the
7849 /// target element type.
7850 void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType,
7851                                        Expr *Element, unsigned ElementKind) {
7852   // Skip a bitcast to 'id' or qualified 'id'.
7853   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
7854     if (ICE->getCastKind() == CK_BitCast &&
7855         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
7856       Element = ICE->getSubExpr();
7857   }
7858 
7859   QualType ElementType = Element->getType();
7860   ExprResult ElementResult(Element);
7861   if (ElementType->getAs<ObjCObjectPointerType>() &&
7862       S.CheckSingleAssignmentConstraints(TargetElementType,
7863                                          ElementResult,
7864                                          false, false)
7865         != Sema::Compatible) {
7866     S.Diag(Element->getLocStart(),
7867            diag::warn_objc_collection_literal_element)
7868       << ElementType << ElementKind << TargetElementType
7869       << Element->getSourceRange();
7870   }
7871 
7872   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
7873     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
7874   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
7875     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
7876 }
7877 
7878 /// Check an Objective-C array literal being converted to the given
7879 /// target type.
7880 void checkObjCArrayLiteral(Sema &S, QualType TargetType,
7881                            ObjCArrayLiteral *ArrayLiteral) {
7882   if (!S.NSArrayDecl)
7883     return;
7884 
7885   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
7886   if (!TargetObjCPtr)
7887     return;
7888 
7889   if (TargetObjCPtr->isUnspecialized() ||
7890       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
7891         != S.NSArrayDecl->getCanonicalDecl())
7892     return;
7893 
7894   auto TypeArgs = TargetObjCPtr->getTypeArgs();
7895   if (TypeArgs.size() != 1)
7896     return;
7897 
7898   QualType TargetElementType = TypeArgs[0];
7899   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
7900     checkObjCCollectionLiteralElement(S, TargetElementType,
7901                                       ArrayLiteral->getElement(I),
7902                                       0);
7903   }
7904 }
7905 
7906 /// Check an Objective-C dictionary literal being converted to the given
7907 /// target type.
7908 void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
7909                                 ObjCDictionaryLiteral *DictionaryLiteral) {
7910   if (!S.NSDictionaryDecl)
7911     return;
7912 
7913   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
7914   if (!TargetObjCPtr)
7915     return;
7916 
7917   if (TargetObjCPtr->isUnspecialized() ||
7918       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
7919         != S.NSDictionaryDecl->getCanonicalDecl())
7920     return;
7921 
7922   auto TypeArgs = TargetObjCPtr->getTypeArgs();
7923   if (TypeArgs.size() != 2)
7924     return;
7925 
7926   QualType TargetKeyType = TypeArgs[0];
7927   QualType TargetObjectType = TypeArgs[1];
7928   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
7929     auto Element = DictionaryLiteral->getKeyValueElement(I);
7930     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
7931     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
7932   }
7933 }
7934 
7935 // Helper function to filter out cases for constant width constant conversion.
7936 // Don't warn on char array initialization or for non-decimal values.
7937 bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
7938                                    SourceLocation CC) {
7939   // If initializing from a constant, and the constant starts with '0',
7940   // then it is a binary, octal, or hexadecimal.  Allow these constants
7941   // to fill all the bits, even if there is a sign change.
7942   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
7943     const char FirstLiteralCharacter =
7944         S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
7945     if (FirstLiteralCharacter == '0')
7946       return false;
7947   }
7948 
7949   // If the CC location points to a '{', and the type is char, then assume
7950   // assume it is an array initialization.
7951   if (CC.isValid() && T->isCharType()) {
7952     const char FirstContextCharacter =
7953         S.getSourceManager().getCharacterData(CC)[0];
7954     if (FirstContextCharacter == '{')
7955       return false;
7956   }
7957 
7958   return true;
7959 }
7960 
7961 void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
7962                              SourceLocation CC, bool *ICContext = nullptr) {
7963   if (E->isTypeDependent() || E->isValueDependent()) return;
7964 
7965   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
7966   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
7967   if (Source == Target) return;
7968   if (Target->isDependentType()) return;
7969 
7970   // If the conversion context location is invalid don't complain. We also
7971   // don't want to emit a warning if the issue occurs from the expansion of
7972   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
7973   // delay this check as long as possible. Once we detect we are in that
7974   // scenario, we just return.
7975   if (CC.isInvalid())
7976     return;
7977 
7978   // Diagnose implicit casts to bool.
7979   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
7980     if (isa<StringLiteral>(E))
7981       // Warn on string literal to bool.  Checks for string literals in logical
7982       // and expressions, for instance, assert(0 && "error here"), are
7983       // prevented by a check in AnalyzeImplicitConversions().
7984       return DiagnoseImpCast(S, E, T, CC,
7985                              diag::warn_impcast_string_literal_to_bool);
7986     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
7987         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
7988       // This covers the literal expressions that evaluate to Objective-C
7989       // objects.
7990       return DiagnoseImpCast(S, E, T, CC,
7991                              diag::warn_impcast_objective_c_literal_to_bool);
7992     }
7993     if (Source->isPointerType() || Source->canDecayToPointerType()) {
7994       // Warn on pointer to bool conversion that is always true.
7995       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
7996                                      SourceRange(CC));
7997     }
7998   }
7999 
8000   // Check implicit casts from Objective-C collection literals to specialized
8001   // collection types, e.g., NSArray<NSString *> *.
8002   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
8003     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
8004   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
8005     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
8006 
8007   // Strip vector types.
8008   if (isa<VectorType>(Source)) {
8009     if (!isa<VectorType>(Target)) {
8010       if (S.SourceMgr.isInSystemMacro(CC))
8011         return;
8012       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
8013     }
8014 
8015     // If the vector cast is cast between two vectors of the same size, it is
8016     // a bitcast, not a conversion.
8017     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
8018       return;
8019 
8020     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
8021     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
8022   }
8023   if (auto VecTy = dyn_cast<VectorType>(Target))
8024     Target = VecTy->getElementType().getTypePtr();
8025 
8026   // Strip complex types.
8027   if (isa<ComplexType>(Source)) {
8028     if (!isa<ComplexType>(Target)) {
8029       if (S.SourceMgr.isInSystemMacro(CC))
8030         return;
8031 
8032       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
8033     }
8034 
8035     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
8036     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
8037   }
8038 
8039   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
8040   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
8041 
8042   // If the source is floating point...
8043   if (SourceBT && SourceBT->isFloatingPoint()) {
8044     // ...and the target is floating point...
8045     if (TargetBT && TargetBT->isFloatingPoint()) {
8046       // ...then warn if we're dropping FP rank.
8047 
8048       // Builtin FP kinds are ordered by increasing FP rank.
8049       if (SourceBT->getKind() > TargetBT->getKind()) {
8050         // Don't warn about float constants that are precisely
8051         // representable in the target type.
8052         Expr::EvalResult result;
8053         if (E->EvaluateAsRValue(result, S.Context)) {
8054           // Value might be a float, a float vector, or a float complex.
8055           if (IsSameFloatAfterCast(result.Val,
8056                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
8057                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
8058             return;
8059         }
8060 
8061         if (S.SourceMgr.isInSystemMacro(CC))
8062           return;
8063 
8064         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
8065       }
8066       // ... or possibly if we're increasing rank, too
8067       else if (TargetBT->getKind() > SourceBT->getKind()) {
8068         if (S.SourceMgr.isInSystemMacro(CC))
8069           return;
8070 
8071         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
8072       }
8073       return;
8074     }
8075 
8076     // If the target is integral, always warn.
8077     if (TargetBT && TargetBT->isInteger()) {
8078       if (S.SourceMgr.isInSystemMacro(CC))
8079         return;
8080 
8081       DiagnoseFloatingImpCast(S, E, T, CC);
8082     }
8083 
8084     // Detect the case where a call result is converted from floating-point to
8085     // to bool, and the final argument to the call is converted from bool, to
8086     // discover this typo:
8087     //
8088     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
8089     //
8090     // FIXME: This is an incredibly special case; is there some more general
8091     // way to detect this class of misplaced-parentheses bug?
8092     if (Target->isBooleanType() && isa<CallExpr>(E)) {
8093       // Check last argument of function call to see if it is an
8094       // implicit cast from a type matching the type the result
8095       // is being cast to.
8096       CallExpr *CEx = cast<CallExpr>(E);
8097       if (unsigned NumArgs = CEx->getNumArgs()) {
8098         Expr *LastA = CEx->getArg(NumArgs - 1);
8099         Expr *InnerE = LastA->IgnoreParenImpCasts();
8100         if (isa<ImplicitCastExpr>(LastA) &&
8101             InnerE->getType()->isBooleanType()) {
8102           // Warn on this floating-point to bool conversion
8103           DiagnoseImpCast(S, E, T, CC,
8104                           diag::warn_impcast_floating_point_to_bool);
8105         }
8106       }
8107     }
8108     return;
8109   }
8110 
8111   DiagnoseNullConversion(S, E, T, CC);
8112 
8113   if (!Source->isIntegerType() || !Target->isIntegerType())
8114     return;
8115 
8116   // TODO: remove this early return once the false positives for constant->bool
8117   // in templates, macros, etc, are reduced or removed.
8118   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
8119     return;
8120 
8121   IntRange SourceRange = GetExprRange(S.Context, E);
8122   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
8123 
8124   if (SourceRange.Width > TargetRange.Width) {
8125     // If the source is a constant, use a default-on diagnostic.
8126     // TODO: this should happen for bitfield stores, too.
8127     llvm::APSInt Value(32);
8128     if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
8129       if (S.SourceMgr.isInSystemMacro(CC))
8130         return;
8131 
8132       std::string PrettySourceValue = Value.toString(10);
8133       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
8134 
8135       S.DiagRuntimeBehavior(E->getExprLoc(), E,
8136         S.PDiag(diag::warn_impcast_integer_precision_constant)
8137             << PrettySourceValue << PrettyTargetValue
8138             << E->getType() << T << E->getSourceRange()
8139             << clang::SourceRange(CC));
8140       return;
8141     }
8142 
8143     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
8144     if (S.SourceMgr.isInSystemMacro(CC))
8145       return;
8146 
8147     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
8148       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
8149                              /* pruneControlFlow */ true);
8150     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
8151   }
8152 
8153   if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
8154       SourceRange.NonNegative && Source->isSignedIntegerType()) {
8155     // Warn when doing a signed to signed conversion, warn if the positive
8156     // source value is exactly the width of the target type, which will
8157     // cause a negative value to be stored.
8158 
8159     llvm::APSInt Value;
8160     if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
8161         !S.SourceMgr.isInSystemMacro(CC)) {
8162       if (isSameWidthConstantConversion(S, E, T, CC)) {
8163         std::string PrettySourceValue = Value.toString(10);
8164         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
8165 
8166         S.DiagRuntimeBehavior(
8167             E->getExprLoc(), E,
8168             S.PDiag(diag::warn_impcast_integer_precision_constant)
8169                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
8170                 << E->getSourceRange() << clang::SourceRange(CC));
8171         return;
8172       }
8173     }
8174 
8175     // Fall through for non-constants to give a sign conversion warning.
8176   }
8177 
8178   if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
8179       (!TargetRange.NonNegative && SourceRange.NonNegative &&
8180        SourceRange.Width == TargetRange.Width)) {
8181     if (S.SourceMgr.isInSystemMacro(CC))
8182       return;
8183 
8184     unsigned DiagID = diag::warn_impcast_integer_sign;
8185 
8186     // Traditionally, gcc has warned about this under -Wsign-compare.
8187     // We also want to warn about it in -Wconversion.
8188     // So if -Wconversion is off, use a completely identical diagnostic
8189     // in the sign-compare group.
8190     // The conditional-checking code will
8191     if (ICContext) {
8192       DiagID = diag::warn_impcast_integer_sign_conditional;
8193       *ICContext = true;
8194     }
8195 
8196     return DiagnoseImpCast(S, E, T, CC, DiagID);
8197   }
8198 
8199   // Diagnose conversions between different enumeration types.
8200   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
8201   // type, to give us better diagnostics.
8202   QualType SourceType = E->getType();
8203   if (!S.getLangOpts().CPlusPlus) {
8204     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
8205       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
8206         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
8207         SourceType = S.Context.getTypeDeclType(Enum);
8208         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
8209       }
8210   }
8211 
8212   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
8213     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
8214       if (SourceEnum->getDecl()->hasNameForLinkage() &&
8215           TargetEnum->getDecl()->hasNameForLinkage() &&
8216           SourceEnum != TargetEnum) {
8217         if (S.SourceMgr.isInSystemMacro(CC))
8218           return;
8219 
8220         return DiagnoseImpCast(S, E, SourceType, T, CC,
8221                                diag::warn_impcast_different_enum_types);
8222       }
8223 }
8224 
8225 void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
8226                               SourceLocation CC, QualType T);
8227 
8228 void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
8229                              SourceLocation CC, bool &ICContext) {
8230   E = E->IgnoreParenImpCasts();
8231 
8232   if (isa<ConditionalOperator>(E))
8233     return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
8234 
8235   AnalyzeImplicitConversions(S, E, CC);
8236   if (E->getType() != T)
8237     return CheckImplicitConversion(S, E, T, CC, &ICContext);
8238 }
8239 
8240 void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
8241                               SourceLocation CC, QualType T) {
8242   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
8243 
8244   bool Suspicious = false;
8245   CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
8246   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
8247 
8248   // If -Wconversion would have warned about either of the candidates
8249   // for a signedness conversion to the context type...
8250   if (!Suspicious) return;
8251 
8252   // ...but it's currently ignored...
8253   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
8254     return;
8255 
8256   // ...then check whether it would have warned about either of the
8257   // candidates for a signedness conversion to the condition type.
8258   if (E->getType() == T) return;
8259 
8260   Suspicious = false;
8261   CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
8262                           E->getType(), CC, &Suspicious);
8263   if (!Suspicious)
8264     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
8265                             E->getType(), CC, &Suspicious);
8266 }
8267 
8268 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
8269 /// Input argument E is a logical expression.
8270 void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
8271   if (S.getLangOpts().Bool)
8272     return;
8273   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
8274 }
8275 
8276 /// AnalyzeImplicitConversions - Find and report any interesting
8277 /// implicit conversions in the given expression.  There are a couple
8278 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
8279 void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
8280   QualType T = OrigE->getType();
8281   Expr *E = OrigE->IgnoreParenImpCasts();
8282 
8283   if (E->isTypeDependent() || E->isValueDependent())
8284     return;
8285 
8286   // For conditional operators, we analyze the arguments as if they
8287   // were being fed directly into the output.
8288   if (isa<ConditionalOperator>(E)) {
8289     ConditionalOperator *CO = cast<ConditionalOperator>(E);
8290     CheckConditionalOperator(S, CO, CC, T);
8291     return;
8292   }
8293 
8294   // Check implicit argument conversions for function calls.
8295   if (CallExpr *Call = dyn_cast<CallExpr>(E))
8296     CheckImplicitArgumentConversions(S, Call, CC);
8297 
8298   // Go ahead and check any implicit conversions we might have skipped.
8299   // The non-canonical typecheck is just an optimization;
8300   // CheckImplicitConversion will filter out dead implicit conversions.
8301   if (E->getType() != T)
8302     CheckImplicitConversion(S, E, T, CC);
8303 
8304   // Now continue drilling into this expression.
8305 
8306   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
8307     // The bound subexpressions in a PseudoObjectExpr are not reachable
8308     // as transitive children.
8309     // FIXME: Use a more uniform representation for this.
8310     for (auto *SE : POE->semantics())
8311       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
8312         AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
8313   }
8314 
8315   // Skip past explicit casts.
8316   if (isa<ExplicitCastExpr>(E)) {
8317     E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
8318     return AnalyzeImplicitConversions(S, E, CC);
8319   }
8320 
8321   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
8322     // Do a somewhat different check with comparison operators.
8323     if (BO->isComparisonOp())
8324       return AnalyzeComparison(S, BO);
8325 
8326     // And with simple assignments.
8327     if (BO->getOpcode() == BO_Assign)
8328       return AnalyzeAssignment(S, BO);
8329   }
8330 
8331   // These break the otherwise-useful invariant below.  Fortunately,
8332   // we don't really need to recurse into them, because any internal
8333   // expressions should have been analyzed already when they were
8334   // built into statements.
8335   if (isa<StmtExpr>(E)) return;
8336 
8337   // Don't descend into unevaluated contexts.
8338   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
8339 
8340   // Now just recurse over the expression's children.
8341   CC = E->getExprLoc();
8342   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
8343   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
8344   for (Stmt *SubStmt : E->children()) {
8345     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
8346     if (!ChildExpr)
8347       continue;
8348 
8349     if (IsLogicalAndOperator &&
8350         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
8351       // Ignore checking string literals that are in logical and operators.
8352       // This is a common pattern for asserts.
8353       continue;
8354     AnalyzeImplicitConversions(S, ChildExpr, CC);
8355   }
8356 
8357   if (BO && BO->isLogicalOp()) {
8358     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
8359     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
8360       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
8361 
8362     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
8363     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
8364       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
8365   }
8366 
8367   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
8368     if (U->getOpcode() == UO_LNot)
8369       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
8370 }
8371 
8372 } // end anonymous namespace
8373 
8374 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
8375 // Returns true when emitting a warning about taking the address of a reference.
8376 static bool CheckForReference(Sema &SemaRef, const Expr *E,
8377                               PartialDiagnostic PD) {
8378   E = E->IgnoreParenImpCasts();
8379 
8380   const FunctionDecl *FD = nullptr;
8381 
8382   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
8383     if (!DRE->getDecl()->getType()->isReferenceType())
8384       return false;
8385   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
8386     if (!M->getMemberDecl()->getType()->isReferenceType())
8387       return false;
8388   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
8389     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
8390       return false;
8391     FD = Call->getDirectCallee();
8392   } else {
8393     return false;
8394   }
8395 
8396   SemaRef.Diag(E->getExprLoc(), PD);
8397 
8398   // If possible, point to location of function.
8399   if (FD) {
8400     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
8401   }
8402 
8403   return true;
8404 }
8405 
8406 // Returns true if the SourceLocation is expanded from any macro body.
8407 // Returns false if the SourceLocation is invalid, is from not in a macro
8408 // expansion, or is from expanded from a top-level macro argument.
8409 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
8410   if (Loc.isInvalid())
8411     return false;
8412 
8413   while (Loc.isMacroID()) {
8414     if (SM.isMacroBodyExpansion(Loc))
8415       return true;
8416     Loc = SM.getImmediateMacroCallerLoc(Loc);
8417   }
8418 
8419   return false;
8420 }
8421 
8422 /// \brief Diagnose pointers that are always non-null.
8423 /// \param E the expression containing the pointer
8424 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
8425 /// compared to a null pointer
8426 /// \param IsEqual True when the comparison is equal to a null pointer
8427 /// \param Range Extra SourceRange to highlight in the diagnostic
8428 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
8429                                         Expr::NullPointerConstantKind NullKind,
8430                                         bool IsEqual, SourceRange Range) {
8431   if (!E)
8432     return;
8433 
8434   // Don't warn inside macros.
8435   if (E->getExprLoc().isMacroID()) {
8436     const SourceManager &SM = getSourceManager();
8437     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
8438         IsInAnyMacroBody(SM, Range.getBegin()))
8439       return;
8440   }
8441   E = E->IgnoreImpCasts();
8442 
8443   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
8444 
8445   if (isa<CXXThisExpr>(E)) {
8446     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
8447                                 : diag::warn_this_bool_conversion;
8448     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
8449     return;
8450   }
8451 
8452   bool IsAddressOf = false;
8453 
8454   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
8455     if (UO->getOpcode() != UO_AddrOf)
8456       return;
8457     IsAddressOf = true;
8458     E = UO->getSubExpr();
8459   }
8460 
8461   if (IsAddressOf) {
8462     unsigned DiagID = IsCompare
8463                           ? diag::warn_address_of_reference_null_compare
8464                           : diag::warn_address_of_reference_bool_conversion;
8465     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
8466                                          << IsEqual;
8467     if (CheckForReference(*this, E, PD)) {
8468       return;
8469     }
8470   }
8471 
8472   auto ComplainAboutNonnullParamOrCall = [&](bool IsParam) {
8473     std::string Str;
8474     llvm::raw_string_ostream S(Str);
8475     E->printPretty(S, nullptr, getPrintingPolicy());
8476     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
8477                                 : diag::warn_cast_nonnull_to_bool;
8478     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
8479       << E->getSourceRange() << Range << IsEqual;
8480   };
8481 
8482   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
8483   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
8484     if (auto *Callee = Call->getDirectCallee()) {
8485       if (Callee->hasAttr<ReturnsNonNullAttr>()) {
8486         ComplainAboutNonnullParamOrCall(false);
8487         return;
8488       }
8489     }
8490   }
8491 
8492   // Expect to find a single Decl.  Skip anything more complicated.
8493   ValueDecl *D = nullptr;
8494   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
8495     D = R->getDecl();
8496   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
8497     D = M->getMemberDecl();
8498   }
8499 
8500   // Weak Decls can be null.
8501   if (!D || D->isWeak())
8502     return;
8503 
8504   // Check for parameter decl with nonnull attribute
8505   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
8506     if (getCurFunction() &&
8507         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
8508       if (PV->hasAttr<NonNullAttr>()) {
8509         ComplainAboutNonnullParamOrCall(true);
8510         return;
8511       }
8512 
8513       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
8514         auto ParamIter = std::find(FD->param_begin(), FD->param_end(), PV);
8515         assert(ParamIter != FD->param_end());
8516         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
8517 
8518         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
8519           if (!NonNull->args_size()) {
8520               ComplainAboutNonnullParamOrCall(true);
8521               return;
8522           }
8523 
8524           for (unsigned ArgNo : NonNull->args()) {
8525             if (ArgNo == ParamNo) {
8526               ComplainAboutNonnullParamOrCall(true);
8527               return;
8528             }
8529           }
8530         }
8531       }
8532     }
8533   }
8534 
8535   QualType T = D->getType();
8536   const bool IsArray = T->isArrayType();
8537   const bool IsFunction = T->isFunctionType();
8538 
8539   // Address of function is used to silence the function warning.
8540   if (IsAddressOf && IsFunction) {
8541     return;
8542   }
8543 
8544   // Found nothing.
8545   if (!IsAddressOf && !IsFunction && !IsArray)
8546     return;
8547 
8548   // Pretty print the expression for the diagnostic.
8549   std::string Str;
8550   llvm::raw_string_ostream S(Str);
8551   E->printPretty(S, nullptr, getPrintingPolicy());
8552 
8553   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
8554                               : diag::warn_impcast_pointer_to_bool;
8555   enum {
8556     AddressOf,
8557     FunctionPointer,
8558     ArrayPointer
8559   } DiagType;
8560   if (IsAddressOf)
8561     DiagType = AddressOf;
8562   else if (IsFunction)
8563     DiagType = FunctionPointer;
8564   else if (IsArray)
8565     DiagType = ArrayPointer;
8566   else
8567     llvm_unreachable("Could not determine diagnostic.");
8568   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
8569                                 << Range << IsEqual;
8570 
8571   if (!IsFunction)
8572     return;
8573 
8574   // Suggest '&' to silence the function warning.
8575   Diag(E->getExprLoc(), diag::note_function_warning_silence)
8576       << FixItHint::CreateInsertion(E->getLocStart(), "&");
8577 
8578   // Check to see if '()' fixit should be emitted.
8579   QualType ReturnType;
8580   UnresolvedSet<4> NonTemplateOverloads;
8581   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
8582   if (ReturnType.isNull())
8583     return;
8584 
8585   if (IsCompare) {
8586     // There are two cases here.  If there is null constant, the only suggest
8587     // for a pointer return type.  If the null is 0, then suggest if the return
8588     // type is a pointer or an integer type.
8589     if (!ReturnType->isPointerType()) {
8590       if (NullKind == Expr::NPCK_ZeroExpression ||
8591           NullKind == Expr::NPCK_ZeroLiteral) {
8592         if (!ReturnType->isIntegerType())
8593           return;
8594       } else {
8595         return;
8596       }
8597     }
8598   } else { // !IsCompare
8599     // For function to bool, only suggest if the function pointer has bool
8600     // return type.
8601     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
8602       return;
8603   }
8604   Diag(E->getExprLoc(), diag::note_function_to_function_call)
8605       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
8606 }
8607 
8608 /// Diagnoses "dangerous" implicit conversions within the given
8609 /// expression (which is a full expression).  Implements -Wconversion
8610 /// and -Wsign-compare.
8611 ///
8612 /// \param CC the "context" location of the implicit conversion, i.e.
8613 ///   the most location of the syntactic entity requiring the implicit
8614 ///   conversion
8615 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
8616   // Don't diagnose in unevaluated contexts.
8617   if (isUnevaluatedContext())
8618     return;
8619 
8620   // Don't diagnose for value- or type-dependent expressions.
8621   if (E->isTypeDependent() || E->isValueDependent())
8622     return;
8623 
8624   // Check for array bounds violations in cases where the check isn't triggered
8625   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
8626   // ArraySubscriptExpr is on the RHS of a variable initialization.
8627   CheckArrayAccess(E);
8628 
8629   // This is not the right CC for (e.g.) a variable initialization.
8630   AnalyzeImplicitConversions(*this, E, CC);
8631 }
8632 
8633 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
8634 /// Input argument E is a logical expression.
8635 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
8636   ::CheckBoolLikeConversion(*this, E, CC);
8637 }
8638 
8639 /// Diagnose when expression is an integer constant expression and its evaluation
8640 /// results in integer overflow
8641 void Sema::CheckForIntOverflow (Expr *E) {
8642   // Use a work list to deal with nested struct initializers.
8643   SmallVector<Expr *, 2> Exprs(1, E);
8644 
8645   do {
8646     Expr *E = Exprs.pop_back_val();
8647 
8648     if (isa<BinaryOperator>(E->IgnoreParenCasts())) {
8649       E->IgnoreParenCasts()->EvaluateForOverflow(Context);
8650       continue;
8651     }
8652 
8653     if (auto InitList = dyn_cast<InitListExpr>(E))
8654       Exprs.append(InitList->inits().begin(), InitList->inits().end());
8655   } while (!Exprs.empty());
8656 }
8657 
8658 namespace {
8659 /// \brief Visitor for expressions which looks for unsequenced operations on the
8660 /// same object.
8661 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
8662   typedef EvaluatedExprVisitor<SequenceChecker> Base;
8663 
8664   /// \brief A tree of sequenced regions within an expression. Two regions are
8665   /// unsequenced if one is an ancestor or a descendent of the other. When we
8666   /// finish processing an expression with sequencing, such as a comma
8667   /// expression, we fold its tree nodes into its parent, since they are
8668   /// unsequenced with respect to nodes we will visit later.
8669   class SequenceTree {
8670     struct Value {
8671       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
8672       unsigned Parent : 31;
8673       bool Merged : 1;
8674     };
8675     SmallVector<Value, 8> Values;
8676 
8677   public:
8678     /// \brief A region within an expression which may be sequenced with respect
8679     /// to some other region.
8680     class Seq {
8681       explicit Seq(unsigned N) : Index(N) {}
8682       unsigned Index;
8683       friend class SequenceTree;
8684     public:
8685       Seq() : Index(0) {}
8686     };
8687 
8688     SequenceTree() { Values.push_back(Value(0)); }
8689     Seq root() const { return Seq(0); }
8690 
8691     /// \brief Create a new sequence of operations, which is an unsequenced
8692     /// subset of \p Parent. This sequence of operations is sequenced with
8693     /// respect to other children of \p Parent.
8694     Seq allocate(Seq Parent) {
8695       Values.push_back(Value(Parent.Index));
8696       return Seq(Values.size() - 1);
8697     }
8698 
8699     /// \brief Merge a sequence of operations into its parent.
8700     void merge(Seq S) {
8701       Values[S.Index].Merged = true;
8702     }
8703 
8704     /// \brief Determine whether two operations are unsequenced. This operation
8705     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
8706     /// should have been merged into its parent as appropriate.
8707     bool isUnsequenced(Seq Cur, Seq Old) {
8708       unsigned C = representative(Cur.Index);
8709       unsigned Target = representative(Old.Index);
8710       while (C >= Target) {
8711         if (C == Target)
8712           return true;
8713         C = Values[C].Parent;
8714       }
8715       return false;
8716     }
8717 
8718   private:
8719     /// \brief Pick a representative for a sequence.
8720     unsigned representative(unsigned K) {
8721       if (Values[K].Merged)
8722         // Perform path compression as we go.
8723         return Values[K].Parent = representative(Values[K].Parent);
8724       return K;
8725     }
8726   };
8727 
8728   /// An object for which we can track unsequenced uses.
8729   typedef NamedDecl *Object;
8730 
8731   /// Different flavors of object usage which we track. We only track the
8732   /// least-sequenced usage of each kind.
8733   enum UsageKind {
8734     /// A read of an object. Multiple unsequenced reads are OK.
8735     UK_Use,
8736     /// A modification of an object which is sequenced before the value
8737     /// computation of the expression, such as ++n in C++.
8738     UK_ModAsValue,
8739     /// A modification of an object which is not sequenced before the value
8740     /// computation of the expression, such as n++.
8741     UK_ModAsSideEffect,
8742 
8743     UK_Count = UK_ModAsSideEffect + 1
8744   };
8745 
8746   struct Usage {
8747     Usage() : Use(nullptr), Seq() {}
8748     Expr *Use;
8749     SequenceTree::Seq Seq;
8750   };
8751 
8752   struct UsageInfo {
8753     UsageInfo() : Diagnosed(false) {}
8754     Usage Uses[UK_Count];
8755     /// Have we issued a diagnostic for this variable already?
8756     bool Diagnosed;
8757   };
8758   typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
8759 
8760   Sema &SemaRef;
8761   /// Sequenced regions within the expression.
8762   SequenceTree Tree;
8763   /// Declaration modifications and references which we have seen.
8764   UsageInfoMap UsageMap;
8765   /// The region we are currently within.
8766   SequenceTree::Seq Region;
8767   /// Filled in with declarations which were modified as a side-effect
8768   /// (that is, post-increment operations).
8769   SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
8770   /// Expressions to check later. We defer checking these to reduce
8771   /// stack usage.
8772   SmallVectorImpl<Expr *> &WorkList;
8773 
8774   /// RAII object wrapping the visitation of a sequenced subexpression of an
8775   /// expression. At the end of this process, the side-effects of the evaluation
8776   /// become sequenced with respect to the value computation of the result, so
8777   /// we downgrade any UK_ModAsSideEffect within the evaluation to
8778   /// UK_ModAsValue.
8779   struct SequencedSubexpression {
8780     SequencedSubexpression(SequenceChecker &Self)
8781       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
8782       Self.ModAsSideEffect = &ModAsSideEffect;
8783     }
8784     ~SequencedSubexpression() {
8785       for (auto MI = ModAsSideEffect.rbegin(), ME = ModAsSideEffect.rend();
8786            MI != ME; ++MI) {
8787         UsageInfo &U = Self.UsageMap[MI->first];
8788         auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
8789         Self.addUsage(U, MI->first, SideEffectUsage.Use, UK_ModAsValue);
8790         SideEffectUsage = MI->second;
8791       }
8792       Self.ModAsSideEffect = OldModAsSideEffect;
8793     }
8794 
8795     SequenceChecker &Self;
8796     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
8797     SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
8798   };
8799 
8800   /// RAII object wrapping the visitation of a subexpression which we might
8801   /// choose to evaluate as a constant. If any subexpression is evaluated and
8802   /// found to be non-constant, this allows us to suppress the evaluation of
8803   /// the outer expression.
8804   class EvaluationTracker {
8805   public:
8806     EvaluationTracker(SequenceChecker &Self)
8807         : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
8808       Self.EvalTracker = this;
8809     }
8810     ~EvaluationTracker() {
8811       Self.EvalTracker = Prev;
8812       if (Prev)
8813         Prev->EvalOK &= EvalOK;
8814     }
8815 
8816     bool evaluate(const Expr *E, bool &Result) {
8817       if (!EvalOK || E->isValueDependent())
8818         return false;
8819       EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
8820       return EvalOK;
8821     }
8822 
8823   private:
8824     SequenceChecker &Self;
8825     EvaluationTracker *Prev;
8826     bool EvalOK;
8827   } *EvalTracker;
8828 
8829   /// \brief Find the object which is produced by the specified expression,
8830   /// if any.
8831   Object getObject(Expr *E, bool Mod) const {
8832     E = E->IgnoreParenCasts();
8833     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
8834       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
8835         return getObject(UO->getSubExpr(), Mod);
8836     } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
8837       if (BO->getOpcode() == BO_Comma)
8838         return getObject(BO->getRHS(), Mod);
8839       if (Mod && BO->isAssignmentOp())
8840         return getObject(BO->getLHS(), Mod);
8841     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
8842       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
8843       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
8844         return ME->getMemberDecl();
8845     } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
8846       // FIXME: If this is a reference, map through to its value.
8847       return DRE->getDecl();
8848     return nullptr;
8849   }
8850 
8851   /// \brief Note that an object was modified or used by an expression.
8852   void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
8853     Usage &U = UI.Uses[UK];
8854     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
8855       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
8856         ModAsSideEffect->push_back(std::make_pair(O, U));
8857       U.Use = Ref;
8858       U.Seq = Region;
8859     }
8860   }
8861   /// \brief Check whether a modification or use conflicts with a prior usage.
8862   void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
8863                   bool IsModMod) {
8864     if (UI.Diagnosed)
8865       return;
8866 
8867     const Usage &U = UI.Uses[OtherKind];
8868     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
8869       return;
8870 
8871     Expr *Mod = U.Use;
8872     Expr *ModOrUse = Ref;
8873     if (OtherKind == UK_Use)
8874       std::swap(Mod, ModOrUse);
8875 
8876     SemaRef.Diag(Mod->getExprLoc(),
8877                  IsModMod ? diag::warn_unsequenced_mod_mod
8878                           : diag::warn_unsequenced_mod_use)
8879       << O << SourceRange(ModOrUse->getExprLoc());
8880     UI.Diagnosed = true;
8881   }
8882 
8883   void notePreUse(Object O, Expr *Use) {
8884     UsageInfo &U = UsageMap[O];
8885     // Uses conflict with other modifications.
8886     checkUsage(O, U, Use, UK_ModAsValue, false);
8887   }
8888   void notePostUse(Object O, Expr *Use) {
8889     UsageInfo &U = UsageMap[O];
8890     checkUsage(O, U, Use, UK_ModAsSideEffect, false);
8891     addUsage(U, O, Use, UK_Use);
8892   }
8893 
8894   void notePreMod(Object O, Expr *Mod) {
8895     UsageInfo &U = UsageMap[O];
8896     // Modifications conflict with other modifications and with uses.
8897     checkUsage(O, U, Mod, UK_ModAsValue, true);
8898     checkUsage(O, U, Mod, UK_Use, false);
8899   }
8900   void notePostMod(Object O, Expr *Use, UsageKind UK) {
8901     UsageInfo &U = UsageMap[O];
8902     checkUsage(O, U, Use, UK_ModAsSideEffect, true);
8903     addUsage(U, O, Use, UK);
8904   }
8905 
8906 public:
8907   SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
8908       : Base(S.Context), SemaRef(S), Region(Tree.root()),
8909         ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
8910     Visit(E);
8911   }
8912 
8913   void VisitStmt(Stmt *S) {
8914     // Skip all statements which aren't expressions for now.
8915   }
8916 
8917   void VisitExpr(Expr *E) {
8918     // By default, just recurse to evaluated subexpressions.
8919     Base::VisitStmt(E);
8920   }
8921 
8922   void VisitCastExpr(CastExpr *E) {
8923     Object O = Object();
8924     if (E->getCastKind() == CK_LValueToRValue)
8925       O = getObject(E->getSubExpr(), false);
8926 
8927     if (O)
8928       notePreUse(O, E);
8929     VisitExpr(E);
8930     if (O)
8931       notePostUse(O, E);
8932   }
8933 
8934   void VisitBinComma(BinaryOperator *BO) {
8935     // C++11 [expr.comma]p1:
8936     //   Every value computation and side effect associated with the left
8937     //   expression is sequenced before every value computation and side
8938     //   effect associated with the right expression.
8939     SequenceTree::Seq LHS = Tree.allocate(Region);
8940     SequenceTree::Seq RHS = Tree.allocate(Region);
8941     SequenceTree::Seq OldRegion = Region;
8942 
8943     {
8944       SequencedSubexpression SeqLHS(*this);
8945       Region = LHS;
8946       Visit(BO->getLHS());
8947     }
8948 
8949     Region = RHS;
8950     Visit(BO->getRHS());
8951 
8952     Region = OldRegion;
8953 
8954     // Forget that LHS and RHS are sequenced. They are both unsequenced
8955     // with respect to other stuff.
8956     Tree.merge(LHS);
8957     Tree.merge(RHS);
8958   }
8959 
8960   void VisitBinAssign(BinaryOperator *BO) {
8961     // The modification is sequenced after the value computation of the LHS
8962     // and RHS, so check it before inspecting the operands and update the
8963     // map afterwards.
8964     Object O = getObject(BO->getLHS(), true);
8965     if (!O)
8966       return VisitExpr(BO);
8967 
8968     notePreMod(O, BO);
8969 
8970     // C++11 [expr.ass]p7:
8971     //   E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
8972     //   only once.
8973     //
8974     // Therefore, for a compound assignment operator, O is considered used
8975     // everywhere except within the evaluation of E1 itself.
8976     if (isa<CompoundAssignOperator>(BO))
8977       notePreUse(O, BO);
8978 
8979     Visit(BO->getLHS());
8980 
8981     if (isa<CompoundAssignOperator>(BO))
8982       notePostUse(O, BO);
8983 
8984     Visit(BO->getRHS());
8985 
8986     // C++11 [expr.ass]p1:
8987     //   the assignment is sequenced [...] before the value computation of the
8988     //   assignment expression.
8989     // C11 6.5.16/3 has no such rule.
8990     notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
8991                                                        : UK_ModAsSideEffect);
8992   }
8993 
8994   void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
8995     VisitBinAssign(CAO);
8996   }
8997 
8998   void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
8999   void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
9000   void VisitUnaryPreIncDec(UnaryOperator *UO) {
9001     Object O = getObject(UO->getSubExpr(), true);
9002     if (!O)
9003       return VisitExpr(UO);
9004 
9005     notePreMod(O, UO);
9006     Visit(UO->getSubExpr());
9007     // C++11 [expr.pre.incr]p1:
9008     //   the expression ++x is equivalent to x+=1
9009     notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
9010                                                        : UK_ModAsSideEffect);
9011   }
9012 
9013   void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
9014   void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
9015   void VisitUnaryPostIncDec(UnaryOperator *UO) {
9016     Object O = getObject(UO->getSubExpr(), true);
9017     if (!O)
9018       return VisitExpr(UO);
9019 
9020     notePreMod(O, UO);
9021     Visit(UO->getSubExpr());
9022     notePostMod(O, UO, UK_ModAsSideEffect);
9023   }
9024 
9025   /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
9026   void VisitBinLOr(BinaryOperator *BO) {
9027     // The side-effects of the LHS of an '&&' are sequenced before the
9028     // value computation of the RHS, and hence before the value computation
9029     // of the '&&' itself, unless the LHS evaluates to zero. We treat them
9030     // as if they were unconditionally sequenced.
9031     EvaluationTracker Eval(*this);
9032     {
9033       SequencedSubexpression Sequenced(*this);
9034       Visit(BO->getLHS());
9035     }
9036 
9037     bool Result;
9038     if (Eval.evaluate(BO->getLHS(), Result)) {
9039       if (!Result)
9040         Visit(BO->getRHS());
9041     } else {
9042       // Check for unsequenced operations in the RHS, treating it as an
9043       // entirely separate evaluation.
9044       //
9045       // FIXME: If there are operations in the RHS which are unsequenced
9046       // with respect to operations outside the RHS, and those operations
9047       // are unconditionally evaluated, diagnose them.
9048       WorkList.push_back(BO->getRHS());
9049     }
9050   }
9051   void VisitBinLAnd(BinaryOperator *BO) {
9052     EvaluationTracker Eval(*this);
9053     {
9054       SequencedSubexpression Sequenced(*this);
9055       Visit(BO->getLHS());
9056     }
9057 
9058     bool Result;
9059     if (Eval.evaluate(BO->getLHS(), Result)) {
9060       if (Result)
9061         Visit(BO->getRHS());
9062     } else {
9063       WorkList.push_back(BO->getRHS());
9064     }
9065   }
9066 
9067   // Only visit the condition, unless we can be sure which subexpression will
9068   // be chosen.
9069   void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
9070     EvaluationTracker Eval(*this);
9071     {
9072       SequencedSubexpression Sequenced(*this);
9073       Visit(CO->getCond());
9074     }
9075 
9076     bool Result;
9077     if (Eval.evaluate(CO->getCond(), Result))
9078       Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
9079     else {
9080       WorkList.push_back(CO->getTrueExpr());
9081       WorkList.push_back(CO->getFalseExpr());
9082     }
9083   }
9084 
9085   void VisitCallExpr(CallExpr *CE) {
9086     // C++11 [intro.execution]p15:
9087     //   When calling a function [...], every value computation and side effect
9088     //   associated with any argument expression, or with the postfix expression
9089     //   designating the called function, is sequenced before execution of every
9090     //   expression or statement in the body of the function [and thus before
9091     //   the value computation of its result].
9092     SequencedSubexpression Sequenced(*this);
9093     Base::VisitCallExpr(CE);
9094 
9095     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
9096   }
9097 
9098   void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
9099     // This is a call, so all subexpressions are sequenced before the result.
9100     SequencedSubexpression Sequenced(*this);
9101 
9102     if (!CCE->isListInitialization())
9103       return VisitExpr(CCE);
9104 
9105     // In C++11, list initializations are sequenced.
9106     SmallVector<SequenceTree::Seq, 32> Elts;
9107     SequenceTree::Seq Parent = Region;
9108     for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
9109                                         E = CCE->arg_end();
9110          I != E; ++I) {
9111       Region = Tree.allocate(Parent);
9112       Elts.push_back(Region);
9113       Visit(*I);
9114     }
9115 
9116     // Forget that the initializers are sequenced.
9117     Region = Parent;
9118     for (unsigned I = 0; I < Elts.size(); ++I)
9119       Tree.merge(Elts[I]);
9120   }
9121 
9122   void VisitInitListExpr(InitListExpr *ILE) {
9123     if (!SemaRef.getLangOpts().CPlusPlus11)
9124       return VisitExpr(ILE);
9125 
9126     // In C++11, list initializations are sequenced.
9127     SmallVector<SequenceTree::Seq, 32> Elts;
9128     SequenceTree::Seq Parent = Region;
9129     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
9130       Expr *E = ILE->getInit(I);
9131       if (!E) continue;
9132       Region = Tree.allocate(Parent);
9133       Elts.push_back(Region);
9134       Visit(E);
9135     }
9136 
9137     // Forget that the initializers are sequenced.
9138     Region = Parent;
9139     for (unsigned I = 0; I < Elts.size(); ++I)
9140       Tree.merge(Elts[I]);
9141   }
9142 };
9143 } // end anonymous namespace
9144 
9145 void Sema::CheckUnsequencedOperations(Expr *E) {
9146   SmallVector<Expr *, 8> WorkList;
9147   WorkList.push_back(E);
9148   while (!WorkList.empty()) {
9149     Expr *Item = WorkList.pop_back_val();
9150     SequenceChecker(*this, Item, WorkList);
9151   }
9152 }
9153 
9154 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
9155                               bool IsConstexpr) {
9156   CheckImplicitConversions(E, CheckLoc);
9157   CheckUnsequencedOperations(E);
9158   if (!IsConstexpr && !E->isValueDependent())
9159     CheckForIntOverflow(E);
9160 }
9161 
9162 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
9163                                        FieldDecl *BitField,
9164                                        Expr *Init) {
9165   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
9166 }
9167 
9168 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
9169                                          SourceLocation Loc) {
9170   if (!PType->isVariablyModifiedType())
9171     return;
9172   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
9173     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
9174     return;
9175   }
9176   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
9177     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
9178     return;
9179   }
9180   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
9181     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
9182     return;
9183   }
9184 
9185   const ArrayType *AT = S.Context.getAsArrayType(PType);
9186   if (!AT)
9187     return;
9188 
9189   if (AT->getSizeModifier() != ArrayType::Star) {
9190     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
9191     return;
9192   }
9193 
9194   S.Diag(Loc, diag::err_array_star_in_function_definition);
9195 }
9196 
9197 /// CheckParmsForFunctionDef - Check that the parameters of the given
9198 /// function are appropriate for the definition of a function. This
9199 /// takes care of any checks that cannot be performed on the
9200 /// declaration itself, e.g., that the types of each of the function
9201 /// parameters are complete.
9202 bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
9203                                     ParmVarDecl *const *PEnd,
9204                                     bool CheckParameterNames) {
9205   bool HasInvalidParm = false;
9206   for (; P != PEnd; ++P) {
9207     ParmVarDecl *Param = *P;
9208 
9209     // C99 6.7.5.3p4: the parameters in a parameter type list in a
9210     // function declarator that is part of a function definition of
9211     // that function shall not have incomplete type.
9212     //
9213     // This is also C++ [dcl.fct]p6.
9214     if (!Param->isInvalidDecl() &&
9215         RequireCompleteType(Param->getLocation(), Param->getType(),
9216                             diag::err_typecheck_decl_incomplete_type)) {
9217       Param->setInvalidDecl();
9218       HasInvalidParm = true;
9219     }
9220 
9221     // C99 6.9.1p5: If the declarator includes a parameter type list, the
9222     // declaration of each parameter shall include an identifier.
9223     if (CheckParameterNames &&
9224         Param->getIdentifier() == nullptr &&
9225         !Param->isImplicit() &&
9226         !getLangOpts().CPlusPlus)
9227       Diag(Param->getLocation(), diag::err_parameter_name_omitted);
9228 
9229     // C99 6.7.5.3p12:
9230     //   If the function declarator is not part of a definition of that
9231     //   function, parameters may have incomplete type and may use the [*]
9232     //   notation in their sequences of declarator specifiers to specify
9233     //   variable length array types.
9234     QualType PType = Param->getOriginalType();
9235     // FIXME: This diagnostic should point the '[*]' if source-location
9236     // information is added for it.
9237     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
9238 
9239     // MSVC destroys objects passed by value in the callee.  Therefore a
9240     // function definition which takes such a parameter must be able to call the
9241     // object's destructor.  However, we don't perform any direct access check
9242     // on the dtor.
9243     if (getLangOpts().CPlusPlus && Context.getTargetInfo()
9244                                        .getCXXABI()
9245                                        .areArgsDestroyedLeftToRightInCallee()) {
9246       if (!Param->isInvalidDecl()) {
9247         if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
9248           CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
9249           if (!ClassDecl->isInvalidDecl() &&
9250               !ClassDecl->hasIrrelevantDestructor() &&
9251               !ClassDecl->isDependentContext()) {
9252             CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
9253             MarkFunctionReferenced(Param->getLocation(), Destructor);
9254             DiagnoseUseOfDecl(Destructor, Param->getLocation());
9255           }
9256         }
9257       }
9258     }
9259 
9260     // Parameters with the pass_object_size attribute only need to be marked
9261     // constant at function definitions. Because we lack information about
9262     // whether we're on a declaration or definition when we're instantiating the
9263     // attribute, we need to check for constness here.
9264     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
9265       if (!Param->getType().isConstQualified())
9266         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
9267             << Attr->getSpelling() << 1;
9268   }
9269 
9270   return HasInvalidParm;
9271 }
9272 
9273 /// CheckCastAlign - Implements -Wcast-align, which warns when a
9274 /// pointer cast increases the alignment requirements.
9275 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
9276   // This is actually a lot of work to potentially be doing on every
9277   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
9278   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
9279     return;
9280 
9281   // Ignore dependent types.
9282   if (T->isDependentType() || Op->getType()->isDependentType())
9283     return;
9284 
9285   // Require that the destination be a pointer type.
9286   const PointerType *DestPtr = T->getAs<PointerType>();
9287   if (!DestPtr) return;
9288 
9289   // If the destination has alignment 1, we're done.
9290   QualType DestPointee = DestPtr->getPointeeType();
9291   if (DestPointee->isIncompleteType()) return;
9292   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
9293   if (DestAlign.isOne()) return;
9294 
9295   // Require that the source be a pointer type.
9296   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
9297   if (!SrcPtr) return;
9298   QualType SrcPointee = SrcPtr->getPointeeType();
9299 
9300   // Whitelist casts from cv void*.  We already implicitly
9301   // whitelisted casts to cv void*, since they have alignment 1.
9302   // Also whitelist casts involving incomplete types, which implicitly
9303   // includes 'void'.
9304   if (SrcPointee->isIncompleteType()) return;
9305 
9306   CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
9307   if (SrcAlign >= DestAlign) return;
9308 
9309   Diag(TRange.getBegin(), diag::warn_cast_align)
9310     << Op->getType() << T
9311     << static_cast<unsigned>(SrcAlign.getQuantity())
9312     << static_cast<unsigned>(DestAlign.getQuantity())
9313     << TRange << Op->getSourceRange();
9314 }
9315 
9316 static const Type* getElementType(const Expr *BaseExpr) {
9317   const Type* EltType = BaseExpr->getType().getTypePtr();
9318   if (EltType->isAnyPointerType())
9319     return EltType->getPointeeType().getTypePtr();
9320   else if (EltType->isArrayType())
9321     return EltType->getBaseElementTypeUnsafe();
9322   return EltType;
9323 }
9324 
9325 /// \brief Check whether this array fits the idiom of a size-one tail padded
9326 /// array member of a struct.
9327 ///
9328 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
9329 /// commonly used to emulate flexible arrays in C89 code.
9330 static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
9331                                     const NamedDecl *ND) {
9332   if (Size != 1 || !ND) return false;
9333 
9334   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
9335   if (!FD) return false;
9336 
9337   // Don't consider sizes resulting from macro expansions or template argument
9338   // substitution to form C89 tail-padded arrays.
9339 
9340   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
9341   while (TInfo) {
9342     TypeLoc TL = TInfo->getTypeLoc();
9343     // Look through typedefs.
9344     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
9345       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
9346       TInfo = TDL->getTypeSourceInfo();
9347       continue;
9348     }
9349     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
9350       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
9351       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
9352         return false;
9353     }
9354     break;
9355   }
9356 
9357   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
9358   if (!RD) return false;
9359   if (RD->isUnion()) return false;
9360   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
9361     if (!CRD->isStandardLayout()) return false;
9362   }
9363 
9364   // See if this is the last field decl in the record.
9365   const Decl *D = FD;
9366   while ((D = D->getNextDeclInContext()))
9367     if (isa<FieldDecl>(D))
9368       return false;
9369   return true;
9370 }
9371 
9372 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
9373                             const ArraySubscriptExpr *ASE,
9374                             bool AllowOnePastEnd, bool IndexNegated) {
9375   IndexExpr = IndexExpr->IgnoreParenImpCasts();
9376   if (IndexExpr->isValueDependent())
9377     return;
9378 
9379   const Type *EffectiveType = getElementType(BaseExpr);
9380   BaseExpr = BaseExpr->IgnoreParenCasts();
9381   const ConstantArrayType *ArrayTy =
9382     Context.getAsConstantArrayType(BaseExpr->getType());
9383   if (!ArrayTy)
9384     return;
9385 
9386   llvm::APSInt index;
9387   if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
9388     return;
9389   if (IndexNegated)
9390     index = -index;
9391 
9392   const NamedDecl *ND = nullptr;
9393   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
9394     ND = dyn_cast<NamedDecl>(DRE->getDecl());
9395   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
9396     ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
9397 
9398   if (index.isUnsigned() || !index.isNegative()) {
9399     llvm::APInt size = ArrayTy->getSize();
9400     if (!size.isStrictlyPositive())
9401       return;
9402 
9403     const Type* BaseType = getElementType(BaseExpr);
9404     if (BaseType != EffectiveType) {
9405       // Make sure we're comparing apples to apples when comparing index to size
9406       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
9407       uint64_t array_typesize = Context.getTypeSize(BaseType);
9408       // Handle ptrarith_typesize being zero, such as when casting to void*
9409       if (!ptrarith_typesize) ptrarith_typesize = 1;
9410       if (ptrarith_typesize != array_typesize) {
9411         // There's a cast to a different size type involved
9412         uint64_t ratio = array_typesize / ptrarith_typesize;
9413         // TODO: Be smarter about handling cases where array_typesize is not a
9414         // multiple of ptrarith_typesize
9415         if (ptrarith_typesize * ratio == array_typesize)
9416           size *= llvm::APInt(size.getBitWidth(), ratio);
9417       }
9418     }
9419 
9420     if (size.getBitWidth() > index.getBitWidth())
9421       index = index.zext(size.getBitWidth());
9422     else if (size.getBitWidth() < index.getBitWidth())
9423       size = size.zext(index.getBitWidth());
9424 
9425     // For array subscripting the index must be less than size, but for pointer
9426     // arithmetic also allow the index (offset) to be equal to size since
9427     // computing the next address after the end of the array is legal and
9428     // commonly done e.g. in C++ iterators and range-based for loops.
9429     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
9430       return;
9431 
9432     // Also don't warn for arrays of size 1 which are members of some
9433     // structure. These are often used to approximate flexible arrays in C89
9434     // code.
9435     if (IsTailPaddedMemberArray(*this, size, ND))
9436       return;
9437 
9438     // Suppress the warning if the subscript expression (as identified by the
9439     // ']' location) and the index expression are both from macro expansions
9440     // within a system header.
9441     if (ASE) {
9442       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
9443           ASE->getRBracketLoc());
9444       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
9445         SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
9446             IndexExpr->getLocStart());
9447         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
9448           return;
9449       }
9450     }
9451 
9452     unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
9453     if (ASE)
9454       DiagID = diag::warn_array_index_exceeds_bounds;
9455 
9456     DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
9457                         PDiag(DiagID) << index.toString(10, true)
9458                           << size.toString(10, true)
9459                           << (unsigned)size.getLimitedValue(~0U)
9460                           << IndexExpr->getSourceRange());
9461   } else {
9462     unsigned DiagID = diag::warn_array_index_precedes_bounds;
9463     if (!ASE) {
9464       DiagID = diag::warn_ptr_arith_precedes_bounds;
9465       if (index.isNegative()) index = -index;
9466     }
9467 
9468     DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
9469                         PDiag(DiagID) << index.toString(10, true)
9470                           << IndexExpr->getSourceRange());
9471   }
9472 
9473   if (!ND) {
9474     // Try harder to find a NamedDecl to point at in the note.
9475     while (const ArraySubscriptExpr *ASE =
9476            dyn_cast<ArraySubscriptExpr>(BaseExpr))
9477       BaseExpr = ASE->getBase()->IgnoreParenCasts();
9478     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
9479       ND = dyn_cast<NamedDecl>(DRE->getDecl());
9480     if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
9481       ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
9482   }
9483 
9484   if (ND)
9485     DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
9486                         PDiag(diag::note_array_index_out_of_bounds)
9487                           << ND->getDeclName());
9488 }
9489 
9490 void Sema::CheckArrayAccess(const Expr *expr) {
9491   int AllowOnePastEnd = 0;
9492   while (expr) {
9493     expr = expr->IgnoreParenImpCasts();
9494     switch (expr->getStmtClass()) {
9495       case Stmt::ArraySubscriptExprClass: {
9496         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
9497         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
9498                          AllowOnePastEnd > 0);
9499         return;
9500       }
9501       case Stmt::OMPArraySectionExprClass: {
9502         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
9503         if (ASE->getLowerBound())
9504           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
9505                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
9506         return;
9507       }
9508       case Stmt::UnaryOperatorClass: {
9509         // Only unwrap the * and & unary operators
9510         const UnaryOperator *UO = cast<UnaryOperator>(expr);
9511         expr = UO->getSubExpr();
9512         switch (UO->getOpcode()) {
9513           case UO_AddrOf:
9514             AllowOnePastEnd++;
9515             break;
9516           case UO_Deref:
9517             AllowOnePastEnd--;
9518             break;
9519           default:
9520             return;
9521         }
9522         break;
9523       }
9524       case Stmt::ConditionalOperatorClass: {
9525         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
9526         if (const Expr *lhs = cond->getLHS())
9527           CheckArrayAccess(lhs);
9528         if (const Expr *rhs = cond->getRHS())
9529           CheckArrayAccess(rhs);
9530         return;
9531       }
9532       default:
9533         return;
9534     }
9535   }
9536 }
9537 
9538 //===--- CHECK: Objective-C retain cycles ----------------------------------//
9539 
9540 namespace {
9541   struct RetainCycleOwner {
9542     RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
9543     VarDecl *Variable;
9544     SourceRange Range;
9545     SourceLocation Loc;
9546     bool Indirect;
9547 
9548     void setLocsFrom(Expr *e) {
9549       Loc = e->getExprLoc();
9550       Range = e->getSourceRange();
9551     }
9552   };
9553 } // end anonymous namespace
9554 
9555 /// Consider whether capturing the given variable can possibly lead to
9556 /// a retain cycle.
9557 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
9558   // In ARC, it's captured strongly iff the variable has __strong
9559   // lifetime.  In MRR, it's captured strongly if the variable is
9560   // __block and has an appropriate type.
9561   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
9562     return false;
9563 
9564   owner.Variable = var;
9565   if (ref)
9566     owner.setLocsFrom(ref);
9567   return true;
9568 }
9569 
9570 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
9571   while (true) {
9572     e = e->IgnoreParens();
9573     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
9574       switch (cast->getCastKind()) {
9575       case CK_BitCast:
9576       case CK_LValueBitCast:
9577       case CK_LValueToRValue:
9578       case CK_ARCReclaimReturnedObject:
9579         e = cast->getSubExpr();
9580         continue;
9581 
9582       default:
9583         return false;
9584       }
9585     }
9586 
9587     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
9588       ObjCIvarDecl *ivar = ref->getDecl();
9589       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
9590         return false;
9591 
9592       // Try to find a retain cycle in the base.
9593       if (!findRetainCycleOwner(S, ref->getBase(), owner))
9594         return false;
9595 
9596       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
9597       owner.Indirect = true;
9598       return true;
9599     }
9600 
9601     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
9602       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
9603       if (!var) return false;
9604       return considerVariable(var, ref, owner);
9605     }
9606 
9607     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
9608       if (member->isArrow()) return false;
9609 
9610       // Don't count this as an indirect ownership.
9611       e = member->getBase();
9612       continue;
9613     }
9614 
9615     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
9616       // Only pay attention to pseudo-objects on property references.
9617       ObjCPropertyRefExpr *pre
9618         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
9619                                               ->IgnoreParens());
9620       if (!pre) return false;
9621       if (pre->isImplicitProperty()) return false;
9622       ObjCPropertyDecl *property = pre->getExplicitProperty();
9623       if (!property->isRetaining() &&
9624           !(property->getPropertyIvarDecl() &&
9625             property->getPropertyIvarDecl()->getType()
9626               .getObjCLifetime() == Qualifiers::OCL_Strong))
9627           return false;
9628 
9629       owner.Indirect = true;
9630       if (pre->isSuperReceiver()) {
9631         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
9632         if (!owner.Variable)
9633           return false;
9634         owner.Loc = pre->getLocation();
9635         owner.Range = pre->getSourceRange();
9636         return true;
9637       }
9638       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
9639                               ->getSourceExpr());
9640       continue;
9641     }
9642 
9643     // Array ivars?
9644 
9645     return false;
9646   }
9647 }
9648 
9649 namespace {
9650   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
9651     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
9652       : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
9653         Context(Context), Variable(variable), Capturer(nullptr),
9654         VarWillBeReased(false) {}
9655     ASTContext &Context;
9656     VarDecl *Variable;
9657     Expr *Capturer;
9658     bool VarWillBeReased;
9659 
9660     void VisitDeclRefExpr(DeclRefExpr *ref) {
9661       if (ref->getDecl() == Variable && !Capturer)
9662         Capturer = ref;
9663     }
9664 
9665     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
9666       if (Capturer) return;
9667       Visit(ref->getBase());
9668       if (Capturer && ref->isFreeIvar())
9669         Capturer = ref;
9670     }
9671 
9672     void VisitBlockExpr(BlockExpr *block) {
9673       // Look inside nested blocks
9674       if (block->getBlockDecl()->capturesVariable(Variable))
9675         Visit(block->getBlockDecl()->getBody());
9676     }
9677 
9678     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
9679       if (Capturer) return;
9680       if (OVE->getSourceExpr())
9681         Visit(OVE->getSourceExpr());
9682     }
9683     void VisitBinaryOperator(BinaryOperator *BinOp) {
9684       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
9685         return;
9686       Expr *LHS = BinOp->getLHS();
9687       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
9688         if (DRE->getDecl() != Variable)
9689           return;
9690         if (Expr *RHS = BinOp->getRHS()) {
9691           RHS = RHS->IgnoreParenCasts();
9692           llvm::APSInt Value;
9693           VarWillBeReased =
9694             (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
9695         }
9696       }
9697     }
9698   };
9699 } // end anonymous namespace
9700 
9701 /// Check whether the given argument is a block which captures a
9702 /// variable.
9703 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
9704   assert(owner.Variable && owner.Loc.isValid());
9705 
9706   e = e->IgnoreParenCasts();
9707 
9708   // Look through [^{...} copy] and Block_copy(^{...}).
9709   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
9710     Selector Cmd = ME->getSelector();
9711     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
9712       e = ME->getInstanceReceiver();
9713       if (!e)
9714         return nullptr;
9715       e = e->IgnoreParenCasts();
9716     }
9717   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
9718     if (CE->getNumArgs() == 1) {
9719       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
9720       if (Fn) {
9721         const IdentifierInfo *FnI = Fn->getIdentifier();
9722         if (FnI && FnI->isStr("_Block_copy")) {
9723           e = CE->getArg(0)->IgnoreParenCasts();
9724         }
9725       }
9726     }
9727   }
9728 
9729   BlockExpr *block = dyn_cast<BlockExpr>(e);
9730   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
9731     return nullptr;
9732 
9733   FindCaptureVisitor visitor(S.Context, owner.Variable);
9734   visitor.Visit(block->getBlockDecl()->getBody());
9735   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
9736 }
9737 
9738 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
9739                                 RetainCycleOwner &owner) {
9740   assert(capturer);
9741   assert(owner.Variable && owner.Loc.isValid());
9742 
9743   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
9744     << owner.Variable << capturer->getSourceRange();
9745   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
9746     << owner.Indirect << owner.Range;
9747 }
9748 
9749 /// Check for a keyword selector that starts with the word 'add' or
9750 /// 'set'.
9751 static bool isSetterLikeSelector(Selector sel) {
9752   if (sel.isUnarySelector()) return false;
9753 
9754   StringRef str = sel.getNameForSlot(0);
9755   while (!str.empty() && str.front() == '_') str = str.substr(1);
9756   if (str.startswith("set"))
9757     str = str.substr(3);
9758   else if (str.startswith("add")) {
9759     // Specially whitelist 'addOperationWithBlock:'.
9760     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
9761       return false;
9762     str = str.substr(3);
9763   }
9764   else
9765     return false;
9766 
9767   if (str.empty()) return true;
9768   return !isLowercase(str.front());
9769 }
9770 
9771 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
9772                                                     ObjCMessageExpr *Message) {
9773   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
9774                                                 Message->getReceiverInterface(),
9775                                                 NSAPI::ClassId_NSMutableArray);
9776   if (!IsMutableArray) {
9777     return None;
9778   }
9779 
9780   Selector Sel = Message->getSelector();
9781 
9782   Optional<NSAPI::NSArrayMethodKind> MKOpt =
9783     S.NSAPIObj->getNSArrayMethodKind(Sel);
9784   if (!MKOpt) {
9785     return None;
9786   }
9787 
9788   NSAPI::NSArrayMethodKind MK = *MKOpt;
9789 
9790   switch (MK) {
9791     case NSAPI::NSMutableArr_addObject:
9792     case NSAPI::NSMutableArr_insertObjectAtIndex:
9793     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
9794       return 0;
9795     case NSAPI::NSMutableArr_replaceObjectAtIndex:
9796       return 1;
9797 
9798     default:
9799       return None;
9800   }
9801 
9802   return None;
9803 }
9804 
9805 static
9806 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
9807                                                   ObjCMessageExpr *Message) {
9808   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
9809                                             Message->getReceiverInterface(),
9810                                             NSAPI::ClassId_NSMutableDictionary);
9811   if (!IsMutableDictionary) {
9812     return None;
9813   }
9814 
9815   Selector Sel = Message->getSelector();
9816 
9817   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
9818     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
9819   if (!MKOpt) {
9820     return None;
9821   }
9822 
9823   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
9824 
9825   switch (MK) {
9826     case NSAPI::NSMutableDict_setObjectForKey:
9827     case NSAPI::NSMutableDict_setValueForKey:
9828     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
9829       return 0;
9830 
9831     default:
9832       return None;
9833   }
9834 
9835   return None;
9836 }
9837 
9838 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
9839   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
9840                                                 Message->getReceiverInterface(),
9841                                                 NSAPI::ClassId_NSMutableSet);
9842 
9843   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
9844                                             Message->getReceiverInterface(),
9845                                             NSAPI::ClassId_NSMutableOrderedSet);
9846   if (!IsMutableSet && !IsMutableOrderedSet) {
9847     return None;
9848   }
9849 
9850   Selector Sel = Message->getSelector();
9851 
9852   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
9853   if (!MKOpt) {
9854     return None;
9855   }
9856 
9857   NSAPI::NSSetMethodKind MK = *MKOpt;
9858 
9859   switch (MK) {
9860     case NSAPI::NSMutableSet_addObject:
9861     case NSAPI::NSOrderedSet_setObjectAtIndex:
9862     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
9863     case NSAPI::NSOrderedSet_insertObjectAtIndex:
9864       return 0;
9865     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
9866       return 1;
9867   }
9868 
9869   return None;
9870 }
9871 
9872 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
9873   if (!Message->isInstanceMessage()) {
9874     return;
9875   }
9876 
9877   Optional<int> ArgOpt;
9878 
9879   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
9880       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
9881       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
9882     return;
9883   }
9884 
9885   int ArgIndex = *ArgOpt;
9886 
9887   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
9888   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
9889     Arg = OE->getSourceExpr()->IgnoreImpCasts();
9890   }
9891 
9892   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
9893     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
9894       if (ArgRE->isObjCSelfExpr()) {
9895         Diag(Message->getSourceRange().getBegin(),
9896              diag::warn_objc_circular_container)
9897           << ArgRE->getDecl()->getName() << StringRef("super");
9898       }
9899     }
9900   } else {
9901     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
9902 
9903     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
9904       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
9905     }
9906 
9907     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
9908       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
9909         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
9910           ValueDecl *Decl = ReceiverRE->getDecl();
9911           Diag(Message->getSourceRange().getBegin(),
9912                diag::warn_objc_circular_container)
9913             << Decl->getName() << Decl->getName();
9914           if (!ArgRE->isObjCSelfExpr()) {
9915             Diag(Decl->getLocation(),
9916                  diag::note_objc_circular_container_declared_here)
9917               << Decl->getName();
9918           }
9919         }
9920       }
9921     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
9922       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
9923         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
9924           ObjCIvarDecl *Decl = IvarRE->getDecl();
9925           Diag(Message->getSourceRange().getBegin(),
9926                diag::warn_objc_circular_container)
9927             << Decl->getName() << Decl->getName();
9928           Diag(Decl->getLocation(),
9929                diag::note_objc_circular_container_declared_here)
9930             << Decl->getName();
9931         }
9932       }
9933     }
9934   }
9935 }
9936 
9937 /// Check a message send to see if it's likely to cause a retain cycle.
9938 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
9939   // Only check instance methods whose selector looks like a setter.
9940   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
9941     return;
9942 
9943   // Try to find a variable that the receiver is strongly owned by.
9944   RetainCycleOwner owner;
9945   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
9946     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
9947       return;
9948   } else {
9949     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
9950     owner.Variable = getCurMethodDecl()->getSelfDecl();
9951     owner.Loc = msg->getSuperLoc();
9952     owner.Range = msg->getSuperLoc();
9953   }
9954 
9955   // Check whether the receiver is captured by any of the arguments.
9956   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
9957     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
9958       return diagnoseRetainCycle(*this, capturer, owner);
9959 }
9960 
9961 /// Check a property assign to see if it's likely to cause a retain cycle.
9962 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
9963   RetainCycleOwner owner;
9964   if (!findRetainCycleOwner(*this, receiver, owner))
9965     return;
9966 
9967   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
9968     diagnoseRetainCycle(*this, capturer, owner);
9969 }
9970 
9971 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
9972   RetainCycleOwner Owner;
9973   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
9974     return;
9975 
9976   // Because we don't have an expression for the variable, we have to set the
9977   // location explicitly here.
9978   Owner.Loc = Var->getLocation();
9979   Owner.Range = Var->getSourceRange();
9980 
9981   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
9982     diagnoseRetainCycle(*this, Capturer, Owner);
9983 }
9984 
9985 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
9986                                      Expr *RHS, bool isProperty) {
9987   // Check if RHS is an Objective-C object literal, which also can get
9988   // immediately zapped in a weak reference.  Note that we explicitly
9989   // allow ObjCStringLiterals, since those are designed to never really die.
9990   RHS = RHS->IgnoreParenImpCasts();
9991 
9992   // This enum needs to match with the 'select' in
9993   // warn_objc_arc_literal_assign (off-by-1).
9994   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
9995   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
9996     return false;
9997 
9998   S.Diag(Loc, diag::warn_arc_literal_assign)
9999     << (unsigned) Kind
10000     << (isProperty ? 0 : 1)
10001     << RHS->getSourceRange();
10002 
10003   return true;
10004 }
10005 
10006 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
10007                                     Qualifiers::ObjCLifetime LT,
10008                                     Expr *RHS, bool isProperty) {
10009   // Strip off any implicit cast added to get to the one ARC-specific.
10010   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
10011     if (cast->getCastKind() == CK_ARCConsumeObject) {
10012       S.Diag(Loc, diag::warn_arc_retained_assign)
10013         << (LT == Qualifiers::OCL_ExplicitNone)
10014         << (isProperty ? 0 : 1)
10015         << RHS->getSourceRange();
10016       return true;
10017     }
10018     RHS = cast->getSubExpr();
10019   }
10020 
10021   if (LT == Qualifiers::OCL_Weak &&
10022       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
10023     return true;
10024 
10025   return false;
10026 }
10027 
10028 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
10029                               QualType LHS, Expr *RHS) {
10030   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
10031 
10032   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
10033     return false;
10034 
10035   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
10036     return true;
10037 
10038   return false;
10039 }
10040 
10041 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
10042                               Expr *LHS, Expr *RHS) {
10043   QualType LHSType;
10044   // PropertyRef on LHS type need be directly obtained from
10045   // its declaration as it has a PseudoType.
10046   ObjCPropertyRefExpr *PRE
10047     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
10048   if (PRE && !PRE->isImplicitProperty()) {
10049     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
10050     if (PD)
10051       LHSType = PD->getType();
10052   }
10053 
10054   if (LHSType.isNull())
10055     LHSType = LHS->getType();
10056 
10057   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
10058 
10059   if (LT == Qualifiers::OCL_Weak) {
10060     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
10061       getCurFunction()->markSafeWeakUse(LHS);
10062   }
10063 
10064   if (checkUnsafeAssigns(Loc, LHSType, RHS))
10065     return;
10066 
10067   // FIXME. Check for other life times.
10068   if (LT != Qualifiers::OCL_None)
10069     return;
10070 
10071   if (PRE) {
10072     if (PRE->isImplicitProperty())
10073       return;
10074     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
10075     if (!PD)
10076       return;
10077 
10078     unsigned Attributes = PD->getPropertyAttributes();
10079     if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
10080       // when 'assign' attribute was not explicitly specified
10081       // by user, ignore it and rely on property type itself
10082       // for lifetime info.
10083       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
10084       if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
10085           LHSType->isObjCRetainableType())
10086         return;
10087 
10088       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
10089         if (cast->getCastKind() == CK_ARCConsumeObject) {
10090           Diag(Loc, diag::warn_arc_retained_property_assign)
10091           << RHS->getSourceRange();
10092           return;
10093         }
10094         RHS = cast->getSubExpr();
10095       }
10096     }
10097     else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
10098       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
10099         return;
10100     }
10101   }
10102 }
10103 
10104 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
10105 
10106 namespace {
10107 bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
10108                                  SourceLocation StmtLoc,
10109                                  const NullStmt *Body) {
10110   // Do not warn if the body is a macro that expands to nothing, e.g:
10111   //
10112   // #define CALL(x)
10113   // if (condition)
10114   //   CALL(0);
10115   //
10116   if (Body->hasLeadingEmptyMacro())
10117     return false;
10118 
10119   // Get line numbers of statement and body.
10120   bool StmtLineInvalid;
10121   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
10122                                                       &StmtLineInvalid);
10123   if (StmtLineInvalid)
10124     return false;
10125 
10126   bool BodyLineInvalid;
10127   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
10128                                                       &BodyLineInvalid);
10129   if (BodyLineInvalid)
10130     return false;
10131 
10132   // Warn if null statement and body are on the same line.
10133   if (StmtLine != BodyLine)
10134     return false;
10135 
10136   return true;
10137 }
10138 } // end anonymous namespace
10139 
10140 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
10141                                  const Stmt *Body,
10142                                  unsigned DiagID) {
10143   // Since this is a syntactic check, don't emit diagnostic for template
10144   // instantiations, this just adds noise.
10145   if (CurrentInstantiationScope)
10146     return;
10147 
10148   // The body should be a null statement.
10149   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
10150   if (!NBody)
10151     return;
10152 
10153   // Do the usual checks.
10154   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
10155     return;
10156 
10157   Diag(NBody->getSemiLoc(), DiagID);
10158   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
10159 }
10160 
10161 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
10162                                  const Stmt *PossibleBody) {
10163   assert(!CurrentInstantiationScope); // Ensured by caller
10164 
10165   SourceLocation StmtLoc;
10166   const Stmt *Body;
10167   unsigned DiagID;
10168   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
10169     StmtLoc = FS->getRParenLoc();
10170     Body = FS->getBody();
10171     DiagID = diag::warn_empty_for_body;
10172   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
10173     StmtLoc = WS->getCond()->getSourceRange().getEnd();
10174     Body = WS->getBody();
10175     DiagID = diag::warn_empty_while_body;
10176   } else
10177     return; // Neither `for' nor `while'.
10178 
10179   // The body should be a null statement.
10180   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
10181   if (!NBody)
10182     return;
10183 
10184   // Skip expensive checks if diagnostic is disabled.
10185   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
10186     return;
10187 
10188   // Do the usual checks.
10189   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
10190     return;
10191 
10192   // `for(...);' and `while(...);' are popular idioms, so in order to keep
10193   // noise level low, emit diagnostics only if for/while is followed by a
10194   // CompoundStmt, e.g.:
10195   //    for (int i = 0; i < n; i++);
10196   //    {
10197   //      a(i);
10198   //    }
10199   // or if for/while is followed by a statement with more indentation
10200   // than for/while itself:
10201   //    for (int i = 0; i < n; i++);
10202   //      a(i);
10203   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
10204   if (!ProbableTypo) {
10205     bool BodyColInvalid;
10206     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
10207                              PossibleBody->getLocStart(),
10208                              &BodyColInvalid);
10209     if (BodyColInvalid)
10210       return;
10211 
10212     bool StmtColInvalid;
10213     unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
10214                              S->getLocStart(),
10215                              &StmtColInvalid);
10216     if (StmtColInvalid)
10217       return;
10218 
10219     if (BodyCol > StmtCol)
10220       ProbableTypo = true;
10221   }
10222 
10223   if (ProbableTypo) {
10224     Diag(NBody->getSemiLoc(), DiagID);
10225     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
10226   }
10227 }
10228 
10229 //===--- CHECK: Warn on self move with std::move. -------------------------===//
10230 
10231 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
10232 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
10233                              SourceLocation OpLoc) {
10234   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
10235     return;
10236 
10237   if (!ActiveTemplateInstantiations.empty())
10238     return;
10239 
10240   // Strip parens and casts away.
10241   LHSExpr = LHSExpr->IgnoreParenImpCasts();
10242   RHSExpr = RHSExpr->IgnoreParenImpCasts();
10243 
10244   // Check for a call expression
10245   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
10246   if (!CE || CE->getNumArgs() != 1)
10247     return;
10248 
10249   // Check for a call to std::move
10250   const FunctionDecl *FD = CE->getDirectCallee();
10251   if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
10252       !FD->getIdentifier()->isStr("move"))
10253     return;
10254 
10255   // Get argument from std::move
10256   RHSExpr = CE->getArg(0);
10257 
10258   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
10259   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
10260 
10261   // Two DeclRefExpr's, check that the decls are the same.
10262   if (LHSDeclRef && RHSDeclRef) {
10263     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
10264       return;
10265     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
10266         RHSDeclRef->getDecl()->getCanonicalDecl())
10267       return;
10268 
10269     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
10270                                         << LHSExpr->getSourceRange()
10271                                         << RHSExpr->getSourceRange();
10272     return;
10273   }
10274 
10275   // Member variables require a different approach to check for self moves.
10276   // MemberExpr's are the same if every nested MemberExpr refers to the same
10277   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
10278   // the base Expr's are CXXThisExpr's.
10279   const Expr *LHSBase = LHSExpr;
10280   const Expr *RHSBase = RHSExpr;
10281   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
10282   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
10283   if (!LHSME || !RHSME)
10284     return;
10285 
10286   while (LHSME && RHSME) {
10287     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
10288         RHSME->getMemberDecl()->getCanonicalDecl())
10289       return;
10290 
10291     LHSBase = LHSME->getBase();
10292     RHSBase = RHSME->getBase();
10293     LHSME = dyn_cast<MemberExpr>(LHSBase);
10294     RHSME = dyn_cast<MemberExpr>(RHSBase);
10295   }
10296 
10297   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
10298   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
10299   if (LHSDeclRef && RHSDeclRef) {
10300     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
10301       return;
10302     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
10303         RHSDeclRef->getDecl()->getCanonicalDecl())
10304       return;
10305 
10306     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
10307                                         << LHSExpr->getSourceRange()
10308                                         << RHSExpr->getSourceRange();
10309     return;
10310   }
10311 
10312   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
10313     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
10314                                         << LHSExpr->getSourceRange()
10315                                         << RHSExpr->getSourceRange();
10316 }
10317 
10318 //===--- Layout compatibility ----------------------------------------------//
10319 
10320 namespace {
10321 
10322 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
10323 
10324 /// \brief Check if two enumeration types are layout-compatible.
10325 bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
10326   // C++11 [dcl.enum] p8:
10327   // Two enumeration types are layout-compatible if they have the same
10328   // underlying type.
10329   return ED1->isComplete() && ED2->isComplete() &&
10330          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
10331 }
10332 
10333 /// \brief Check if two fields are layout-compatible.
10334 bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
10335   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
10336     return false;
10337 
10338   if (Field1->isBitField() != Field2->isBitField())
10339     return false;
10340 
10341   if (Field1->isBitField()) {
10342     // Make sure that the bit-fields are the same length.
10343     unsigned Bits1 = Field1->getBitWidthValue(C);
10344     unsigned Bits2 = Field2->getBitWidthValue(C);
10345 
10346     if (Bits1 != Bits2)
10347       return false;
10348   }
10349 
10350   return true;
10351 }
10352 
10353 /// \brief Check if two standard-layout structs are layout-compatible.
10354 /// (C++11 [class.mem] p17)
10355 bool isLayoutCompatibleStruct(ASTContext &C,
10356                               RecordDecl *RD1,
10357                               RecordDecl *RD2) {
10358   // If both records are C++ classes, check that base classes match.
10359   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
10360     // If one of records is a CXXRecordDecl we are in C++ mode,
10361     // thus the other one is a CXXRecordDecl, too.
10362     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
10363     // Check number of base classes.
10364     if (D1CXX->getNumBases() != D2CXX->getNumBases())
10365       return false;
10366 
10367     // Check the base classes.
10368     for (CXXRecordDecl::base_class_const_iterator
10369                Base1 = D1CXX->bases_begin(),
10370            BaseEnd1 = D1CXX->bases_end(),
10371               Base2 = D2CXX->bases_begin();
10372          Base1 != BaseEnd1;
10373          ++Base1, ++Base2) {
10374       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
10375         return false;
10376     }
10377   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
10378     // If only RD2 is a C++ class, it should have zero base classes.
10379     if (D2CXX->getNumBases() > 0)
10380       return false;
10381   }
10382 
10383   // Check the fields.
10384   RecordDecl::field_iterator Field2 = RD2->field_begin(),
10385                              Field2End = RD2->field_end(),
10386                              Field1 = RD1->field_begin(),
10387                              Field1End = RD1->field_end();
10388   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
10389     if (!isLayoutCompatible(C, *Field1, *Field2))
10390       return false;
10391   }
10392   if (Field1 != Field1End || Field2 != Field2End)
10393     return false;
10394 
10395   return true;
10396 }
10397 
10398 /// \brief Check if two standard-layout unions are layout-compatible.
10399 /// (C++11 [class.mem] p18)
10400 bool isLayoutCompatibleUnion(ASTContext &C,
10401                              RecordDecl *RD1,
10402                              RecordDecl *RD2) {
10403   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
10404   for (auto *Field2 : RD2->fields())
10405     UnmatchedFields.insert(Field2);
10406 
10407   for (auto *Field1 : RD1->fields()) {
10408     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
10409         I = UnmatchedFields.begin(),
10410         E = UnmatchedFields.end();
10411 
10412     for ( ; I != E; ++I) {
10413       if (isLayoutCompatible(C, Field1, *I)) {
10414         bool Result = UnmatchedFields.erase(*I);
10415         (void) Result;
10416         assert(Result);
10417         break;
10418       }
10419     }
10420     if (I == E)
10421       return false;
10422   }
10423 
10424   return UnmatchedFields.empty();
10425 }
10426 
10427 bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
10428   if (RD1->isUnion() != RD2->isUnion())
10429     return false;
10430 
10431   if (RD1->isUnion())
10432     return isLayoutCompatibleUnion(C, RD1, RD2);
10433   else
10434     return isLayoutCompatibleStruct(C, RD1, RD2);
10435 }
10436 
10437 /// \brief Check if two types are layout-compatible in C++11 sense.
10438 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
10439   if (T1.isNull() || T2.isNull())
10440     return false;
10441 
10442   // C++11 [basic.types] p11:
10443   // If two types T1 and T2 are the same type, then T1 and T2 are
10444   // layout-compatible types.
10445   if (C.hasSameType(T1, T2))
10446     return true;
10447 
10448   T1 = T1.getCanonicalType().getUnqualifiedType();
10449   T2 = T2.getCanonicalType().getUnqualifiedType();
10450 
10451   const Type::TypeClass TC1 = T1->getTypeClass();
10452   const Type::TypeClass TC2 = T2->getTypeClass();
10453 
10454   if (TC1 != TC2)
10455     return false;
10456 
10457   if (TC1 == Type::Enum) {
10458     return isLayoutCompatible(C,
10459                               cast<EnumType>(T1)->getDecl(),
10460                               cast<EnumType>(T2)->getDecl());
10461   } else if (TC1 == Type::Record) {
10462     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
10463       return false;
10464 
10465     return isLayoutCompatible(C,
10466                               cast<RecordType>(T1)->getDecl(),
10467                               cast<RecordType>(T2)->getDecl());
10468   }
10469 
10470   return false;
10471 }
10472 } // end anonymous namespace
10473 
10474 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
10475 
10476 namespace {
10477 /// \brief Given a type tag expression find the type tag itself.
10478 ///
10479 /// \param TypeExpr Type tag expression, as it appears in user's code.
10480 ///
10481 /// \param VD Declaration of an identifier that appears in a type tag.
10482 ///
10483 /// \param MagicValue Type tag magic value.
10484 bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
10485                      const ValueDecl **VD, uint64_t *MagicValue) {
10486   while(true) {
10487     if (!TypeExpr)
10488       return false;
10489 
10490     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
10491 
10492     switch (TypeExpr->getStmtClass()) {
10493     case Stmt::UnaryOperatorClass: {
10494       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
10495       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
10496         TypeExpr = UO->getSubExpr();
10497         continue;
10498       }
10499       return false;
10500     }
10501 
10502     case Stmt::DeclRefExprClass: {
10503       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
10504       *VD = DRE->getDecl();
10505       return true;
10506     }
10507 
10508     case Stmt::IntegerLiteralClass: {
10509       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
10510       llvm::APInt MagicValueAPInt = IL->getValue();
10511       if (MagicValueAPInt.getActiveBits() <= 64) {
10512         *MagicValue = MagicValueAPInt.getZExtValue();
10513         return true;
10514       } else
10515         return false;
10516     }
10517 
10518     case Stmt::BinaryConditionalOperatorClass:
10519     case Stmt::ConditionalOperatorClass: {
10520       const AbstractConditionalOperator *ACO =
10521           cast<AbstractConditionalOperator>(TypeExpr);
10522       bool Result;
10523       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
10524         if (Result)
10525           TypeExpr = ACO->getTrueExpr();
10526         else
10527           TypeExpr = ACO->getFalseExpr();
10528         continue;
10529       }
10530       return false;
10531     }
10532 
10533     case Stmt::BinaryOperatorClass: {
10534       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
10535       if (BO->getOpcode() == BO_Comma) {
10536         TypeExpr = BO->getRHS();
10537         continue;
10538       }
10539       return false;
10540     }
10541 
10542     default:
10543       return false;
10544     }
10545   }
10546 }
10547 
10548 /// \brief Retrieve the C type corresponding to type tag TypeExpr.
10549 ///
10550 /// \param TypeExpr Expression that specifies a type tag.
10551 ///
10552 /// \param MagicValues Registered magic values.
10553 ///
10554 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
10555 ///        kind.
10556 ///
10557 /// \param TypeInfo Information about the corresponding C type.
10558 ///
10559 /// \returns true if the corresponding C type was found.
10560 bool GetMatchingCType(
10561         const IdentifierInfo *ArgumentKind,
10562         const Expr *TypeExpr, const ASTContext &Ctx,
10563         const llvm::DenseMap<Sema::TypeTagMagicValue,
10564                              Sema::TypeTagData> *MagicValues,
10565         bool &FoundWrongKind,
10566         Sema::TypeTagData &TypeInfo) {
10567   FoundWrongKind = false;
10568 
10569   // Variable declaration that has type_tag_for_datatype attribute.
10570   const ValueDecl *VD = nullptr;
10571 
10572   uint64_t MagicValue;
10573 
10574   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
10575     return false;
10576 
10577   if (VD) {
10578     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
10579       if (I->getArgumentKind() != ArgumentKind) {
10580         FoundWrongKind = true;
10581         return false;
10582       }
10583       TypeInfo.Type = I->getMatchingCType();
10584       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
10585       TypeInfo.MustBeNull = I->getMustBeNull();
10586       return true;
10587     }
10588     return false;
10589   }
10590 
10591   if (!MagicValues)
10592     return false;
10593 
10594   llvm::DenseMap<Sema::TypeTagMagicValue,
10595                  Sema::TypeTagData>::const_iterator I =
10596       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
10597   if (I == MagicValues->end())
10598     return false;
10599 
10600   TypeInfo = I->second;
10601   return true;
10602 }
10603 } // end anonymous namespace
10604 
10605 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
10606                                       uint64_t MagicValue, QualType Type,
10607                                       bool LayoutCompatible,
10608                                       bool MustBeNull) {
10609   if (!TypeTagForDatatypeMagicValues)
10610     TypeTagForDatatypeMagicValues.reset(
10611         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
10612 
10613   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
10614   (*TypeTagForDatatypeMagicValues)[Magic] =
10615       TypeTagData(Type, LayoutCompatible, MustBeNull);
10616 }
10617 
10618 namespace {
10619 bool IsSameCharType(QualType T1, QualType T2) {
10620   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
10621   if (!BT1)
10622     return false;
10623 
10624   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
10625   if (!BT2)
10626     return false;
10627 
10628   BuiltinType::Kind T1Kind = BT1->getKind();
10629   BuiltinType::Kind T2Kind = BT2->getKind();
10630 
10631   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
10632          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
10633          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
10634          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
10635 }
10636 } // end anonymous namespace
10637 
10638 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
10639                                     const Expr * const *ExprArgs) {
10640   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
10641   bool IsPointerAttr = Attr->getIsPointer();
10642 
10643   const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
10644   bool FoundWrongKind;
10645   TypeTagData TypeInfo;
10646   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
10647                         TypeTagForDatatypeMagicValues.get(),
10648                         FoundWrongKind, TypeInfo)) {
10649     if (FoundWrongKind)
10650       Diag(TypeTagExpr->getExprLoc(),
10651            diag::warn_type_tag_for_datatype_wrong_kind)
10652         << TypeTagExpr->getSourceRange();
10653     return;
10654   }
10655 
10656   const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
10657   if (IsPointerAttr) {
10658     // Skip implicit cast of pointer to `void *' (as a function argument).
10659     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
10660       if (ICE->getType()->isVoidPointerType() &&
10661           ICE->getCastKind() == CK_BitCast)
10662         ArgumentExpr = ICE->getSubExpr();
10663   }
10664   QualType ArgumentType = ArgumentExpr->getType();
10665 
10666   // Passing a `void*' pointer shouldn't trigger a warning.
10667   if (IsPointerAttr && ArgumentType->isVoidPointerType())
10668     return;
10669 
10670   if (TypeInfo.MustBeNull) {
10671     // Type tag with matching void type requires a null pointer.
10672     if (!ArgumentExpr->isNullPointerConstant(Context,
10673                                              Expr::NPC_ValueDependentIsNotNull)) {
10674       Diag(ArgumentExpr->getExprLoc(),
10675            diag::warn_type_safety_null_pointer_required)
10676           << ArgumentKind->getName()
10677           << ArgumentExpr->getSourceRange()
10678           << TypeTagExpr->getSourceRange();
10679     }
10680     return;
10681   }
10682 
10683   QualType RequiredType = TypeInfo.Type;
10684   if (IsPointerAttr)
10685     RequiredType = Context.getPointerType(RequiredType);
10686 
10687   bool mismatch = false;
10688   if (!TypeInfo.LayoutCompatible) {
10689     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
10690 
10691     // C++11 [basic.fundamental] p1:
10692     // Plain char, signed char, and unsigned char are three distinct types.
10693     //
10694     // But we treat plain `char' as equivalent to `signed char' or `unsigned
10695     // char' depending on the current char signedness mode.
10696     if (mismatch)
10697       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
10698                                            RequiredType->getPointeeType())) ||
10699           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
10700         mismatch = false;
10701   } else
10702     if (IsPointerAttr)
10703       mismatch = !isLayoutCompatible(Context,
10704                                      ArgumentType->getPointeeType(),
10705                                      RequiredType->getPointeeType());
10706     else
10707       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
10708 
10709   if (mismatch)
10710     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
10711         << ArgumentType << ArgumentKind
10712         << TypeInfo.LayoutCompatible << RequiredType
10713         << ArgumentExpr->getSourceRange()
10714         << TypeTagExpr->getSourceRange();
10715 }
10716