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