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