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