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