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