clang API Documentation

SemaChecking.cpp
Go to the documentation of this file.
00001 //===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 //  This file implements extra semantic analysis beyond what is enforced
00011 //  by the C type system.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "clang/Sema/SemaInternal.h"
00016 #include "clang/AST/ASTContext.h"
00017 #include "clang/AST/CharUnits.h"
00018 #include "clang/AST/DeclCXX.h"
00019 #include "clang/AST/DeclObjC.h"
00020 #include "clang/AST/EvaluatedExprVisitor.h"
00021 #include "clang/AST/Expr.h"
00022 #include "clang/AST/ExprCXX.h"
00023 #include "clang/AST/ExprObjC.h"
00024 #include "clang/AST/StmtCXX.h"
00025 #include "clang/AST/StmtObjC.h"
00026 #include "clang/Analysis/Analyses/FormatString.h"
00027 #include "clang/Basic/CharInfo.h"
00028 #include "clang/Basic/TargetBuiltins.h"
00029 #include "clang/Basic/TargetInfo.h"
00030 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
00031 #include "clang/Sema/Initialization.h"
00032 #include "clang/Sema/Lookup.h"
00033 #include "clang/Sema/ScopeInfo.h"
00034 #include "clang/Sema/Sema.h"
00035 #include "llvm/ADT/STLExtras.h"
00036 #include "llvm/ADT/SmallBitVector.h"
00037 #include "llvm/ADT/SmallString.h"
00038 #include "llvm/Support/ConvertUTF.h"
00039 #include "llvm/Support/raw_ostream.h"
00040 #include <limits>
00041 using namespace clang;
00042 using namespace sema;
00043 
00044 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
00045                                                     unsigned ByteNo) const {
00046   return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
00047                                Context.getTargetInfo());
00048 }
00049 
00050 /// Checks that a call expression's argument count is the desired number.
00051 /// This is useful when doing custom type-checking.  Returns true on error.
00052 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
00053   unsigned argCount = call->getNumArgs();
00054   if (argCount == desiredArgCount) return false;
00055 
00056   if (argCount < desiredArgCount)
00057     return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
00058         << 0 /*function call*/ << desiredArgCount << argCount
00059         << call->getSourceRange();
00060 
00061   // Highlight all the excess arguments.
00062   SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
00063                     call->getArg(argCount - 1)->getLocEnd());
00064     
00065   return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
00066     << 0 /*function call*/ << desiredArgCount << argCount
00067     << call->getArg(1)->getSourceRange();
00068 }
00069 
00070 /// Check that the first argument to __builtin_annotation is an integer
00071 /// and the second argument is a non-wide string literal.
00072 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
00073   if (checkArgCount(S, TheCall, 2))
00074     return true;
00075 
00076   // First argument should be an integer.
00077   Expr *ValArg = TheCall->getArg(0);
00078   QualType Ty = ValArg->getType();
00079   if (!Ty->isIntegerType()) {
00080     S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
00081       << ValArg->getSourceRange();
00082     return true;
00083   }
00084 
00085   // Second argument should be a constant string.
00086   Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
00087   StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
00088   if (!Literal || !Literal->isAscii()) {
00089     S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
00090       << StrArg->getSourceRange();
00091     return true;
00092   }
00093 
00094   TheCall->setType(Ty);
00095   return false;
00096 }
00097 
00098 /// Check that the argument to __builtin_addressof is a glvalue, and set the
00099 /// result type to the corresponding pointer type.
00100 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
00101   if (checkArgCount(S, TheCall, 1))
00102     return true;
00103 
00104   ExprResult Arg(TheCall->getArg(0));
00105   QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
00106   if (ResultType.isNull())
00107     return true;
00108 
00109   TheCall->setArg(0, Arg.get());
00110   TheCall->setType(ResultType);
00111   return false;
00112 }
00113 
00114 static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
00115                       CallExpr *TheCall, unsigned SizeIdx,
00116                                   unsigned DstSizeIdx) {
00117   if (TheCall->getNumArgs() <= SizeIdx ||
00118       TheCall->getNumArgs() <= DstSizeIdx)
00119     return;
00120 
00121   const Expr *SizeArg = TheCall->getArg(SizeIdx);
00122   const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
00123 
00124   llvm::APSInt Size, DstSize;
00125 
00126   // find out if both sizes are known at compile time
00127   if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
00128       !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
00129     return;
00130 
00131   if (Size.ule(DstSize))
00132     return;
00133 
00134   // confirmed overflow so generate the diagnostic.
00135   IdentifierInfo *FnName = FDecl->getIdentifier();
00136   SourceLocation SL = TheCall->getLocStart();
00137   SourceRange SR = TheCall->getSourceRange();
00138 
00139   S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
00140 }
00141 
00142 ExprResult
00143 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
00144                                CallExpr *TheCall) {
00145   ExprResult TheCallResult(TheCall);
00146 
00147   // Find out if any arguments are required to be integer constant expressions.
00148   unsigned ICEArguments = 0;
00149   ASTContext::GetBuiltinTypeError Error;
00150   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
00151   if (Error != ASTContext::GE_None)
00152     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
00153   
00154   // If any arguments are required to be ICE's, check and diagnose.
00155   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
00156     // Skip arguments not required to be ICE's.
00157     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
00158     
00159     llvm::APSInt Result;
00160     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
00161       return true;
00162     ICEArguments &= ~(1 << ArgNo);
00163   }
00164   
00165   switch (BuiltinID) {
00166   case Builtin::BI__builtin___CFStringMakeConstantString:
00167     assert(TheCall->getNumArgs() == 1 &&
00168            "Wrong # arguments to builtin CFStringMakeConstantString");
00169     if (CheckObjCString(TheCall->getArg(0)))
00170       return ExprError();
00171     break;
00172   case Builtin::BI__builtin_stdarg_start:
00173   case Builtin::BI__builtin_va_start:
00174     if (SemaBuiltinVAStart(TheCall))
00175       return ExprError();
00176     break;
00177   case Builtin::BI__va_start: {
00178     switch (Context.getTargetInfo().getTriple().getArch()) {
00179     case llvm::Triple::arm:
00180     case llvm::Triple::thumb:
00181       if (SemaBuiltinVAStartARM(TheCall))
00182         return ExprError();
00183       break;
00184     default:
00185       if (SemaBuiltinVAStart(TheCall))
00186         return ExprError();
00187       break;
00188     }
00189     break;
00190   }
00191   case Builtin::BI__builtin_isgreater:
00192   case Builtin::BI__builtin_isgreaterequal:
00193   case Builtin::BI__builtin_isless:
00194   case Builtin::BI__builtin_islessequal:
00195   case Builtin::BI__builtin_islessgreater:
00196   case Builtin::BI__builtin_isunordered:
00197     if (SemaBuiltinUnorderedCompare(TheCall))
00198       return ExprError();
00199     break;
00200   case Builtin::BI__builtin_fpclassify:
00201     if (SemaBuiltinFPClassification(TheCall, 6))
00202       return ExprError();
00203     break;
00204   case Builtin::BI__builtin_isfinite:
00205   case Builtin::BI__builtin_isinf:
00206   case Builtin::BI__builtin_isinf_sign:
00207   case Builtin::BI__builtin_isnan:
00208   case Builtin::BI__builtin_isnormal:
00209     if (SemaBuiltinFPClassification(TheCall, 1))
00210       return ExprError();
00211     break;
00212   case Builtin::BI__builtin_shufflevector:
00213     return SemaBuiltinShuffleVector(TheCall);
00214     // TheCall will be freed by the smart pointer here, but that's fine, since
00215     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
00216   case Builtin::BI__builtin_prefetch:
00217     if (SemaBuiltinPrefetch(TheCall))
00218       return ExprError();
00219     break;
00220   case Builtin::BI__assume:
00221   case Builtin::BI__builtin_assume:
00222     if (SemaBuiltinAssume(TheCall))
00223       return ExprError();
00224     break;
00225   case Builtin::BI__builtin_assume_aligned:
00226     if (SemaBuiltinAssumeAligned(TheCall))
00227       return ExprError();
00228     break;
00229   case Builtin::BI__builtin_object_size:
00230     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
00231       return ExprError();
00232     break;
00233   case Builtin::BI__builtin_longjmp:
00234     if (SemaBuiltinLongjmp(TheCall))
00235       return ExprError();
00236     break;
00237 
00238   case Builtin::BI__builtin_classify_type:
00239     if (checkArgCount(*this, TheCall, 1)) return true;
00240     TheCall->setType(Context.IntTy);
00241     break;
00242   case Builtin::BI__builtin_constant_p:
00243     if (checkArgCount(*this, TheCall, 1)) return true;
00244     TheCall->setType(Context.IntTy);
00245     break;
00246   case Builtin::BI__sync_fetch_and_add:
00247   case Builtin::BI__sync_fetch_and_add_1:
00248   case Builtin::BI__sync_fetch_and_add_2:
00249   case Builtin::BI__sync_fetch_and_add_4:
00250   case Builtin::BI__sync_fetch_and_add_8:
00251   case Builtin::BI__sync_fetch_and_add_16:
00252   case Builtin::BI__sync_fetch_and_sub:
00253   case Builtin::BI__sync_fetch_and_sub_1:
00254   case Builtin::BI__sync_fetch_and_sub_2:
00255   case Builtin::BI__sync_fetch_and_sub_4:
00256   case Builtin::BI__sync_fetch_and_sub_8:
00257   case Builtin::BI__sync_fetch_and_sub_16:
00258   case Builtin::BI__sync_fetch_and_or:
00259   case Builtin::BI__sync_fetch_and_or_1:
00260   case Builtin::BI__sync_fetch_and_or_2:
00261   case Builtin::BI__sync_fetch_and_or_4:
00262   case Builtin::BI__sync_fetch_and_or_8:
00263   case Builtin::BI__sync_fetch_and_or_16:
00264   case Builtin::BI__sync_fetch_and_and:
00265   case Builtin::BI__sync_fetch_and_and_1:
00266   case Builtin::BI__sync_fetch_and_and_2:
00267   case Builtin::BI__sync_fetch_and_and_4:
00268   case Builtin::BI__sync_fetch_and_and_8:
00269   case Builtin::BI__sync_fetch_and_and_16:
00270   case Builtin::BI__sync_fetch_and_xor:
00271   case Builtin::BI__sync_fetch_and_xor_1:
00272   case Builtin::BI__sync_fetch_and_xor_2:
00273   case Builtin::BI__sync_fetch_and_xor_4:
00274   case Builtin::BI__sync_fetch_and_xor_8:
00275   case Builtin::BI__sync_fetch_and_xor_16:
00276   case Builtin::BI__sync_fetch_and_nand:
00277   case Builtin::BI__sync_fetch_and_nand_1:
00278   case Builtin::BI__sync_fetch_and_nand_2:
00279   case Builtin::BI__sync_fetch_and_nand_4:
00280   case Builtin::BI__sync_fetch_and_nand_8:
00281   case Builtin::BI__sync_fetch_and_nand_16:
00282   case Builtin::BI__sync_add_and_fetch:
00283   case Builtin::BI__sync_add_and_fetch_1:
00284   case Builtin::BI__sync_add_and_fetch_2:
00285   case Builtin::BI__sync_add_and_fetch_4:
00286   case Builtin::BI__sync_add_and_fetch_8:
00287   case Builtin::BI__sync_add_and_fetch_16:
00288   case Builtin::BI__sync_sub_and_fetch:
00289   case Builtin::BI__sync_sub_and_fetch_1:
00290   case Builtin::BI__sync_sub_and_fetch_2:
00291   case Builtin::BI__sync_sub_and_fetch_4:
00292   case Builtin::BI__sync_sub_and_fetch_8:
00293   case Builtin::BI__sync_sub_and_fetch_16:
00294   case Builtin::BI__sync_and_and_fetch:
00295   case Builtin::BI__sync_and_and_fetch_1:
00296   case Builtin::BI__sync_and_and_fetch_2:
00297   case Builtin::BI__sync_and_and_fetch_4:
00298   case Builtin::BI__sync_and_and_fetch_8:
00299   case Builtin::BI__sync_and_and_fetch_16:
00300   case Builtin::BI__sync_or_and_fetch:
00301   case Builtin::BI__sync_or_and_fetch_1:
00302   case Builtin::BI__sync_or_and_fetch_2:
00303   case Builtin::BI__sync_or_and_fetch_4:
00304   case Builtin::BI__sync_or_and_fetch_8:
00305   case Builtin::BI__sync_or_and_fetch_16:
00306   case Builtin::BI__sync_xor_and_fetch:
00307   case Builtin::BI__sync_xor_and_fetch_1:
00308   case Builtin::BI__sync_xor_and_fetch_2:
00309   case Builtin::BI__sync_xor_and_fetch_4:
00310   case Builtin::BI__sync_xor_and_fetch_8:
00311   case Builtin::BI__sync_xor_and_fetch_16:
00312   case Builtin::BI__sync_nand_and_fetch:
00313   case Builtin::BI__sync_nand_and_fetch_1:
00314   case Builtin::BI__sync_nand_and_fetch_2:
00315   case Builtin::BI__sync_nand_and_fetch_4:
00316   case Builtin::BI__sync_nand_and_fetch_8:
00317   case Builtin::BI__sync_nand_and_fetch_16:
00318   case Builtin::BI__sync_val_compare_and_swap:
00319   case Builtin::BI__sync_val_compare_and_swap_1:
00320   case Builtin::BI__sync_val_compare_and_swap_2:
00321   case Builtin::BI__sync_val_compare_and_swap_4:
00322   case Builtin::BI__sync_val_compare_and_swap_8:
00323   case Builtin::BI__sync_val_compare_and_swap_16:
00324   case Builtin::BI__sync_bool_compare_and_swap:
00325   case Builtin::BI__sync_bool_compare_and_swap_1:
00326   case Builtin::BI__sync_bool_compare_and_swap_2:
00327   case Builtin::BI__sync_bool_compare_and_swap_4:
00328   case Builtin::BI__sync_bool_compare_and_swap_8:
00329   case Builtin::BI__sync_bool_compare_and_swap_16:
00330   case Builtin::BI__sync_lock_test_and_set:
00331   case Builtin::BI__sync_lock_test_and_set_1:
00332   case Builtin::BI__sync_lock_test_and_set_2:
00333   case Builtin::BI__sync_lock_test_and_set_4:
00334   case Builtin::BI__sync_lock_test_and_set_8:
00335   case Builtin::BI__sync_lock_test_and_set_16:
00336   case Builtin::BI__sync_lock_release:
00337   case Builtin::BI__sync_lock_release_1:
00338   case Builtin::BI__sync_lock_release_2:
00339   case Builtin::BI__sync_lock_release_4:
00340   case Builtin::BI__sync_lock_release_8:
00341   case Builtin::BI__sync_lock_release_16:
00342   case Builtin::BI__sync_swap:
00343   case Builtin::BI__sync_swap_1:
00344   case Builtin::BI__sync_swap_2:
00345   case Builtin::BI__sync_swap_4:
00346   case Builtin::BI__sync_swap_8:
00347   case Builtin::BI__sync_swap_16:
00348     return SemaBuiltinAtomicOverloaded(TheCallResult);
00349 #define BUILTIN(ID, TYPE, ATTRS)
00350 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
00351   case Builtin::BI##ID: \
00352     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
00353 #include "clang/Basic/Builtins.def"
00354   case Builtin::BI__builtin_annotation:
00355     if (SemaBuiltinAnnotation(*this, TheCall))
00356       return ExprError();
00357     break;
00358   case Builtin::BI__builtin_addressof:
00359     if (SemaBuiltinAddressof(*this, TheCall))
00360       return ExprError();
00361     break;
00362   case Builtin::BI__builtin_operator_new:
00363   case Builtin::BI__builtin_operator_delete:
00364     if (!getLangOpts().CPlusPlus) {
00365       Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
00366         << (BuiltinID == Builtin::BI__builtin_operator_new
00367                 ? "__builtin_operator_new"
00368                 : "__builtin_operator_delete")
00369         << "C++";
00370       return ExprError();
00371     }
00372     // CodeGen assumes it can find the global new and delete to call,
00373     // so ensure that they are declared.
00374     DeclareGlobalNewDelete();
00375     break;
00376 
00377   // check secure string manipulation functions where overflows
00378   // are detectable at compile time
00379   case Builtin::BI__builtin___memcpy_chk:
00380   case Builtin::BI__builtin___memmove_chk:
00381   case Builtin::BI__builtin___memset_chk:
00382   case Builtin::BI__builtin___strlcat_chk:
00383   case Builtin::BI__builtin___strlcpy_chk:
00384   case Builtin::BI__builtin___strncat_chk:
00385   case Builtin::BI__builtin___strncpy_chk:
00386   case Builtin::BI__builtin___stpncpy_chk:
00387     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
00388     break;
00389   case Builtin::BI__builtin___memccpy_chk:
00390     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
00391     break;
00392   case Builtin::BI__builtin___snprintf_chk:
00393   case Builtin::BI__builtin___vsnprintf_chk:
00394     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
00395     break;
00396   }
00397 
00398   // Since the target specific builtins for each arch overlap, only check those
00399   // of the arch we are compiling for.
00400   if (BuiltinID >= Builtin::FirstTSBuiltin) {
00401     switch (Context.getTargetInfo().getTriple().getArch()) {
00402       case llvm::Triple::arm:
00403       case llvm::Triple::armeb:
00404       case llvm::Triple::thumb:
00405       case llvm::Triple::thumbeb:
00406         if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
00407           return ExprError();
00408         break;
00409       case llvm::Triple::aarch64:
00410       case llvm::Triple::aarch64_be:
00411         if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
00412           return ExprError();
00413         break;
00414       case llvm::Triple::mips:
00415       case llvm::Triple::mipsel:
00416       case llvm::Triple::mips64:
00417       case llvm::Triple::mips64el:
00418         if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
00419           return ExprError();
00420         break;
00421       case llvm::Triple::x86:
00422       case llvm::Triple::x86_64:
00423         if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
00424           return ExprError();
00425         break;
00426       default:
00427         break;
00428     }
00429   }
00430 
00431   return TheCallResult;
00432 }
00433 
00434 // Get the valid immediate range for the specified NEON type code.
00435 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
00436   NeonTypeFlags Type(t);
00437   int IsQuad = ForceQuad ? true : Type.isQuad();
00438   switch (Type.getEltType()) {
00439   case NeonTypeFlags::Int8:
00440   case NeonTypeFlags::Poly8:
00441     return shift ? 7 : (8 << IsQuad) - 1;
00442   case NeonTypeFlags::Int16:
00443   case NeonTypeFlags::Poly16:
00444     return shift ? 15 : (4 << IsQuad) - 1;
00445   case NeonTypeFlags::Int32:
00446     return shift ? 31 : (2 << IsQuad) - 1;
00447   case NeonTypeFlags::Int64:
00448   case NeonTypeFlags::Poly64:
00449     return shift ? 63 : (1 << IsQuad) - 1;
00450   case NeonTypeFlags::Poly128:
00451     return shift ? 127 : (1 << IsQuad) - 1;
00452   case NeonTypeFlags::Float16:
00453     assert(!shift && "cannot shift float types!");
00454     return (4 << IsQuad) - 1;
00455   case NeonTypeFlags::Float32:
00456     assert(!shift && "cannot shift float types!");
00457     return (2 << IsQuad) - 1;
00458   case NeonTypeFlags::Float64:
00459     assert(!shift && "cannot shift float types!");
00460     return (1 << IsQuad) - 1;
00461   }
00462   llvm_unreachable("Invalid NeonTypeFlag!");
00463 }
00464 
00465 /// getNeonEltType - Return the QualType corresponding to the elements of
00466 /// the vector type specified by the NeonTypeFlags.  This is used to check
00467 /// the pointer arguments for Neon load/store intrinsics.
00468 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
00469                                bool IsPolyUnsigned, bool IsInt64Long) {
00470   switch (Flags.getEltType()) {
00471   case NeonTypeFlags::Int8:
00472     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
00473   case NeonTypeFlags::Int16:
00474     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
00475   case NeonTypeFlags::Int32:
00476     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
00477   case NeonTypeFlags::Int64:
00478     if (IsInt64Long)
00479       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
00480     else
00481       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
00482                                 : Context.LongLongTy;
00483   case NeonTypeFlags::Poly8:
00484     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
00485   case NeonTypeFlags::Poly16:
00486     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
00487   case NeonTypeFlags::Poly64:
00488     return Context.UnsignedLongTy;
00489   case NeonTypeFlags::Poly128:
00490     break;
00491   case NeonTypeFlags::Float16:
00492     return Context.HalfTy;
00493   case NeonTypeFlags::Float32:
00494     return Context.FloatTy;
00495   case NeonTypeFlags::Float64:
00496     return Context.DoubleTy;
00497   }
00498   llvm_unreachable("Invalid NeonTypeFlag!");
00499 }
00500 
00501 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
00502   llvm::APSInt Result;
00503   uint64_t mask = 0;
00504   unsigned TV = 0;
00505   int PtrArgNum = -1;
00506   bool HasConstPtr = false;
00507   switch (BuiltinID) {
00508 #define GET_NEON_OVERLOAD_CHECK
00509 #include "clang/Basic/arm_neon.inc"
00510 #undef GET_NEON_OVERLOAD_CHECK
00511   }
00512 
00513   // For NEON intrinsics which are overloaded on vector element type, validate
00514   // the immediate which specifies which variant to emit.
00515   unsigned ImmArg = TheCall->getNumArgs()-1;
00516   if (mask) {
00517     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
00518       return true;
00519 
00520     TV = Result.getLimitedValue(64);
00521     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
00522       return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
00523         << TheCall->getArg(ImmArg)->getSourceRange();
00524   }
00525 
00526   if (PtrArgNum >= 0) {
00527     // Check that pointer arguments have the specified type.
00528     Expr *Arg = TheCall->getArg(PtrArgNum);
00529     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
00530       Arg = ICE->getSubExpr();
00531     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
00532     QualType RHSTy = RHS.get()->getType();
00533 
00534     llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
00535     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64;
00536     bool IsInt64Long =
00537         Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
00538     QualType EltTy =
00539         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
00540     if (HasConstPtr)
00541       EltTy = EltTy.withConst();
00542     QualType LHSTy = Context.getPointerType(EltTy);
00543     AssignConvertType ConvTy;
00544     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
00545     if (RHS.isInvalid())
00546       return true;
00547     if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
00548                                  RHS.get(), AA_Assigning))
00549       return true;
00550   }
00551 
00552   // For NEON intrinsics which take an immediate value as part of the
00553   // instruction, range check them here.
00554   unsigned i = 0, l = 0, u = 0;
00555   switch (BuiltinID) {
00556   default:
00557     return false;
00558 #define GET_NEON_IMMEDIATE_CHECK
00559 #include "clang/Basic/arm_neon.inc"
00560 #undef GET_NEON_IMMEDIATE_CHECK
00561   }
00562 
00563   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
00564 }
00565 
00566 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
00567                                         unsigned MaxWidth) {
00568   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
00569           BuiltinID == ARM::BI__builtin_arm_ldaex ||
00570           BuiltinID == ARM::BI__builtin_arm_strex ||
00571           BuiltinID == ARM::BI__builtin_arm_stlex ||
00572           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
00573           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
00574           BuiltinID == AArch64::BI__builtin_arm_strex ||
00575           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
00576          "unexpected ARM builtin");
00577   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
00578                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
00579                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
00580                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
00581 
00582   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
00583 
00584   // Ensure that we have the proper number of arguments.
00585   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
00586     return true;
00587 
00588   // Inspect the pointer argument of the atomic builtin.  This should always be
00589   // a pointer type, whose element is an integral scalar or pointer type.
00590   // Because it is a pointer type, we don't have to worry about any implicit
00591   // casts here.
00592   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
00593   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
00594   if (PointerArgRes.isInvalid())
00595     return true;
00596   PointerArg = PointerArgRes.get();
00597 
00598   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
00599   if (!pointerType) {
00600     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
00601       << PointerArg->getType() << PointerArg->getSourceRange();
00602     return true;
00603   }
00604 
00605   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
00606   // task is to insert the appropriate casts into the AST. First work out just
00607   // what the appropriate type is.
00608   QualType ValType = pointerType->getPointeeType();
00609   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
00610   if (IsLdrex)
00611     AddrType.addConst();
00612 
00613   // Issue a warning if the cast is dodgy.
00614   CastKind CastNeeded = CK_NoOp;
00615   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
00616     CastNeeded = CK_BitCast;
00617     Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
00618       << PointerArg->getType()
00619       << Context.getPointerType(AddrType)
00620       << AA_Passing << PointerArg->getSourceRange();
00621   }
00622 
00623   // Finally, do the cast and replace the argument with the corrected version.
00624   AddrType = Context.getPointerType(AddrType);
00625   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
00626   if (PointerArgRes.isInvalid())
00627     return true;
00628   PointerArg = PointerArgRes.get();
00629 
00630   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
00631 
00632   // In general, we allow ints, floats and pointers to be loaded and stored.
00633   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
00634       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
00635     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
00636       << PointerArg->getType() << PointerArg->getSourceRange();
00637     return true;
00638   }
00639 
00640   // But ARM doesn't have instructions to deal with 128-bit versions.
00641   if (Context.getTypeSize(ValType) > MaxWidth) {
00642     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
00643     Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
00644       << PointerArg->getType() << PointerArg->getSourceRange();
00645     return true;
00646   }
00647 
00648   switch (ValType.getObjCLifetime()) {
00649   case Qualifiers::OCL_None:
00650   case Qualifiers::OCL_ExplicitNone:
00651     // okay
00652     break;
00653 
00654   case Qualifiers::OCL_Weak:
00655   case Qualifiers::OCL_Strong:
00656   case Qualifiers::OCL_Autoreleasing:
00657     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
00658       << ValType << PointerArg->getSourceRange();
00659     return true;
00660   }
00661 
00662 
00663   if (IsLdrex) {
00664     TheCall->setType(ValType);
00665     return false;
00666   }
00667 
00668   // Initialize the argument to be stored.
00669   ExprResult ValArg = TheCall->getArg(0);
00670   InitializedEntity Entity = InitializedEntity::InitializeParameter(
00671       Context, ValType, /*consume*/ false);
00672   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
00673   if (ValArg.isInvalid())
00674     return true;
00675   TheCall->setArg(0, ValArg.get());
00676 
00677   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
00678   // but the custom checker bypasses all default analysis.
00679   TheCall->setType(Context.IntTy);
00680   return false;
00681 }
00682 
00683 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
00684   llvm::APSInt Result;
00685 
00686   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
00687       BuiltinID == ARM::BI__builtin_arm_ldaex ||
00688       BuiltinID == ARM::BI__builtin_arm_strex ||
00689       BuiltinID == ARM::BI__builtin_arm_stlex) {
00690     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
00691   }
00692 
00693   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
00694     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
00695       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
00696   }
00697 
00698   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
00699     return true;
00700 
00701   // For intrinsics which take an immediate value as part of the instruction,
00702   // range check them here.
00703   unsigned i = 0, l = 0, u = 0;
00704   switch (BuiltinID) {
00705   default: return false;
00706   case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
00707   case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
00708   case ARM::BI__builtin_arm_vcvtr_f:
00709   case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
00710   case ARM::BI__builtin_arm_dmb:
00711   case ARM::BI__builtin_arm_dsb:
00712   case ARM::BI__builtin_arm_isb:
00713   case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
00714   }
00715 
00716   // FIXME: VFP Intrinsics should error if VFP not present.
00717   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
00718 }
00719 
00720 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
00721                                          CallExpr *TheCall) {
00722   llvm::APSInt Result;
00723 
00724   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
00725       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
00726       BuiltinID == AArch64::BI__builtin_arm_strex ||
00727       BuiltinID == AArch64::BI__builtin_arm_stlex) {
00728     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
00729   }
00730 
00731   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
00732     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
00733       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
00734       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
00735       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
00736   }
00737 
00738   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
00739     return true;
00740 
00741   // For intrinsics which take an immediate value as part of the instruction,
00742   // range check them here.
00743   unsigned i = 0, l = 0, u = 0;
00744   switch (BuiltinID) {
00745   default: return false;
00746   case AArch64::BI__builtin_arm_dmb:
00747   case AArch64::BI__builtin_arm_dsb:
00748   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
00749   }
00750 
00751   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
00752 }
00753 
00754 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
00755   unsigned i = 0, l = 0, u = 0;
00756   switch (BuiltinID) {
00757   default: return false;
00758   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
00759   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
00760   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
00761   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
00762   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
00763   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
00764   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
00765   }
00766 
00767   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
00768 }
00769 
00770 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
00771   switch (BuiltinID) {
00772   case X86::BI_mm_prefetch:
00773     // This is declared to take (const char*, int)
00774     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3);
00775   }
00776   return false;
00777 }
00778 
00779 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
00780 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
00781 /// Returns true when the format fits the function and the FormatStringInfo has
00782 /// been populated.
00783 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
00784                                FormatStringInfo *FSI) {
00785   FSI->HasVAListArg = Format->getFirstArg() == 0;
00786   FSI->FormatIdx = Format->getFormatIdx() - 1;
00787   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
00788 
00789   // The way the format attribute works in GCC, the implicit this argument
00790   // of member functions is counted. However, it doesn't appear in our own
00791   // lists, so decrement format_idx in that case.
00792   if (IsCXXMember) {
00793     if(FSI->FormatIdx == 0)
00794       return false;
00795     --FSI->FormatIdx;
00796     if (FSI->FirstDataArg != 0)
00797       --FSI->FirstDataArg;
00798   }
00799   return true;
00800 }
00801 
00802 /// Checks if a the given expression evaluates to null.
00803 ///
00804 /// \brief Returns true if the value evaluates to null.
00805 static bool CheckNonNullExpr(Sema &S,
00806                              const Expr *Expr) {
00807   // As a special case, transparent unions initialized with zero are
00808   // considered null for the purposes of the nonnull attribute.
00809   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
00810     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
00811       if (const CompoundLiteralExpr *CLE =
00812           dyn_cast<CompoundLiteralExpr>(Expr))
00813         if (const InitListExpr *ILE =
00814             dyn_cast<InitListExpr>(CLE->getInitializer()))
00815           Expr = ILE->getInit(0);
00816   }
00817 
00818   bool Result;
00819   return (!Expr->isValueDependent() &&
00820           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
00821           !Result);
00822 }
00823 
00824 static void CheckNonNullArgument(Sema &S,
00825                                  const Expr *ArgExpr,
00826                                  SourceLocation CallSiteLoc) {
00827   if (CheckNonNullExpr(S, ArgExpr))
00828     S.Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
00829 }
00830 
00831 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
00832   FormatStringInfo FSI;
00833   if ((GetFormatStringType(Format) == FST_NSString) &&
00834       getFormatStringInfo(Format, false, &FSI)) {
00835     Idx = FSI.FormatIdx;
00836     return true;
00837   }
00838   return false;
00839 }
00840 /// \brief Diagnose use of %s directive in an NSString which is being passed
00841 /// as formatting string to formatting method.
00842 static void
00843 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
00844                                         const NamedDecl *FDecl,
00845                                         Expr **Args,
00846                                         unsigned NumArgs) {
00847   unsigned Idx = 0;
00848   bool Format = false;
00849   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
00850   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
00851     Idx = 2;
00852     Format = true;
00853   }
00854   else
00855     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
00856       if (S.GetFormatNSStringIdx(I, Idx)) {
00857         Format = true;
00858         break;
00859       }
00860     }
00861   if (!Format || NumArgs <= Idx)
00862     return;
00863   const Expr *FormatExpr = Args[Idx];
00864   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
00865     FormatExpr = CSCE->getSubExpr();
00866   const StringLiteral *FormatString;
00867   if (const ObjCStringLiteral *OSL =
00868       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
00869     FormatString = OSL->getString();
00870   else
00871     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
00872   if (!FormatString)
00873     return;
00874   if (S.FormatStringHasSArg(FormatString)) {
00875     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
00876       << "%s" << 1 << 1;
00877     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
00878       << FDecl->getDeclName();
00879   }
00880 }
00881 
00882 static void CheckNonNullArguments(Sema &S,
00883                                   const NamedDecl *FDecl,
00884                                   ArrayRef<const Expr *> Args,
00885                                   SourceLocation CallSiteLoc) {
00886   // Check the attributes attached to the method/function itself.
00887   llvm::SmallBitVector NonNullArgs;
00888   for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
00889     if (!NonNull->args_size()) {
00890       // Easy case: all pointer arguments are nonnull.
00891       for (const auto *Arg : Args)
00892         if (S.isValidPointerAttrType(Arg->getType()))
00893           CheckNonNullArgument(S, Arg, CallSiteLoc);
00894       return;
00895     }
00896 
00897     for (unsigned Val : NonNull->args()) {
00898       if (Val >= Args.size())
00899         continue;
00900       if (NonNullArgs.empty())
00901         NonNullArgs.resize(Args.size());
00902       NonNullArgs.set(Val);
00903     }
00904   }
00905 
00906   // Check the attributes on the parameters.
00907   ArrayRef<ParmVarDecl*> parms;
00908   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
00909     parms = FD->parameters();
00910   else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(FDecl))
00911     parms = MD->parameters();
00912 
00913   unsigned ArgIndex = 0;
00914   for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
00915        I != E; ++I, ++ArgIndex) {
00916     const ParmVarDecl *PVD = *I;
00917     if (PVD->hasAttr<NonNullAttr>() ||
00918         (ArgIndex < NonNullArgs.size() && NonNullArgs[ArgIndex]))
00919       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
00920   }
00921 
00922   // In case this is a variadic call, check any remaining arguments.
00923   for (/**/; ArgIndex < NonNullArgs.size(); ++ArgIndex)
00924     if (NonNullArgs[ArgIndex])
00925       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
00926 }
00927 
00928 /// Handles the checks for format strings, non-POD arguments to vararg
00929 /// functions, and NULL arguments passed to non-NULL parameters.
00930 void Sema::checkCall(NamedDecl *FDecl, ArrayRef<const Expr *> Args,
00931                      unsigned NumParams, bool IsMemberFunction,
00932                      SourceLocation Loc, SourceRange Range,
00933                      VariadicCallType CallType) {
00934   // FIXME: We should check as much as we can in the template definition.
00935   if (CurContext->isDependentContext())
00936     return;
00937 
00938   // Printf and scanf checking.
00939   llvm::SmallBitVector CheckedVarArgs;
00940   if (FDecl) {
00941     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
00942       // Only create vector if there are format attributes.
00943       CheckedVarArgs.resize(Args.size());
00944 
00945       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
00946                            CheckedVarArgs);
00947     }
00948   }
00949 
00950   // Refuse POD arguments that weren't caught by the format string
00951   // checks above.
00952   if (CallType != VariadicDoesNotApply) {
00953     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
00954       // Args[ArgIdx] can be null in malformed code.
00955       if (const Expr *Arg = Args[ArgIdx]) {
00956         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
00957           checkVariadicArgument(Arg, CallType);
00958       }
00959     }
00960   }
00961 
00962   if (FDecl) {
00963     CheckNonNullArguments(*this, FDecl, Args, Loc);
00964 
00965     // Type safety checking.
00966     for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
00967       CheckArgumentWithTypeTag(I, Args.data());
00968   }
00969 }
00970 
00971 /// CheckConstructorCall - Check a constructor call for correctness and safety
00972 /// properties not enforced by the C type system.
00973 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
00974                                 ArrayRef<const Expr *> Args,
00975                                 const FunctionProtoType *Proto,
00976                                 SourceLocation Loc) {
00977   VariadicCallType CallType =
00978     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
00979   checkCall(FDecl, Args, Proto->getNumParams(),
00980             /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
00981 }
00982 
00983 /// CheckFunctionCall - Check a direct function call for various correctness
00984 /// and safety properties not strictly enforced by the C type system.
00985 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
00986                              const FunctionProtoType *Proto) {
00987   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
00988                               isa<CXXMethodDecl>(FDecl);
00989   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
00990                           IsMemberOperatorCall;
00991   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
00992                                                   TheCall->getCallee());
00993   unsigned NumParams = Proto ? Proto->getNumParams() : 0;
00994   Expr** Args = TheCall->getArgs();
00995   unsigned NumArgs = TheCall->getNumArgs();
00996   if (IsMemberOperatorCall) {
00997     // If this is a call to a member operator, hide the first argument
00998     // from checkCall.
00999     // FIXME: Our choice of AST representation here is less than ideal.
01000     ++Args;
01001     --NumArgs;
01002   }
01003   checkCall(FDecl, llvm::makeArrayRef(Args, NumArgs), NumParams,
01004             IsMemberFunction, TheCall->getRParenLoc(),
01005             TheCall->getCallee()->getSourceRange(), CallType);
01006 
01007   IdentifierInfo *FnInfo = FDecl->getIdentifier();
01008   // None of the checks below are needed for functions that don't have
01009   // simple names (e.g., C++ conversion functions).
01010   if (!FnInfo)
01011     return false;
01012 
01013   CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
01014   if (getLangOpts().ObjC1)
01015     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
01016 
01017   unsigned CMId = FDecl->getMemoryFunctionKind();
01018   if (CMId == 0)
01019     return false;
01020 
01021   // Handle memory setting and copying functions.
01022   if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
01023     CheckStrlcpycatArguments(TheCall, FnInfo);
01024   else if (CMId == Builtin::BIstrncat)
01025     CheckStrncatArguments(TheCall, FnInfo);
01026   else
01027     CheckMemaccessArguments(TheCall, CMId, FnInfo);
01028 
01029   return false;
01030 }
01031 
01032 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 
01033                                ArrayRef<const Expr *> Args) {
01034   VariadicCallType CallType =
01035       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
01036 
01037   checkCall(Method, Args, Method->param_size(),
01038             /*IsMemberFunction=*/false,
01039             lbrac, Method->getSourceRange(), CallType);
01040 
01041   return false;
01042 }
01043 
01044 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
01045                             const FunctionProtoType *Proto) {
01046   const VarDecl *V = dyn_cast<VarDecl>(NDecl);
01047   if (!V)
01048     return false;
01049 
01050   QualType Ty = V->getType();
01051   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType())
01052     return false;
01053 
01054   VariadicCallType CallType;
01055   if (!Proto || !Proto->isVariadic()) {
01056     CallType = VariadicDoesNotApply;
01057   } else if (Ty->isBlockPointerType()) {
01058     CallType = VariadicBlock;
01059   } else { // Ty->isFunctionPointerType()
01060     CallType = VariadicFunction;
01061   }
01062   unsigned NumParams = Proto ? Proto->getNumParams() : 0;
01063 
01064   checkCall(NDecl, llvm::makeArrayRef(TheCall->getArgs(),
01065                                       TheCall->getNumArgs()),
01066             NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
01067             TheCall->getCallee()->getSourceRange(), CallType);
01068 
01069   return false;
01070 }
01071 
01072 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
01073 /// such as function pointers returned from functions.
01074 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
01075   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
01076                                                   TheCall->getCallee());
01077   unsigned NumParams = Proto ? Proto->getNumParams() : 0;
01078 
01079   checkCall(/*FDecl=*/nullptr,
01080             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
01081             NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
01082             TheCall->getCallee()->getSourceRange(), CallType);
01083 
01084   return false;
01085 }
01086 
01087 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
01088   if (Ordering < AtomicExpr::AO_ABI_memory_order_relaxed ||
01089       Ordering > AtomicExpr::AO_ABI_memory_order_seq_cst)
01090     return false;
01091 
01092   switch (Op) {
01093   case AtomicExpr::AO__c11_atomic_init:
01094     llvm_unreachable("There is no ordering argument for an init");
01095 
01096   case AtomicExpr::AO__c11_atomic_load:
01097   case AtomicExpr::AO__atomic_load_n:
01098   case AtomicExpr::AO__atomic_load:
01099     return Ordering != AtomicExpr::AO_ABI_memory_order_release &&
01100            Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
01101 
01102   case AtomicExpr::AO__c11_atomic_store:
01103   case AtomicExpr::AO__atomic_store:
01104   case AtomicExpr::AO__atomic_store_n:
01105     return Ordering != AtomicExpr::AO_ABI_memory_order_consume &&
01106            Ordering != AtomicExpr::AO_ABI_memory_order_acquire &&
01107            Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
01108 
01109   default:
01110     return true;
01111   }
01112 }
01113 
01114 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
01115                                          AtomicExpr::AtomicOp Op) {
01116   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
01117   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
01118 
01119   // All these operations take one of the following forms:
01120   enum {
01121     // C    __c11_atomic_init(A *, C)
01122     Init,
01123     // C    __c11_atomic_load(A *, int)
01124     Load,
01125     // void __atomic_load(A *, CP, int)
01126     Copy,
01127     // C    __c11_atomic_add(A *, M, int)
01128     Arithmetic,
01129     // C    __atomic_exchange_n(A *, CP, int)
01130     Xchg,
01131     // void __atomic_exchange(A *, C *, CP, int)
01132     GNUXchg,
01133     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
01134     C11CmpXchg,
01135     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
01136     GNUCmpXchg
01137   } Form = Init;
01138   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
01139   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
01140   // where:
01141   //   C is an appropriate type,
01142   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
01143   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
01144   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
01145   //   the int parameters are for orderings.
01146 
01147   assert(AtomicExpr::AO__c11_atomic_init == 0 &&
01148          AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
01149          && "need to update code for modified C11 atomics");
01150   bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
01151                Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
01152   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
01153              Op == AtomicExpr::AO__atomic_store_n ||
01154              Op == AtomicExpr::AO__atomic_exchange_n ||
01155              Op == AtomicExpr::AO__atomic_compare_exchange_n;
01156   bool IsAddSub = false;
01157 
01158   switch (Op) {
01159   case AtomicExpr::AO__c11_atomic_init:
01160     Form = Init;
01161     break;
01162 
01163   case AtomicExpr::AO__c11_atomic_load:
01164   case AtomicExpr::AO__atomic_load_n:
01165     Form = Load;
01166     break;
01167 
01168   case AtomicExpr::AO__c11_atomic_store:
01169   case AtomicExpr::AO__atomic_load:
01170   case AtomicExpr::AO__atomic_store:
01171   case AtomicExpr::AO__atomic_store_n:
01172     Form = Copy;
01173     break;
01174 
01175   case AtomicExpr::AO__c11_atomic_fetch_add:
01176   case AtomicExpr::AO__c11_atomic_fetch_sub:
01177   case AtomicExpr::AO__atomic_fetch_add:
01178   case AtomicExpr::AO__atomic_fetch_sub:
01179   case AtomicExpr::AO__atomic_add_fetch:
01180   case AtomicExpr::AO__atomic_sub_fetch:
01181     IsAddSub = true;
01182     // Fall through.
01183   case AtomicExpr::AO__c11_atomic_fetch_and:
01184   case AtomicExpr::AO__c11_atomic_fetch_or:
01185   case AtomicExpr::AO__c11_atomic_fetch_xor:
01186   case AtomicExpr::AO__atomic_fetch_and:
01187   case AtomicExpr::AO__atomic_fetch_or:
01188   case AtomicExpr::AO__atomic_fetch_xor:
01189   case AtomicExpr::AO__atomic_fetch_nand:
01190   case AtomicExpr::AO__atomic_and_fetch:
01191   case AtomicExpr::AO__atomic_or_fetch:
01192   case AtomicExpr::AO__atomic_xor_fetch:
01193   case AtomicExpr::AO__atomic_nand_fetch:
01194     Form = Arithmetic;
01195     break;
01196 
01197   case AtomicExpr::AO__c11_atomic_exchange:
01198   case AtomicExpr::AO__atomic_exchange_n:
01199     Form = Xchg;
01200     break;
01201 
01202   case AtomicExpr::AO__atomic_exchange:
01203     Form = GNUXchg;
01204     break;
01205 
01206   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
01207   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
01208     Form = C11CmpXchg;
01209     break;
01210 
01211   case AtomicExpr::AO__atomic_compare_exchange:
01212   case AtomicExpr::AO__atomic_compare_exchange_n:
01213     Form = GNUCmpXchg;
01214     break;
01215   }
01216 
01217   // Check we have the right number of arguments.
01218   if (TheCall->getNumArgs() < NumArgs[Form]) {
01219     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
01220       << 0 << NumArgs[Form] << TheCall->getNumArgs()
01221       << TheCall->getCallee()->getSourceRange();
01222     return ExprError();
01223   } else if (TheCall->getNumArgs() > NumArgs[Form]) {
01224     Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
01225          diag::err_typecheck_call_too_many_args)
01226       << 0 << NumArgs[Form] << TheCall->getNumArgs()
01227       << TheCall->getCallee()->getSourceRange();
01228     return ExprError();
01229   }
01230 
01231   // Inspect the first argument of the atomic operation.
01232   Expr *Ptr = TheCall->getArg(0);
01233   Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
01234   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
01235   if (!pointerType) {
01236     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
01237       << Ptr->getType() << Ptr->getSourceRange();
01238     return ExprError();
01239   }
01240 
01241   // For a __c11 builtin, this should be a pointer to an _Atomic type.
01242   QualType AtomTy = pointerType->getPointeeType(); // 'A'
01243   QualType ValType = AtomTy; // 'C'
01244   if (IsC11) {
01245     if (!AtomTy->isAtomicType()) {
01246       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
01247         << Ptr->getType() << Ptr->getSourceRange();
01248       return ExprError();
01249     }
01250     if (AtomTy.isConstQualified()) {
01251       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
01252         << Ptr->getType() << Ptr->getSourceRange();
01253       return ExprError();
01254     }
01255     ValType = AtomTy->getAs<AtomicType>()->getValueType();
01256   }
01257 
01258   // For an arithmetic operation, the implied arithmetic must be well-formed.
01259   if (Form == Arithmetic) {
01260     // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
01261     if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
01262       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
01263         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
01264       return ExprError();
01265     }
01266     if (!IsAddSub && !ValType->isIntegerType()) {
01267       Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
01268         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
01269       return ExprError();
01270     }
01271   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
01272     // For __atomic_*_n operations, the value type must be a scalar integral or
01273     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
01274     Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
01275       << IsC11 << Ptr->getType() << Ptr->getSourceRange();
01276     return ExprError();
01277   }
01278 
01279   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
01280       !AtomTy->isScalarType()) {
01281     // For GNU atomics, require a trivially-copyable type. This is not part of
01282     // the GNU atomics specification, but we enforce it for sanity.
01283     Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
01284       << Ptr->getType() << Ptr->getSourceRange();
01285     return ExprError();
01286   }
01287 
01288   // FIXME: For any builtin other than a load, the ValType must not be
01289   // const-qualified.
01290 
01291   switch (ValType.getObjCLifetime()) {
01292   case Qualifiers::OCL_None:
01293   case Qualifiers::OCL_ExplicitNone:
01294     // okay
01295     break;
01296 
01297   case Qualifiers::OCL_Weak:
01298   case Qualifiers::OCL_Strong:
01299   case Qualifiers::OCL_Autoreleasing:
01300     // FIXME: Can this happen? By this point, ValType should be known
01301     // to be trivially copyable.
01302     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
01303       << ValType << Ptr->getSourceRange();
01304     return ExprError();
01305   }
01306 
01307   QualType ResultType = ValType;
01308   if (Form == Copy || Form == GNUXchg || Form == Init)
01309     ResultType = Context.VoidTy;
01310   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
01311     ResultType = Context.BoolTy;
01312 
01313   // The type of a parameter passed 'by value'. In the GNU atomics, such
01314   // arguments are actually passed as pointers.
01315   QualType ByValType = ValType; // 'CP'
01316   if (!IsC11 && !IsN)
01317     ByValType = Ptr->getType();
01318 
01319   // The first argument --- the pointer --- has a fixed type; we
01320   // deduce the types of the rest of the arguments accordingly.  Walk
01321   // the remaining arguments, converting them to the deduced value type.
01322   for (unsigned i = 1; i != NumArgs[Form]; ++i) {
01323     QualType Ty;
01324     if (i < NumVals[Form] + 1) {
01325       switch (i) {
01326       case 1:
01327         // The second argument is the non-atomic operand. For arithmetic, this
01328         // is always passed by value, and for a compare_exchange it is always
01329         // passed by address. For the rest, GNU uses by-address and C11 uses
01330         // by-value.
01331         assert(Form != Load);
01332         if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
01333           Ty = ValType;
01334         else if (Form == Copy || Form == Xchg)
01335           Ty = ByValType;
01336         else if (Form == Arithmetic)
01337           Ty = Context.getPointerDiffType();
01338         else
01339           Ty = Context.getPointerType(ValType.getUnqualifiedType());
01340         break;
01341       case 2:
01342         // The third argument to compare_exchange / GNU exchange is a
01343         // (pointer to a) desired value.
01344         Ty = ByValType;
01345         break;
01346       case 3:
01347         // The fourth argument to GNU compare_exchange is a 'weak' flag.
01348         Ty = Context.BoolTy;
01349         break;
01350       }
01351     } else {
01352       // The order(s) are always converted to int.
01353       Ty = Context.IntTy;
01354     }
01355 
01356     InitializedEntity Entity =
01357         InitializedEntity::InitializeParameter(Context, Ty, false);
01358     ExprResult Arg = TheCall->getArg(i);
01359     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
01360     if (Arg.isInvalid())
01361       return true;
01362     TheCall->setArg(i, Arg.get());
01363   }
01364 
01365   // Permute the arguments into a 'consistent' order.
01366   SmallVector<Expr*, 5> SubExprs;
01367   SubExprs.push_back(Ptr);
01368   switch (Form) {
01369   case Init:
01370     // Note, AtomicExpr::getVal1() has a special case for this atomic.
01371     SubExprs.push_back(TheCall->getArg(1)); // Val1
01372     break;
01373   case Load:
01374     SubExprs.push_back(TheCall->getArg(1)); // Order
01375     break;
01376   case Copy:
01377   case Arithmetic:
01378   case Xchg:
01379     SubExprs.push_back(TheCall->getArg(2)); // Order
01380     SubExprs.push_back(TheCall->getArg(1)); // Val1
01381     break;
01382   case GNUXchg:
01383     // Note, AtomicExpr::getVal2() has a special case for this atomic.
01384     SubExprs.push_back(TheCall->getArg(3)); // Order
01385     SubExprs.push_back(TheCall->getArg(1)); // Val1
01386     SubExprs.push_back(TheCall->getArg(2)); // Val2
01387     break;
01388   case C11CmpXchg:
01389     SubExprs.push_back(TheCall->getArg(3)); // Order
01390     SubExprs.push_back(TheCall->getArg(1)); // Val1
01391     SubExprs.push_back(TheCall->getArg(4)); // OrderFail
01392     SubExprs.push_back(TheCall->getArg(2)); // Val2
01393     break;
01394   case GNUCmpXchg:
01395     SubExprs.push_back(TheCall->getArg(4)); // Order
01396     SubExprs.push_back(TheCall->getArg(1)); // Val1
01397     SubExprs.push_back(TheCall->getArg(5)); // OrderFail
01398     SubExprs.push_back(TheCall->getArg(2)); // Val2
01399     SubExprs.push_back(TheCall->getArg(3)); // Weak
01400     break;
01401   }
01402 
01403   if (SubExprs.size() >= 2 && Form != Init) {
01404     llvm::APSInt Result(32);
01405     if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
01406         !isValidOrderingForOp(Result.getSExtValue(), Op))
01407       Diag(SubExprs[1]->getLocStart(),
01408            diag::warn_atomic_op_has_invalid_memory_order)
01409           << SubExprs[1]->getSourceRange();
01410   }
01411 
01412   AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
01413                                             SubExprs, ResultType, Op,
01414                                             TheCall->getRParenLoc());
01415   
01416   if ((Op == AtomicExpr::AO__c11_atomic_load ||
01417        (Op == AtomicExpr::AO__c11_atomic_store)) &&
01418       Context.AtomicUsesUnsupportedLibcall(AE))
01419     Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
01420     ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
01421 
01422   return AE;
01423 }
01424 
01425 
01426 /// checkBuiltinArgument - Given a call to a builtin function, perform
01427 /// normal type-checking on the given argument, updating the call in
01428 /// place.  This is useful when a builtin function requires custom
01429 /// type-checking for some of its arguments but not necessarily all of
01430 /// them.
01431 ///
01432 /// Returns true on error.
01433 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
01434   FunctionDecl *Fn = E->getDirectCallee();
01435   assert(Fn && "builtin call without direct callee!");
01436 
01437   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
01438   InitializedEntity Entity =
01439     InitializedEntity::InitializeParameter(S.Context, Param);
01440 
01441   ExprResult Arg = E->getArg(0);
01442   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
01443   if (Arg.isInvalid())
01444     return true;
01445 
01446   E->setArg(ArgIndex, Arg.get());
01447   return false;
01448 }
01449 
01450 /// SemaBuiltinAtomicOverloaded - We have a call to a function like
01451 /// __sync_fetch_and_add, which is an overloaded function based on the pointer
01452 /// type of its first argument.  The main ActOnCallExpr routines have already
01453 /// promoted the types of arguments because all of these calls are prototyped as
01454 /// void(...).
01455 ///
01456 /// This function goes through and does final semantic checking for these
01457 /// builtins,
01458 ExprResult
01459 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
01460   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
01461   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
01462   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
01463 
01464   // Ensure that we have at least one argument to do type inference from.
01465   if (TheCall->getNumArgs() < 1) {
01466     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
01467       << 0 << 1 << TheCall->getNumArgs()
01468       << TheCall->getCallee()->getSourceRange();
01469     return ExprError();
01470   }
01471 
01472   // Inspect the first argument of the atomic builtin.  This should always be
01473   // a pointer type, whose element is an integral scalar or pointer type.
01474   // Because it is a pointer type, we don't have to worry about any implicit
01475   // casts here.
01476   // FIXME: We don't allow floating point scalars as input.
01477   Expr *FirstArg = TheCall->getArg(0);
01478   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
01479   if (FirstArgResult.isInvalid())
01480     return ExprError();
01481   FirstArg = FirstArgResult.get();
01482   TheCall->setArg(0, FirstArg);
01483 
01484   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
01485   if (!pointerType) {
01486     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
01487       << FirstArg->getType() << FirstArg->getSourceRange();
01488     return ExprError();
01489   }
01490 
01491   QualType ValType = pointerType->getPointeeType();
01492   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
01493       !ValType->isBlockPointerType()) {
01494     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
01495       << FirstArg->getType() << FirstArg->getSourceRange();
01496     return ExprError();
01497   }
01498 
01499   switch (ValType.getObjCLifetime()) {
01500   case Qualifiers::OCL_None:
01501   case Qualifiers::OCL_ExplicitNone:
01502     // okay
01503     break;
01504 
01505   case Qualifiers::OCL_Weak:
01506   case Qualifiers::OCL_Strong:
01507   case Qualifiers::OCL_Autoreleasing:
01508     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
01509       << ValType << FirstArg->getSourceRange();
01510     return ExprError();
01511   }
01512 
01513   // Strip any qualifiers off ValType.
01514   ValType = ValType.getUnqualifiedType();
01515 
01516   // The majority of builtins return a value, but a few have special return
01517   // types, so allow them to override appropriately below.
01518   QualType ResultType = ValType;
01519 
01520   // We need to figure out which concrete builtin this maps onto.  For example,
01521   // __sync_fetch_and_add with a 2 byte object turns into
01522   // __sync_fetch_and_add_2.
01523 #define BUILTIN_ROW(x) \
01524   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
01525     Builtin::BI##x##_8, Builtin::BI##x##_16 }
01526 
01527   static const unsigned BuiltinIndices[][5] = {
01528     BUILTIN_ROW(__sync_fetch_and_add),
01529     BUILTIN_ROW(__sync_fetch_and_sub),
01530     BUILTIN_ROW(__sync_fetch_and_or),
01531     BUILTIN_ROW(__sync_fetch_and_and),
01532     BUILTIN_ROW(__sync_fetch_and_xor),
01533     BUILTIN_ROW(__sync_fetch_and_nand),
01534 
01535     BUILTIN_ROW(__sync_add_and_fetch),
01536     BUILTIN_ROW(__sync_sub_and_fetch),
01537     BUILTIN_ROW(__sync_and_and_fetch),
01538     BUILTIN_ROW(__sync_or_and_fetch),
01539     BUILTIN_ROW(__sync_xor_and_fetch),
01540     BUILTIN_ROW(__sync_nand_and_fetch),
01541 
01542     BUILTIN_ROW(__sync_val_compare_and_swap),
01543     BUILTIN_ROW(__sync_bool_compare_and_swap),
01544     BUILTIN_ROW(__sync_lock_test_and_set),
01545     BUILTIN_ROW(__sync_lock_release),
01546     BUILTIN_ROW(__sync_swap)
01547   };
01548 #undef BUILTIN_ROW
01549 
01550   // Determine the index of the size.
01551   unsigned SizeIndex;
01552   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
01553   case 1: SizeIndex = 0; break;
01554   case 2: SizeIndex = 1; break;
01555   case 4: SizeIndex = 2; break;
01556   case 8: SizeIndex = 3; break;
01557   case 16: SizeIndex = 4; break;
01558   default:
01559     Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
01560       << FirstArg->getType() << FirstArg->getSourceRange();
01561     return ExprError();
01562   }
01563 
01564   // Each of these builtins has one pointer argument, followed by some number of
01565   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
01566   // that we ignore.  Find out which row of BuiltinIndices to read from as well
01567   // as the number of fixed args.
01568   unsigned BuiltinID = FDecl->getBuiltinID();
01569   unsigned BuiltinIndex, NumFixed = 1;
01570   bool WarnAboutSemanticsChange = false;
01571   switch (BuiltinID) {
01572   default: llvm_unreachable("Unknown overloaded atomic builtin!");
01573   case Builtin::BI__sync_fetch_and_add: 
01574   case Builtin::BI__sync_fetch_and_add_1:
01575   case Builtin::BI__sync_fetch_and_add_2:
01576   case Builtin::BI__sync_fetch_and_add_4:
01577   case Builtin::BI__sync_fetch_and_add_8:
01578   case Builtin::BI__sync_fetch_and_add_16:
01579     BuiltinIndex = 0; 
01580     break;
01581       
01582   case Builtin::BI__sync_fetch_and_sub: 
01583   case Builtin::BI__sync_fetch_and_sub_1:
01584   case Builtin::BI__sync_fetch_and_sub_2:
01585   case Builtin::BI__sync_fetch_and_sub_4:
01586   case Builtin::BI__sync_fetch_and_sub_8:
01587   case Builtin::BI__sync_fetch_and_sub_16:
01588     BuiltinIndex = 1; 
01589     break;
01590       
01591   case Builtin::BI__sync_fetch_and_or:  
01592   case Builtin::BI__sync_fetch_and_or_1:
01593   case Builtin::BI__sync_fetch_and_or_2:
01594   case Builtin::BI__sync_fetch_and_or_4:
01595   case Builtin::BI__sync_fetch_and_or_8:
01596   case Builtin::BI__sync_fetch_and_or_16:
01597     BuiltinIndex = 2; 
01598     break;
01599       
01600   case Builtin::BI__sync_fetch_and_and: 
01601   case Builtin::BI__sync_fetch_and_and_1:
01602   case Builtin::BI__sync_fetch_and_and_2:
01603   case Builtin::BI__sync_fetch_and_and_4:
01604   case Builtin::BI__sync_fetch_and_and_8:
01605   case Builtin::BI__sync_fetch_and_and_16:
01606     BuiltinIndex = 3; 
01607     break;
01608 
01609   case Builtin::BI__sync_fetch_and_xor: 
01610   case Builtin::BI__sync_fetch_and_xor_1:
01611   case Builtin::BI__sync_fetch_and_xor_2:
01612   case Builtin::BI__sync_fetch_and_xor_4:
01613   case Builtin::BI__sync_fetch_and_xor_8:
01614   case Builtin::BI__sync_fetch_and_xor_16:
01615     BuiltinIndex = 4; 
01616     break;
01617 
01618   case Builtin::BI__sync_fetch_and_nand: 
01619   case Builtin::BI__sync_fetch_and_nand_1:
01620   case Builtin::BI__sync_fetch_and_nand_2:
01621   case Builtin::BI__sync_fetch_and_nand_4:
01622   case Builtin::BI__sync_fetch_and_nand_8:
01623   case Builtin::BI__sync_fetch_and_nand_16:
01624     BuiltinIndex = 5;
01625     WarnAboutSemanticsChange = true;
01626     break;
01627 
01628   case Builtin::BI__sync_add_and_fetch: 
01629   case Builtin::BI__sync_add_and_fetch_1:
01630   case Builtin::BI__sync_add_and_fetch_2:
01631   case Builtin::BI__sync_add_and_fetch_4:
01632   case Builtin::BI__sync_add_and_fetch_8:
01633   case Builtin::BI__sync_add_and_fetch_16:
01634     BuiltinIndex = 6; 
01635     break;
01636       
01637   case Builtin::BI__sync_sub_and_fetch: 
01638   case Builtin::BI__sync_sub_and_fetch_1:
01639   case Builtin::BI__sync_sub_and_fetch_2:
01640   case Builtin::BI__sync_sub_and_fetch_4:
01641   case Builtin::BI__sync_sub_and_fetch_8:
01642   case Builtin::BI__sync_sub_and_fetch_16:
01643     BuiltinIndex = 7; 
01644     break;
01645       
01646   case Builtin::BI__sync_and_and_fetch: 
01647   case Builtin::BI__sync_and_and_fetch_1:
01648   case Builtin::BI__sync_and_and_fetch_2:
01649   case Builtin::BI__sync_and_and_fetch_4:
01650   case Builtin::BI__sync_and_and_fetch_8:
01651   case Builtin::BI__sync_and_and_fetch_16:
01652     BuiltinIndex = 8; 
01653     break;
01654       
01655   case Builtin::BI__sync_or_and_fetch:  
01656   case Builtin::BI__sync_or_and_fetch_1:
01657   case Builtin::BI__sync_or_and_fetch_2:
01658   case Builtin::BI__sync_or_and_fetch_4:
01659   case Builtin::BI__sync_or_and_fetch_8:
01660   case Builtin::BI__sync_or_and_fetch_16:
01661     BuiltinIndex = 9; 
01662     break;
01663       
01664   case Builtin::BI__sync_xor_and_fetch: 
01665   case Builtin::BI__sync_xor_and_fetch_1:
01666   case Builtin::BI__sync_xor_and_fetch_2:
01667   case Builtin::BI__sync_xor_and_fetch_4:
01668   case Builtin::BI__sync_xor_and_fetch_8:
01669   case Builtin::BI__sync_xor_and_fetch_16:
01670     BuiltinIndex = 10;
01671     break;
01672 
01673   case Builtin::BI__sync_nand_and_fetch: 
01674   case Builtin::BI__sync_nand_and_fetch_1:
01675   case Builtin::BI__sync_nand_and_fetch_2:
01676   case Builtin::BI__sync_nand_and_fetch_4:
01677   case Builtin::BI__sync_nand_and_fetch_8:
01678   case Builtin::BI__sync_nand_and_fetch_16:
01679     BuiltinIndex = 11;
01680     WarnAboutSemanticsChange = true;
01681     break;
01682 
01683   case Builtin::BI__sync_val_compare_and_swap:
01684   case Builtin::BI__sync_val_compare_and_swap_1:
01685   case Builtin::BI__sync_val_compare_and_swap_2:
01686   case Builtin::BI__sync_val_compare_and_swap_4:
01687   case Builtin::BI__sync_val_compare_and_swap_8:
01688   case Builtin::BI__sync_val_compare_and_swap_16:
01689     BuiltinIndex = 12;
01690     NumFixed = 2;
01691     break;
01692       
01693   case Builtin::BI__sync_bool_compare_and_swap:
01694   case Builtin::BI__sync_bool_compare_and_swap_1:
01695   case Builtin::BI__sync_bool_compare_and_swap_2:
01696   case Builtin::BI__sync_bool_compare_and_swap_4:
01697   case Builtin::BI__sync_bool_compare_and_swap_8:
01698   case Builtin::BI__sync_bool_compare_and_swap_16:
01699     BuiltinIndex = 13;
01700     NumFixed = 2;
01701     ResultType = Context.BoolTy;
01702     break;
01703       
01704   case Builtin::BI__sync_lock_test_and_set: 
01705   case Builtin::BI__sync_lock_test_and_set_1:
01706   case Builtin::BI__sync_lock_test_and_set_2:
01707   case Builtin::BI__sync_lock_test_and_set_4:
01708   case Builtin::BI__sync_lock_test_and_set_8:
01709   case Builtin::BI__sync_lock_test_and_set_16:
01710     BuiltinIndex = 14; 
01711     break;
01712       
01713   case Builtin::BI__sync_lock_release:
01714   case Builtin::BI__sync_lock_release_1:
01715   case Builtin::BI__sync_lock_release_2:
01716   case Builtin::BI__sync_lock_release_4:
01717   case Builtin::BI__sync_lock_release_8:
01718   case Builtin::BI__sync_lock_release_16:
01719     BuiltinIndex = 15;
01720     NumFixed = 0;
01721     ResultType = Context.VoidTy;
01722     break;
01723       
01724   case Builtin::BI__sync_swap: 
01725   case Builtin::BI__sync_swap_1:
01726   case Builtin::BI__sync_swap_2:
01727   case Builtin::BI__sync_swap_4:
01728   case Builtin::BI__sync_swap_8:
01729   case Builtin::BI__sync_swap_16:
01730     BuiltinIndex = 16; 
01731     break;
01732   }
01733 
01734   // Now that we know how many fixed arguments we expect, first check that we
01735   // have at least that many.
01736   if (TheCall->getNumArgs() < 1+NumFixed) {
01737     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
01738       << 0 << 1+NumFixed << TheCall->getNumArgs()
01739       << TheCall->getCallee()->getSourceRange();
01740     return ExprError();
01741   }
01742 
01743   if (WarnAboutSemanticsChange) {
01744     Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
01745       << TheCall->getCallee()->getSourceRange();
01746   }
01747 
01748   // Get the decl for the concrete builtin from this, we can tell what the
01749   // concrete integer type we should convert to is.
01750   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
01751   const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
01752   FunctionDecl *NewBuiltinDecl;
01753   if (NewBuiltinID == BuiltinID)
01754     NewBuiltinDecl = FDecl;
01755   else {
01756     // Perform builtin lookup to avoid redeclaring it.
01757     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
01758     LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
01759     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
01760     assert(Res.getFoundDecl());
01761     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
01762     if (!NewBuiltinDecl)
01763       return ExprError();
01764   }
01765 
01766   // The first argument --- the pointer --- has a fixed type; we
01767   // deduce the types of the rest of the arguments accordingly.  Walk
01768   // the remaining arguments, converting them to the deduced value type.
01769   for (unsigned i = 0; i != NumFixed; ++i) {
01770     ExprResult Arg = TheCall->getArg(i+1);
01771 
01772     // GCC does an implicit conversion to the pointer or integer ValType.  This
01773     // can fail in some cases (1i -> int**), check for this error case now.
01774     // Initialize the argument.
01775     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
01776                                                    ValType, /*consume*/ false);
01777     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
01778     if (Arg.isInvalid())
01779       return ExprError();
01780 
01781     // Okay, we have something that *can* be converted to the right type.  Check
01782     // to see if there is a potentially weird extension going on here.  This can
01783     // happen when you do an atomic operation on something like an char* and
01784     // pass in 42.  The 42 gets converted to char.  This is even more strange
01785     // for things like 45.123 -> char, etc.
01786     // FIXME: Do this check.
01787     TheCall->setArg(i+1, Arg.get());
01788   }
01789 
01790   ASTContext& Context = this->getASTContext();
01791 
01792   // Create a new DeclRefExpr to refer to the new decl.
01793   DeclRefExpr* NewDRE = DeclRefExpr::Create(
01794       Context,
01795       DRE->getQualifierLoc(),
01796       SourceLocation(),
01797       NewBuiltinDecl,
01798       /*enclosing*/ false,
01799       DRE->getLocation(),
01800       Context.BuiltinFnTy,
01801       DRE->getValueKind());
01802 
01803   // Set the callee in the CallExpr.
01804   // FIXME: This loses syntactic information.
01805   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
01806   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
01807                                               CK_BuiltinFnToFnPtr);
01808   TheCall->setCallee(PromotedCall.get());
01809 
01810   // Change the result type of the call to match the original value type. This
01811   // is arbitrary, but the codegen for these builtins ins design to handle it
01812   // gracefully.
01813   TheCall->setType(ResultType);
01814 
01815   return TheCallResult;
01816 }
01817 
01818 /// CheckObjCString - Checks that the argument to the builtin
01819 /// CFString constructor is correct
01820 /// Note: It might also make sense to do the UTF-16 conversion here (would
01821 /// simplify the backend).
01822 bool Sema::CheckObjCString(Expr *Arg) {
01823   Arg = Arg->IgnoreParenCasts();
01824   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
01825 
01826   if (!Literal || !Literal->isAscii()) {
01827     Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
01828       << Arg->getSourceRange();
01829     return true;
01830   }
01831 
01832   if (Literal->containsNonAsciiOrNull()) {
01833     StringRef String = Literal->getString();
01834     unsigned NumBytes = String.size();
01835     SmallVector<UTF16, 128> ToBuf(NumBytes);
01836     const UTF8 *FromPtr = (const UTF8 *)String.data();
01837     UTF16 *ToPtr = &ToBuf[0];
01838     
01839     ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
01840                                                  &ToPtr, ToPtr + NumBytes,
01841                                                  strictConversion);
01842     // Check for conversion failure.
01843     if (Result != conversionOK)
01844       Diag(Arg->getLocStart(),
01845            diag::warn_cfstring_truncated) << Arg->getSourceRange();
01846   }
01847   return false;
01848 }
01849 
01850 /// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
01851 /// Emit an error and return true on failure, return false on success.
01852 bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
01853   Expr *Fn = TheCall->getCallee();
01854   if (TheCall->getNumArgs() > 2) {
01855     Diag(TheCall->getArg(2)->getLocStart(),
01856          diag::err_typecheck_call_too_many_args)
01857       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
01858       << Fn->getSourceRange()
01859       << SourceRange(TheCall->getArg(2)->getLocStart(),
01860                      (*(TheCall->arg_end()-1))->getLocEnd());
01861     return true;
01862   }
01863 
01864   if (TheCall->getNumArgs() < 2) {
01865     return Diag(TheCall->getLocEnd(),
01866       diag::err_typecheck_call_too_few_args_at_least)
01867       << 0 /*function call*/ << 2 << TheCall->getNumArgs();
01868   }
01869 
01870   // Type-check the first argument normally.
01871   if (checkBuiltinArgument(*this, TheCall, 0))
01872     return true;
01873 
01874   // Determine whether the current function is variadic or not.
01875   BlockScopeInfo *CurBlock = getCurBlock();
01876   bool isVariadic;
01877   if (CurBlock)
01878     isVariadic = CurBlock->TheDecl->isVariadic();
01879   else if (FunctionDecl *FD = getCurFunctionDecl())
01880     isVariadic = FD->isVariadic();
01881   else
01882     isVariadic = getCurMethodDecl()->isVariadic();
01883 
01884   if (!isVariadic) {
01885     Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
01886     return true;
01887   }
01888 
01889   // Verify that the second argument to the builtin is the last argument of the
01890   // current function or method.
01891   bool SecondArgIsLastNamedArgument = false;
01892   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
01893 
01894   // These are valid if SecondArgIsLastNamedArgument is false after the next
01895   // block.
01896   QualType Type;
01897   SourceLocation ParamLoc;
01898 
01899   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
01900     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
01901       // FIXME: This isn't correct for methods (results in bogus warning).
01902       // Get the last formal in the current function.
01903       const ParmVarDecl *LastArg;
01904       if (CurBlock)
01905         LastArg = *(CurBlock->TheDecl->param_end()-1);
01906       else if (FunctionDecl *FD = getCurFunctionDecl())
01907         LastArg = *(FD->param_end()-1);
01908       else
01909         LastArg = *(getCurMethodDecl()->param_end()-1);
01910       SecondArgIsLastNamedArgument = PV == LastArg;
01911 
01912       Type = PV->getType();
01913       ParamLoc = PV->getLocation();
01914     }
01915   }
01916 
01917   if (!SecondArgIsLastNamedArgument)
01918     Diag(TheCall->getArg(1)->getLocStart(),
01919          diag::warn_second_parameter_of_va_start_not_last_named_argument);
01920   else if (Type->isReferenceType()) {
01921     Diag(Arg->getLocStart(),
01922          diag::warn_va_start_of_reference_type_is_undefined);
01923     Diag(ParamLoc, diag::note_parameter_type) << Type;
01924   }
01925 
01926   TheCall->setType(Context.VoidTy);
01927   return false;
01928 }
01929 
01930 bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
01931   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
01932   //                 const char *named_addr);
01933 
01934   Expr *Func = Call->getCallee();
01935 
01936   if (Call->getNumArgs() < 3)
01937     return Diag(Call->getLocEnd(),
01938                 diag::err_typecheck_call_too_few_args_at_least)
01939            << 0 /*function call*/ << 3 << Call->getNumArgs();
01940 
01941   // Determine whether the current function is variadic or not.
01942   bool IsVariadic;
01943   if (BlockScopeInfo *CurBlock = getCurBlock())
01944     IsVariadic = CurBlock->TheDecl->isVariadic();
01945   else if (FunctionDecl *FD = getCurFunctionDecl())
01946     IsVariadic = FD->isVariadic();
01947   else if (ObjCMethodDecl *MD = getCurMethodDecl())
01948     IsVariadic = MD->isVariadic();
01949   else
01950     llvm_unreachable("unexpected statement type");
01951 
01952   if (!IsVariadic) {
01953     Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
01954     return true;
01955   }
01956 
01957   // Type-check the first argument normally.
01958   if (checkBuiltinArgument(*this, Call, 0))
01959     return true;
01960 
01961   static const struct {
01962     unsigned ArgNo;
01963     QualType Type;
01964   } ArgumentTypes[] = {
01965     { 1, Context.getPointerType(Context.CharTy.withConst()) },
01966     { 2, Context.getSizeType() },
01967   };
01968 
01969   for (const auto &AT : ArgumentTypes) {
01970     const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
01971     if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
01972       continue;
01973     Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
01974       << Arg->getType() << AT.Type << 1 /* different class */
01975       << 0 /* qualifier difference */ << 3 /* parameter mismatch */
01976       << AT.ArgNo + 1 << Arg->getType() << AT.Type;
01977   }
01978 
01979   return false;
01980 }
01981 
01982 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
01983 /// friends.  This is declared to take (...), so we have to check everything.
01984 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
01985   if (TheCall->getNumArgs() < 2)
01986     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
01987       << 0 << 2 << TheCall->getNumArgs()/*function call*/;
01988   if (TheCall->getNumArgs() > 2)
01989     return Diag(TheCall->getArg(2)->getLocStart(),
01990                 diag::err_typecheck_call_too_many_args)
01991       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
01992       << SourceRange(TheCall->getArg(2)->getLocStart(),
01993                      (*(TheCall->arg_end()-1))->getLocEnd());
01994 
01995   ExprResult OrigArg0 = TheCall->getArg(0);
01996   ExprResult OrigArg1 = TheCall->getArg(1);
01997 
01998   // Do standard promotions between the two arguments, returning their common
01999   // type.
02000   QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
02001   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
02002     return true;
02003 
02004   // Make sure any conversions are pushed back into the call; this is
02005   // type safe since unordered compare builtins are declared as "_Bool
02006   // foo(...)".
02007   TheCall->setArg(0, OrigArg0.get());
02008   TheCall->setArg(1, OrigArg1.get());
02009 
02010   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
02011     return false;
02012 
02013   // If the common type isn't a real floating type, then the arguments were
02014   // invalid for this operation.
02015   if (Res.isNull() || !Res->isRealFloatingType())
02016     return Diag(OrigArg0.get()->getLocStart(),
02017                 diag::err_typecheck_call_invalid_ordered_compare)
02018       << OrigArg0.get()->getType() << OrigArg1.get()->getType()
02019       << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
02020 
02021   return false;
02022 }
02023 
02024 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
02025 /// __builtin_isnan and friends.  This is declared to take (...), so we have
02026 /// to check everything. We expect the last argument to be a floating point
02027 /// value.
02028 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
02029   if (TheCall->getNumArgs() < NumArgs)
02030     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
02031       << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
02032   if (TheCall->getNumArgs() > NumArgs)
02033     return Diag(TheCall->getArg(NumArgs)->getLocStart(),
02034                 diag::err_typecheck_call_too_many_args)
02035       << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
02036       << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
02037                      (*(TheCall->arg_end()-1))->getLocEnd());
02038 
02039   Expr *OrigArg = TheCall->getArg(NumArgs-1);
02040 
02041   if (OrigArg->isTypeDependent())
02042     return false;
02043 
02044   // This operation requires a non-_Complex floating-point number.
02045   if (!OrigArg->getType()->isRealFloatingType())
02046     return Diag(OrigArg->getLocStart(),
02047                 diag::err_typecheck_call_invalid_unary_fp)
02048       << OrigArg->getType() << OrigArg->getSourceRange();
02049 
02050   // If this is an implicit conversion from float -> double, remove it.
02051   if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
02052     Expr *CastArg = Cast->getSubExpr();
02053     if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
02054       assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
02055              "promotion from float to double is the only expected cast here");
02056       Cast->setSubExpr(nullptr);
02057       TheCall->setArg(NumArgs-1, CastArg);
02058     }
02059   }
02060   
02061   return false;
02062 }
02063 
02064 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
02065 // This is declared to take (...), so we have to check everything.
02066 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
02067   if (TheCall->getNumArgs() < 2)
02068     return ExprError(Diag(TheCall->getLocEnd(),
02069                           diag::err_typecheck_call_too_few_args_at_least)
02070                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
02071                      << TheCall->getSourceRange());
02072 
02073   // Determine which of the following types of shufflevector we're checking:
02074   // 1) unary, vector mask: (lhs, mask)
02075   // 2) binary, vector mask: (lhs, rhs, mask)
02076   // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
02077   QualType resType = TheCall->getArg(0)->getType();
02078   unsigned numElements = 0;
02079 
02080   if (!TheCall->getArg(0)->isTypeDependent() &&
02081       !TheCall->getArg(1)->isTypeDependent()) {
02082     QualType LHSType = TheCall->getArg(0)->getType();
02083     QualType RHSType = TheCall->getArg(1)->getType();
02084 
02085     if (!LHSType->isVectorType() || !RHSType->isVectorType())
02086       return ExprError(Diag(TheCall->getLocStart(),
02087                             diag::err_shufflevector_non_vector)
02088                        << SourceRange(TheCall->getArg(0)->getLocStart(),
02089                                       TheCall->getArg(1)->getLocEnd()));
02090 
02091     numElements = LHSType->getAs<VectorType>()->getNumElements();
02092     unsigned numResElements = TheCall->getNumArgs() - 2;
02093 
02094     // Check to see if we have a call with 2 vector arguments, the unary shuffle
02095     // with mask.  If so, verify that RHS is an integer vector type with the
02096     // same number of elts as lhs.
02097     if (TheCall->getNumArgs() == 2) {
02098       if (!RHSType->hasIntegerRepresentation() ||
02099           RHSType->getAs<VectorType>()->getNumElements() != numElements)
02100         return ExprError(Diag(TheCall->getLocStart(),
02101                               diag::err_shufflevector_incompatible_vector)
02102                          << SourceRange(TheCall->getArg(1)->getLocStart(),
02103                                         TheCall->getArg(1)->getLocEnd()));
02104     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
02105       return ExprError(Diag(TheCall->getLocStart(),
02106                             diag::err_shufflevector_incompatible_vector)
02107                        << SourceRange(TheCall->getArg(0)->getLocStart(),
02108                                       TheCall->getArg(1)->getLocEnd()));
02109     } else if (numElements != numResElements) {
02110       QualType eltType = LHSType->getAs<VectorType>()->getElementType();
02111       resType = Context.getVectorType(eltType, numResElements,
02112                                       VectorType::GenericVector);
02113     }
02114   }
02115 
02116   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
02117     if (TheCall->getArg(i)->isTypeDependent() ||
02118         TheCall->getArg(i)->isValueDependent())
02119       continue;
02120 
02121     llvm::APSInt Result(32);
02122     if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
02123       return ExprError(Diag(TheCall->getLocStart(),
02124                             diag::err_shufflevector_nonconstant_argument)
02125                        << TheCall->getArg(i)->getSourceRange());
02126 
02127     // Allow -1 which will be translated to undef in the IR.
02128     if (Result.isSigned() && Result.isAllOnesValue())
02129       continue;
02130 
02131     if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
02132       return ExprError(Diag(TheCall->getLocStart(),
02133                             diag::err_shufflevector_argument_too_large)
02134                        << TheCall->getArg(i)->getSourceRange());
02135   }
02136 
02137   SmallVector<Expr*, 32> exprs;
02138 
02139   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
02140     exprs.push_back(TheCall->getArg(i));
02141     TheCall->setArg(i, nullptr);
02142   }
02143 
02144   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
02145                                          TheCall->getCallee()->getLocStart(),
02146                                          TheCall->getRParenLoc());
02147 }
02148 
02149 /// SemaConvertVectorExpr - Handle __builtin_convertvector
02150 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
02151                                        SourceLocation BuiltinLoc,
02152                                        SourceLocation RParenLoc) {
02153   ExprValueKind VK = VK_RValue;
02154   ExprObjectKind OK = OK_Ordinary;
02155   QualType DstTy = TInfo->getType();
02156   QualType SrcTy = E->getType();
02157 
02158   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
02159     return ExprError(Diag(BuiltinLoc,
02160                           diag::err_convertvector_non_vector)
02161                      << E->getSourceRange());
02162   if (!DstTy->isVectorType() && !DstTy->isDependentType())
02163     return ExprError(Diag(BuiltinLoc,
02164                           diag::err_convertvector_non_vector_type));
02165 
02166   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
02167     unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
02168     unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
02169     if (SrcElts != DstElts)
02170       return ExprError(Diag(BuiltinLoc,
02171                             diag::err_convertvector_incompatible_vector)
02172                        << E->getSourceRange());
02173   }
02174 
02175   return new (Context)
02176       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
02177 }
02178 
02179 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
02180 // This is declared to take (const void*, ...) and can take two
02181 // optional constant int args.
02182 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
02183   unsigned NumArgs = TheCall->getNumArgs();
02184 
02185   if (NumArgs > 3)
02186     return Diag(TheCall->getLocEnd(),
02187              diag::err_typecheck_call_too_many_args_at_most)
02188              << 0 /*function call*/ << 3 << NumArgs
02189              << TheCall->getSourceRange();
02190 
02191   // Argument 0 is checked for us and the remaining arguments must be
02192   // constant integers.
02193   for (unsigned i = 1; i != NumArgs; ++i)
02194     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
02195       return true;
02196 
02197   return false;
02198 }
02199 
02200 /// SemaBuiltinAssume - Handle __assume (MS Extension).
02201 // __assume does not evaluate its arguments, and should warn if its argument
02202 // has side effects.
02203 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
02204   Expr *Arg = TheCall->getArg(0);
02205   if (Arg->isInstantiationDependent()) return false;
02206 
02207   if (Arg->HasSideEffects(Context))
02208     return Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
02209       << Arg->getSourceRange()
02210       << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
02211 
02212   return false;
02213 }
02214 
02215 /// Handle __builtin_assume_aligned. This is declared
02216 /// as (const void*, size_t, ...) and can take one optional constant int arg.
02217 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
02218   unsigned NumArgs = TheCall->getNumArgs();
02219 
02220   if (NumArgs > 3)
02221     return Diag(TheCall->getLocEnd(),
02222              diag::err_typecheck_call_too_many_args_at_most)
02223              << 0 /*function call*/ << 3 << NumArgs
02224              << TheCall->getSourceRange();
02225 
02226   // The alignment must be a constant integer.
02227   Expr *Arg = TheCall->getArg(1);
02228 
02229   // We can't check the value of a dependent argument.
02230   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
02231     llvm::APSInt Result;
02232     if (SemaBuiltinConstantArg(TheCall, 1, Result))
02233       return true;
02234 
02235     if (!Result.isPowerOf2())
02236       return Diag(TheCall->getLocStart(),
02237                   diag::err_alignment_not_power_of_two)
02238            << Arg->getSourceRange();
02239   }
02240 
02241   if (NumArgs > 2) {
02242     ExprResult Arg(TheCall->getArg(2));
02243     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
02244       Context.getSizeType(), false);
02245     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
02246     if (Arg.isInvalid()) return true;
02247     TheCall->setArg(2, Arg.get());
02248   }
02249 
02250   return false;
02251 }
02252 
02253 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
02254 /// TheCall is a constant expression.
02255 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
02256                                   llvm::APSInt &Result) {
02257   Expr *Arg = TheCall->getArg(ArgNum);
02258   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
02259   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
02260   
02261   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
02262   
02263   if (!Arg->isIntegerConstantExpr(Result, Context))
02264     return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
02265                 << FDecl->getDeclName() <<  Arg->getSourceRange();
02266   
02267   return false;
02268 }
02269 
02270 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
02271 /// TheCall is a constant expression in the range [Low, High].
02272 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
02273                                        int Low, int High) {
02274   llvm::APSInt Result;
02275 
02276   // We can't check the value of a dependent argument.
02277   Expr *Arg = TheCall->getArg(ArgNum);
02278   if (Arg->isTypeDependent() || Arg->isValueDependent())
02279     return false;
02280 
02281   // Check constant-ness first.
02282   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
02283     return true;
02284 
02285   if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
02286     return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
02287       << Low << High << Arg->getSourceRange();
02288 
02289   return false;
02290 }
02291 
02292 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
02293 /// This checks that val is a constant 1.
02294 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
02295   Expr *Arg = TheCall->getArg(1);
02296   llvm::APSInt Result;
02297 
02298   // TODO: This is less than ideal. Overload this to take a value.
02299   if (SemaBuiltinConstantArg(TheCall, 1, Result))
02300     return true;
02301   
02302   if (Result != 1)
02303     return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
02304              << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
02305 
02306   return false;
02307 }
02308 
02309 namespace {
02310 enum StringLiteralCheckType {
02311   SLCT_NotALiteral,
02312   SLCT_UncheckedLiteral,
02313   SLCT_CheckedLiteral
02314 };
02315 }
02316 
02317 // Determine if an expression is a string literal or constant string.
02318 // If this function returns false on the arguments to a function expecting a
02319 // format string, we will usually need to emit a warning.
02320 // True string literals are then checked by CheckFormatString.
02321 static StringLiteralCheckType
02322 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
02323                       bool HasVAListArg, unsigned format_idx,
02324                       unsigned firstDataArg, Sema::FormatStringType Type,
02325                       Sema::VariadicCallType CallType, bool InFunctionCall,
02326                       llvm::SmallBitVector &CheckedVarArgs) {
02327  tryAgain:
02328   if (E->isTypeDependent() || E->isValueDependent())
02329     return SLCT_NotALiteral;
02330 
02331   E = E->IgnoreParenCasts();
02332 
02333   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
02334     // Technically -Wformat-nonliteral does not warn about this case.
02335     // The behavior of printf and friends in this case is implementation
02336     // dependent.  Ideally if the format string cannot be null then
02337     // it should have a 'nonnull' attribute in the function prototype.
02338     return SLCT_UncheckedLiteral;
02339 
02340   switch (E->getStmtClass()) {
02341   case Stmt::BinaryConditionalOperatorClass:
02342   case Stmt::ConditionalOperatorClass: {
02343     // The expression is a literal if both sub-expressions were, and it was
02344     // completely checked only if both sub-expressions were checked.
02345     const AbstractConditionalOperator *C =
02346         cast<AbstractConditionalOperator>(E);
02347     StringLiteralCheckType Left =
02348         checkFormatStringExpr(S, C->getTrueExpr(), Args,
02349                               HasVAListArg, format_idx, firstDataArg,
02350                               Type, CallType, InFunctionCall, CheckedVarArgs);
02351     if (Left == SLCT_NotALiteral)
02352       return SLCT_NotALiteral;
02353     StringLiteralCheckType Right =
02354         checkFormatStringExpr(S, C->getFalseExpr(), Args,
02355                               HasVAListArg, format_idx, firstDataArg,
02356                               Type, CallType, InFunctionCall, CheckedVarArgs);
02357     return Left < Right ? Left : Right;
02358   }
02359 
02360   case Stmt::ImplicitCastExprClass: {
02361     E = cast<ImplicitCastExpr>(E)->getSubExpr();
02362     goto tryAgain;
02363   }
02364 
02365   case Stmt::OpaqueValueExprClass:
02366     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
02367       E = src;
02368       goto tryAgain;
02369     }
02370     return SLCT_NotALiteral;
02371 
02372   case Stmt::PredefinedExprClass:
02373     // While __func__, etc., are technically not string literals, they
02374     // cannot contain format specifiers and thus are not a security
02375     // liability.
02376     return SLCT_UncheckedLiteral;
02377       
02378   case Stmt::DeclRefExprClass: {
02379     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
02380 
02381     // As an exception, do not flag errors for variables binding to
02382     // const string literals.
02383     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
02384       bool isConstant = false;
02385       QualType T = DR->getType();
02386 
02387       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
02388         isConstant = AT->getElementType().isConstant(S.Context);
02389       } else if (const PointerType *PT = T->getAs<PointerType>()) {
02390         isConstant = T.isConstant(S.Context) &&
02391                      PT->getPointeeType().isConstant(S.Context);
02392       } else if (T->isObjCObjectPointerType()) {
02393         // In ObjC, there is usually no "const ObjectPointer" type,
02394         // so don't check if the pointee type is constant.
02395         isConstant = T.isConstant(S.Context);
02396       }
02397 
02398       if (isConstant) {
02399         if (const Expr *Init = VD->getAnyInitializer()) {
02400           // Look through initializers like const char c[] = { "foo" }
02401           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
02402             if (InitList->isStringLiteralInit())
02403               Init = InitList->getInit(0)->IgnoreParenImpCasts();
02404           }
02405           return checkFormatStringExpr(S, Init, Args,
02406                                        HasVAListArg, format_idx,
02407                                        firstDataArg, Type, CallType,
02408                                        /*InFunctionCall*/false, CheckedVarArgs);
02409         }
02410       }
02411 
02412       // For vprintf* functions (i.e., HasVAListArg==true), we add a
02413       // special check to see if the format string is a function parameter
02414       // of the function calling the printf function.  If the function
02415       // has an attribute indicating it is a printf-like function, then we
02416       // should suppress warnings concerning non-literals being used in a call
02417       // to a vprintf function.  For example:
02418       //
02419       // void
02420       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
02421       //      va_list ap;
02422       //      va_start(ap, fmt);
02423       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
02424       //      ...
02425       // }
02426       if (HasVAListArg) {
02427         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
02428           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
02429             int PVIndex = PV->getFunctionScopeIndex() + 1;
02430             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
02431               // adjust for implicit parameter
02432               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
02433                 if (MD->isInstance())
02434                   ++PVIndex;
02435               // We also check if the formats are compatible.
02436               // We can't pass a 'scanf' string to a 'printf' function.
02437               if (PVIndex == PVFormat->getFormatIdx() &&
02438                   Type == S.GetFormatStringType(PVFormat))
02439                 return SLCT_UncheckedLiteral;
02440             }
02441           }
02442         }
02443       }
02444     }
02445 
02446     return SLCT_NotALiteral;
02447   }
02448 
02449   case Stmt::CallExprClass:
02450   case Stmt::CXXMemberCallExprClass: {
02451     const CallExpr *CE = cast<CallExpr>(E);
02452     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
02453       if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
02454         unsigned ArgIndex = FA->getFormatIdx();
02455         if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
02456           if (MD->isInstance())
02457             --ArgIndex;
02458         const Expr *Arg = CE->getArg(ArgIndex - 1);
02459 
02460         return checkFormatStringExpr(S, Arg, Args,
02461                                      HasVAListArg, format_idx, firstDataArg,
02462                                      Type, CallType, InFunctionCall,
02463                                      CheckedVarArgs);
02464       } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
02465         unsigned BuiltinID = FD->getBuiltinID();
02466         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
02467             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
02468           const Expr *Arg = CE->getArg(0);
02469           return checkFormatStringExpr(S, Arg, Args,
02470                                        HasVAListArg, format_idx,
02471                                        firstDataArg, Type, CallType,
02472                                        InFunctionCall, CheckedVarArgs);
02473         }
02474       }
02475     }
02476 
02477     return SLCT_NotALiteral;
02478   }
02479   case Stmt::ObjCStringLiteralClass:
02480   case Stmt::StringLiteralClass: {
02481     const StringLiteral *StrE = nullptr;
02482 
02483     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
02484       StrE = ObjCFExpr->getString();
02485     else
02486       StrE = cast<StringLiteral>(E);
02487 
02488     if (StrE) {
02489       S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
02490                           Type, InFunctionCall, CallType, CheckedVarArgs);
02491       return SLCT_CheckedLiteral;
02492     }
02493 
02494     return SLCT_NotALiteral;
02495   }
02496 
02497   default:
02498     return SLCT_NotALiteral;
02499   }
02500 }
02501 
02502 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
02503   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
02504   .Case("scanf", FST_Scanf)
02505   .Cases("printf", "printf0", FST_Printf)
02506   .Cases("NSString", "CFString", FST_NSString)
02507   .Case("strftime", FST_Strftime)
02508   .Case("strfmon", FST_Strfmon)
02509   .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
02510   .Default(FST_Unknown);
02511 }
02512 
02513 /// CheckFormatArguments - Check calls to printf and scanf (and similar
02514 /// functions) for correct use of format strings.
02515 /// Returns true if a format string has been fully checked.
02516 bool Sema::CheckFormatArguments(const FormatAttr *Format,
02517                                 ArrayRef<const Expr *> Args,
02518                                 bool IsCXXMember,
02519                                 VariadicCallType CallType,
02520                                 SourceLocation Loc, SourceRange Range,
02521                                 llvm::SmallBitVector &CheckedVarArgs) {
02522   FormatStringInfo FSI;
02523   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
02524     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
02525                                 FSI.FirstDataArg, GetFormatStringType(Format),
02526                                 CallType, Loc, Range, CheckedVarArgs);
02527   return false;
02528 }
02529 
02530 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
02531                                 bool HasVAListArg, unsigned format_idx,
02532                                 unsigned firstDataArg, FormatStringType Type,
02533                                 VariadicCallType CallType,
02534                                 SourceLocation Loc, SourceRange Range,
02535                                 llvm::SmallBitVector &CheckedVarArgs) {
02536   // CHECK: printf/scanf-like function is called with no format string.
02537   if (format_idx >= Args.size()) {
02538     Diag(Loc, diag::warn_missing_format_string) << Range;
02539     return false;
02540   }
02541 
02542   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
02543 
02544   // CHECK: format string is not a string literal.
02545   //
02546   // Dynamically generated format strings are difficult to
02547   // automatically vet at compile time.  Requiring that format strings
02548   // are string literals: (1) permits the checking of format strings by
02549   // the compiler and thereby (2) can practically remove the source of
02550   // many format string exploits.
02551 
02552   // Format string can be either ObjC string (e.g. @"%d") or
02553   // C string (e.g. "%d")
02554   // ObjC string uses the same format specifiers as C string, so we can use
02555   // the same format string checking logic for both ObjC and C strings.
02556   StringLiteralCheckType CT =
02557       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
02558                             format_idx, firstDataArg, Type, CallType,
02559                             /*IsFunctionCall*/true, CheckedVarArgs);
02560   if (CT != SLCT_NotALiteral)
02561     // Literal format string found, check done!
02562     return CT == SLCT_CheckedLiteral;
02563 
02564   // Strftime is particular as it always uses a single 'time' argument,
02565   // so it is safe to pass a non-literal string.
02566   if (Type == FST_Strftime)
02567     return false;
02568 
02569   // Do not emit diag when the string param is a macro expansion and the
02570   // format is either NSString or CFString. This is a hack to prevent
02571   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
02572   // which are usually used in place of NS and CF string literals.
02573   if (Type == FST_NSString &&
02574       SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
02575     return false;
02576 
02577   // If there are no arguments specified, warn with -Wformat-security, otherwise
02578   // warn only with -Wformat-nonliteral.
02579   if (Args.size() == firstDataArg)
02580     Diag(Args[format_idx]->getLocStart(),
02581          diag::warn_format_nonliteral_noargs)
02582       << OrigFormatExpr->getSourceRange();
02583   else
02584     Diag(Args[format_idx]->getLocStart(),
02585          diag::warn_format_nonliteral)
02586            << OrigFormatExpr->getSourceRange();
02587   return false;
02588 }
02589 
02590 namespace {
02591 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
02592 protected:
02593   Sema &S;
02594   const StringLiteral *FExpr;
02595   const Expr *OrigFormatExpr;
02596   const unsigned FirstDataArg;
02597   const unsigned NumDataArgs;
02598   const char *Beg; // Start of format string.
02599   const bool HasVAListArg;
02600   ArrayRef<const Expr *> Args;
02601   unsigned FormatIdx;
02602   llvm::SmallBitVector CoveredArgs;
02603   bool usesPositionalArgs;
02604   bool atFirstArg;
02605   bool inFunctionCall;
02606   Sema::VariadicCallType CallType;
02607   llvm::SmallBitVector &CheckedVarArgs;
02608 public:
02609   CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
02610                      const Expr *origFormatExpr, unsigned firstDataArg,
02611                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
02612                      ArrayRef<const Expr *> Args,
02613                      unsigned formatIdx, bool inFunctionCall,
02614                      Sema::VariadicCallType callType,
02615                      llvm::SmallBitVector &CheckedVarArgs)
02616     : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
02617       FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
02618       Beg(beg), HasVAListArg(hasVAListArg),
02619       Args(Args), FormatIdx(formatIdx),
02620       usesPositionalArgs(false), atFirstArg(true),
02621       inFunctionCall(inFunctionCall), CallType(callType),
02622       CheckedVarArgs(CheckedVarArgs) {
02623     CoveredArgs.resize(numDataArgs);
02624     CoveredArgs.reset();
02625   }
02626 
02627   void DoneProcessing();
02628 
02629   void HandleIncompleteSpecifier(const char *startSpecifier,
02630                                  unsigned specifierLen) override;
02631 
02632   void HandleInvalidLengthModifier(
02633                            const analyze_format_string::FormatSpecifier &FS,
02634                            const analyze_format_string::ConversionSpecifier &CS,
02635                            const char *startSpecifier, unsigned specifierLen,
02636                            unsigned DiagID);
02637 
02638   void HandleNonStandardLengthModifier(
02639                     const analyze_format_string::FormatSpecifier &FS,
02640                     const char *startSpecifier, unsigned specifierLen);
02641 
02642   void HandleNonStandardConversionSpecifier(
02643                     const analyze_format_string::ConversionSpecifier &CS,
02644                     const char *startSpecifier, unsigned specifierLen);
02645 
02646   void HandlePosition(const char *startPos, unsigned posLen) override;
02647 
02648   void HandleInvalidPosition(const char *startSpecifier,
02649                              unsigned specifierLen,
02650                              analyze_format_string::PositionContext p) override;
02651 
02652   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
02653 
02654   void HandleNullChar(const char *nullCharacter) override;
02655 
02656   template <typename Range>
02657   static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
02658                                    const Expr *ArgumentExpr,
02659                                    PartialDiagnostic PDiag,
02660                                    SourceLocation StringLoc,
02661                                    bool IsStringLocation, Range StringRange,
02662                                    ArrayRef<FixItHint> Fixit = None);
02663 
02664 protected:
02665   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
02666                                         const char *startSpec,
02667                                         unsigned specifierLen,
02668                                         const char *csStart, unsigned csLen);
02669 
02670   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
02671                                          const char *startSpec,
02672                                          unsigned specifierLen);
02673   
02674   SourceRange getFormatStringRange();
02675   CharSourceRange getSpecifierRange(const char *startSpecifier,
02676                                     unsigned specifierLen);
02677   SourceLocation getLocationOfByte(const char *x);
02678 
02679   const Expr *getDataArg(unsigned i) const;
02680   
02681   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
02682                     const analyze_format_string::ConversionSpecifier &CS,
02683                     const char *startSpecifier, unsigned specifierLen,
02684                     unsigned argIndex);
02685 
02686   template <typename Range>
02687   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
02688                             bool IsStringLocation, Range StringRange,
02689                             ArrayRef<FixItHint> Fixit = None);
02690 };
02691 }
02692 
02693 SourceRange CheckFormatHandler::getFormatStringRange() {
02694   return OrigFormatExpr->getSourceRange();
02695 }
02696 
02697 CharSourceRange CheckFormatHandler::
02698 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
02699   SourceLocation Start = getLocationOfByte(startSpecifier);
02700   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
02701 
02702   // Advance the end SourceLocation by one due to half-open ranges.
02703   End = End.getLocWithOffset(1);
02704 
02705   return CharSourceRange::getCharRange(Start, End);
02706 }
02707 
02708 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
02709   return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
02710 }
02711 
02712 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
02713                                                    unsigned specifierLen){
02714   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
02715                        getLocationOfByte(startSpecifier),
02716                        /*IsStringLocation*/true,
02717                        getSpecifierRange(startSpecifier, specifierLen));
02718 }
02719 
02720 void CheckFormatHandler::HandleInvalidLengthModifier(
02721     const analyze_format_string::FormatSpecifier &FS,
02722     const analyze_format_string::ConversionSpecifier &CS,
02723     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
02724   using namespace analyze_format_string;
02725 
02726   const LengthModifier &LM = FS.getLengthModifier();
02727   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
02728 
02729   // See if we know how to fix this length modifier.
02730   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
02731   if (FixedLM) {
02732     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
02733                          getLocationOfByte(LM.getStart()),
02734                          /*IsStringLocation*/true,
02735                          getSpecifierRange(startSpecifier, specifierLen));
02736 
02737     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
02738       << FixedLM->toString()
02739       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
02740 
02741   } else {
02742     FixItHint Hint;
02743     if (DiagID == diag::warn_format_nonsensical_length)
02744       Hint = FixItHint::CreateRemoval(LMRange);
02745 
02746     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
02747                          getLocationOfByte(LM.getStart()),
02748                          /*IsStringLocation*/true,
02749                          getSpecifierRange(startSpecifier, specifierLen),
02750                          Hint);
02751   }
02752 }
02753 
02754 void CheckFormatHandler::HandleNonStandardLengthModifier(
02755     const analyze_format_string::FormatSpecifier &FS,
02756     const char *startSpecifier, unsigned specifierLen) {
02757   using namespace analyze_format_string;
02758 
02759   const LengthModifier &LM = FS.getLengthModifier();
02760   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
02761 
02762   // See if we know how to fix this length modifier.
02763   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
02764   if (FixedLM) {
02765     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
02766                            << LM.toString() << 0,
02767                          getLocationOfByte(LM.getStart()),
02768                          /*IsStringLocation*/true,
02769                          getSpecifierRange(startSpecifier, specifierLen));
02770 
02771     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
02772       << FixedLM->toString()
02773       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
02774 
02775   } else {
02776     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
02777                            << LM.toString() << 0,
02778                          getLocationOfByte(LM.getStart()),
02779                          /*IsStringLocation*/true,
02780                          getSpecifierRange(startSpecifier, specifierLen));
02781   }
02782 }
02783 
02784 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
02785     const analyze_format_string::ConversionSpecifier &CS,
02786     const char *startSpecifier, unsigned specifierLen) {
02787   using namespace analyze_format_string;
02788 
02789   // See if we know how to fix this conversion specifier.
02790   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
02791   if (FixedCS) {
02792     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
02793                           << CS.toString() << /*conversion specifier*/1,
02794                          getLocationOfByte(CS.getStart()),
02795                          /*IsStringLocation*/true,
02796                          getSpecifierRange(startSpecifier, specifierLen));
02797 
02798     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
02799     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
02800       << FixedCS->toString()
02801       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
02802   } else {
02803     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
02804                           << CS.toString() << /*conversion specifier*/1,
02805                          getLocationOfByte(CS.getStart()),
02806                          /*IsStringLocation*/true,
02807                          getSpecifierRange(startSpecifier, specifierLen));
02808   }
02809 }
02810 
02811 void CheckFormatHandler::HandlePosition(const char *startPos,
02812                                         unsigned posLen) {
02813   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
02814                                getLocationOfByte(startPos),
02815                                /*IsStringLocation*/true,
02816                                getSpecifierRange(startPos, posLen));
02817 }
02818 
02819 void
02820 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
02821                                      analyze_format_string::PositionContext p) {
02822   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
02823                          << (unsigned) p,
02824                        getLocationOfByte(startPos), /*IsStringLocation*/true,
02825                        getSpecifierRange(startPos, posLen));
02826 }
02827 
02828 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
02829                                             unsigned posLen) {
02830   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
02831                                getLocationOfByte(startPos),
02832                                /*IsStringLocation*/true,
02833                                getSpecifierRange(startPos, posLen));
02834 }
02835 
02836 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
02837   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
02838     // The presence of a null character is likely an error.
02839     EmitFormatDiagnostic(
02840       S.PDiag(diag::warn_printf_format_string_contains_null_char),
02841       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
02842       getFormatStringRange());
02843   }
02844 }
02845 
02846 // Note that this may return NULL if there was an error parsing or building
02847 // one of the argument expressions.
02848 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
02849   return Args[FirstDataArg + i];
02850 }
02851 
02852 void CheckFormatHandler::DoneProcessing() {
02853     // Does the number of data arguments exceed the number of
02854     // format conversions in the format string?
02855   if (!HasVAListArg) {
02856       // Find any arguments that weren't covered.
02857     CoveredArgs.flip();
02858     signed notCoveredArg = CoveredArgs.find_first();
02859     if (notCoveredArg >= 0) {
02860       assert((unsigned)notCoveredArg < NumDataArgs);
02861       if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
02862         SourceLocation Loc = E->getLocStart();
02863         if (!S.getSourceManager().isInSystemMacro(Loc)) {
02864           EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
02865                                Loc, /*IsStringLocation*/false,
02866                                getFormatStringRange());
02867         }
02868       }
02869     }
02870   }
02871 }
02872 
02873 bool
02874 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
02875                                                      SourceLocation Loc,
02876                                                      const char *startSpec,
02877                                                      unsigned specifierLen,
02878                                                      const char *csStart,
02879                                                      unsigned csLen) {
02880   
02881   bool keepGoing = true;
02882   if (argIndex < NumDataArgs) {
02883     // Consider the argument coverered, even though the specifier doesn't
02884     // make sense.
02885     CoveredArgs.set(argIndex);
02886   }
02887   else {
02888     // If argIndex exceeds the number of data arguments we
02889     // don't issue a warning because that is just a cascade of warnings (and
02890     // they may have intended '%%' anyway). We don't want to continue processing
02891     // the format string after this point, however, as we will like just get
02892     // gibberish when trying to match arguments.
02893     keepGoing = false;
02894   }
02895   
02896   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
02897                          << StringRef(csStart, csLen),
02898                        Loc, /*IsStringLocation*/true,
02899                        getSpecifierRange(startSpec, specifierLen));
02900   
02901   return keepGoing;
02902 }
02903 
02904 void
02905 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
02906                                                       const char *startSpec,
02907                                                       unsigned specifierLen) {
02908   EmitFormatDiagnostic(
02909     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
02910     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
02911 }
02912 
02913 bool
02914 CheckFormatHandler::CheckNumArgs(
02915   const analyze_format_string::FormatSpecifier &FS,
02916   const analyze_format_string::ConversionSpecifier &CS,
02917   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
02918 
02919   if (argIndex >= NumDataArgs) {
02920     PartialDiagnostic PDiag = FS.usesPositionalArg()
02921       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
02922            << (argIndex+1) << NumDataArgs)
02923       : S.PDiag(diag::warn_printf_insufficient_data_args);
02924     EmitFormatDiagnostic(
02925       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
02926       getSpecifierRange(startSpecifier, specifierLen));
02927     return false;
02928   }
02929   return true;
02930 }
02931 
02932 template<typename Range>
02933 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
02934                                               SourceLocation Loc,
02935                                               bool IsStringLocation,
02936                                               Range StringRange,
02937                                               ArrayRef<FixItHint> FixIt) {
02938   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
02939                        Loc, IsStringLocation, StringRange, FixIt);
02940 }
02941 
02942 /// \brief If the format string is not within the funcion call, emit a note
02943 /// so that the function call and string are in diagnostic messages.
02944 ///
02945 /// \param InFunctionCall if true, the format string is within the function
02946 /// call and only one diagnostic message will be produced.  Otherwise, an
02947 /// extra note will be emitted pointing to location of the format string.
02948 ///
02949 /// \param ArgumentExpr the expression that is passed as the format string
02950 /// argument in the function call.  Used for getting locations when two
02951 /// diagnostics are emitted.
02952 ///
02953 /// \param PDiag the callee should already have provided any strings for the
02954 /// diagnostic message.  This function only adds locations and fixits
02955 /// to diagnostics.
02956 ///
02957 /// \param Loc primary location for diagnostic.  If two diagnostics are
02958 /// required, one will be at Loc and a new SourceLocation will be created for
02959 /// the other one.
02960 ///
02961 /// \param IsStringLocation if true, Loc points to the format string should be
02962 /// used for the note.  Otherwise, Loc points to the argument list and will
02963 /// be used with PDiag.
02964 ///
02965 /// \param StringRange some or all of the string to highlight.  This is
02966 /// templated so it can accept either a CharSourceRange or a SourceRange.
02967 ///
02968 /// \param FixIt optional fix it hint for the format string.
02969 template<typename Range>
02970 void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
02971                                               const Expr *ArgumentExpr,
02972                                               PartialDiagnostic PDiag,
02973                                               SourceLocation Loc,
02974                                               bool IsStringLocation,
02975                                               Range StringRange,
02976                                               ArrayRef<FixItHint> FixIt) {
02977   if (InFunctionCall) {
02978     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
02979     D << StringRange;
02980     for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
02981          I != E; ++I) {
02982       D << *I;
02983     }
02984   } else {
02985     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
02986       << ArgumentExpr->getSourceRange();
02987 
02988     const Sema::SemaDiagnosticBuilder &Note =
02989       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
02990              diag::note_format_string_defined);
02991 
02992     Note << StringRange;
02993     for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
02994          I != E; ++I) {
02995       Note << *I;
02996     }
02997   }
02998 }
02999 
03000 //===--- CHECK: Printf format string checking ------------------------------===//
03001 
03002 namespace {
03003 class CheckPrintfHandler : public CheckFormatHandler {
03004   bool ObjCContext;
03005 public:
03006   CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
03007                      const Expr *origFormatExpr, unsigned firstDataArg,
03008                      unsigned numDataArgs, bool isObjC,
03009                      const char *beg, bool hasVAListArg,
03010                      ArrayRef<const Expr *> Args,
03011                      unsigned formatIdx, bool inFunctionCall,
03012                      Sema::VariadicCallType CallType,
03013                      llvm::SmallBitVector &CheckedVarArgs)
03014     : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
03015                          numDataArgs, beg, hasVAListArg, Args,
03016                          formatIdx, inFunctionCall, CallType, CheckedVarArgs),
03017       ObjCContext(isObjC)
03018   {}
03019 
03020 
03021   bool HandleInvalidPrintfConversionSpecifier(
03022                                       const analyze_printf::PrintfSpecifier &FS,
03023                                       const char *startSpecifier,
03024                                       unsigned specifierLen) override;
03025 
03026   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
03027                              const char *startSpecifier,
03028                              unsigned specifierLen) override;
03029   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
03030                        const char *StartSpecifier,
03031                        unsigned SpecifierLen,
03032                        const Expr *E);
03033 
03034   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
03035                     const char *startSpecifier, unsigned specifierLen);
03036   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
03037                            const analyze_printf::OptionalAmount &Amt,
03038                            unsigned type,
03039                            const char *startSpecifier, unsigned specifierLen);
03040   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
03041                   const analyze_printf::OptionalFlag &flag,
03042                   const char *startSpecifier, unsigned specifierLen);
03043   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
03044                          const analyze_printf::OptionalFlag &ignoredFlag,
03045                          const analyze_printf::OptionalFlag &flag,
03046                          const char *startSpecifier, unsigned specifierLen);
03047   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
03048                            const Expr *E);
03049 
03050 };  
03051 }
03052 
03053 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
03054                                       const analyze_printf::PrintfSpecifier &FS,
03055                                       const char *startSpecifier,
03056                                       unsigned specifierLen) {
03057   const analyze_printf::PrintfConversionSpecifier &CS =
03058     FS.getConversionSpecifier();
03059   
03060   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
03061                                           getLocationOfByte(CS.getStart()),
03062                                           startSpecifier, specifierLen,
03063                                           CS.getStart(), CS.getLength());
03064 }
03065 
03066 bool CheckPrintfHandler::HandleAmount(
03067                                const analyze_format_string::OptionalAmount &Amt,
03068                                unsigned k, const char *startSpecifier,
03069                                unsigned specifierLen) {
03070 
03071   if (Amt.hasDataArgument()) {
03072     if (!HasVAListArg) {
03073       unsigned argIndex = Amt.getArgIndex();
03074       if (argIndex >= NumDataArgs) {
03075         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
03076                                << k,
03077                              getLocationOfByte(Amt.getStart()),
03078                              /*IsStringLocation*/true,
03079                              getSpecifierRange(startSpecifier, specifierLen));
03080         // Don't do any more checking.  We will just emit
03081         // spurious errors.
03082         return false;
03083       }
03084 
03085       // Type check the data argument.  It should be an 'int'.
03086       // Although not in conformance with C99, we also allow the argument to be
03087       // an 'unsigned int' as that is a reasonably safe case.  GCC also
03088       // doesn't emit a warning for that case.
03089       CoveredArgs.set(argIndex);
03090       const Expr *Arg = getDataArg(argIndex);
03091       if (!Arg)
03092         return false;
03093 
03094       QualType T = Arg->getType();
03095 
03096       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
03097       assert(AT.isValid());
03098 
03099       if (!AT.matchesType(S.Context, T)) {
03100         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
03101                                << k << AT.getRepresentativeTypeName(S.Context)
03102                                << T << Arg->getSourceRange(),
03103                              getLocationOfByte(Amt.getStart()),
03104                              /*IsStringLocation*/true,
03105                              getSpecifierRange(startSpecifier, specifierLen));
03106         // Don't do any more checking.  We will just emit
03107         // spurious errors.
03108         return false;
03109       }
03110     }
03111   }
03112   return true;
03113 }
03114 
03115 void CheckPrintfHandler::HandleInvalidAmount(
03116                                       const analyze_printf::PrintfSpecifier &FS,
03117                                       const analyze_printf::OptionalAmount &Amt,
03118                                       unsigned type,
03119                                       const char *startSpecifier,
03120                                       unsigned specifierLen) {
03121   const analyze_printf::PrintfConversionSpecifier &CS =
03122     FS.getConversionSpecifier();
03123 
03124   FixItHint fixit =
03125     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
03126       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
03127                                  Amt.getConstantLength()))
03128       : FixItHint();
03129 
03130   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
03131                          << type << CS.toString(),
03132                        getLocationOfByte(Amt.getStart()),
03133                        /*IsStringLocation*/true,
03134                        getSpecifierRange(startSpecifier, specifierLen),
03135                        fixit);
03136 }
03137 
03138 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
03139                                     const analyze_printf::OptionalFlag &flag,
03140                                     const char *startSpecifier,
03141                                     unsigned specifierLen) {
03142   // Warn about pointless flag with a fixit removal.
03143   const analyze_printf::PrintfConversionSpecifier &CS =
03144     FS.getConversionSpecifier();
03145   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
03146                          << flag.toString() << CS.toString(),
03147                        getLocationOfByte(flag.getPosition()),
03148                        /*IsStringLocation*/true,
03149                        getSpecifierRange(startSpecifier, specifierLen),
03150                        FixItHint::CreateRemoval(
03151                          getSpecifierRange(flag.getPosition(), 1)));
03152 }
03153 
03154 void CheckPrintfHandler::HandleIgnoredFlag(
03155                                 const analyze_printf::PrintfSpecifier &FS,
03156                                 const analyze_printf::OptionalFlag &ignoredFlag,
03157                                 const analyze_printf::OptionalFlag &flag,
03158                                 const char *startSpecifier,
03159                                 unsigned specifierLen) {
03160   // Warn about ignored flag with a fixit removal.
03161   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
03162                          << ignoredFlag.toString() << flag.toString(),
03163                        getLocationOfByte(ignoredFlag.getPosition()),
03164                        /*IsStringLocation*/true,
03165                        getSpecifierRange(startSpecifier, specifierLen),
03166                        FixItHint::CreateRemoval(
03167                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
03168 }
03169 
03170 // Determines if the specified is a C++ class or struct containing
03171 // a member with the specified name and kind (e.g. a CXXMethodDecl named
03172 // "c_str()").
03173 template<typename MemberKind>
03174 static llvm::SmallPtrSet<MemberKind*, 1>
03175 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
03176   const RecordType *RT = Ty->getAs<RecordType>();
03177   llvm::SmallPtrSet<MemberKind*, 1> Results;
03178 
03179   if (!RT)
03180     return Results;
03181   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
03182   if (!RD || !RD->getDefinition())
03183     return Results;
03184 
03185   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
03186                  Sema::LookupMemberName);
03187   R.suppressDiagnostics();
03188 
03189   // We just need to include all members of the right kind turned up by the
03190   // filter, at this point.
03191   if (S.LookupQualifiedName(R, RT->getDecl()))
03192     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
03193       NamedDecl *decl = (*I)->getUnderlyingDecl();
03194       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
03195         Results.insert(FK);
03196     }
03197   return Results;
03198 }
03199 
03200 /// Check if we could call '.c_str()' on an object.
03201 ///
03202 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
03203 /// allow the call, or if it would be ambiguous).
03204 bool Sema::hasCStrMethod(const Expr *E) {
03205   typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
03206   MethodSet Results =
03207       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
03208   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
03209        MI != ME; ++MI)
03210     if ((*MI)->getMinRequiredArguments() == 0)
03211       return true;
03212   return false;
03213 }
03214 
03215 // Check if a (w)string was passed when a (w)char* was needed, and offer a
03216 // better diagnostic if so. AT is assumed to be valid.
03217 // Returns true when a c_str() conversion method is found.
03218 bool CheckPrintfHandler::checkForCStrMembers(
03219     const analyze_printf::ArgType &AT, const Expr *E) {
03220   typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
03221 
03222   MethodSet Results =
03223       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
03224 
03225   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
03226        MI != ME; ++MI) {
03227     const CXXMethodDecl *Method = *MI;
03228     if (Method->getMinRequiredArguments() == 0 &&
03229         AT.matchesType(S.Context, Method->getReturnType())) {
03230       // FIXME: Suggest parens if the expression needs them.
03231       SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
03232       S.Diag(E->getLocStart(), diag::note_printf_c_str)
03233           << "c_str()"
03234           << FixItHint::CreateInsertion(EndLoc, ".c_str()");
03235       return true;
03236     }
03237   }
03238 
03239   return false;
03240 }
03241 
03242 bool
03243 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
03244                                             &FS,
03245                                           const char *startSpecifier,
03246                                           unsigned specifierLen) {
03247 
03248   using namespace analyze_format_string;
03249   using namespace analyze_printf;  
03250   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
03251 
03252   if (FS.consumesDataArgument()) {
03253     if (atFirstArg) {
03254         atFirstArg = false;
03255         usesPositionalArgs = FS.usesPositionalArg();
03256     }
03257     else if (usesPositionalArgs != FS.usesPositionalArg()) {
03258       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
03259                                         startSpecifier, specifierLen);
03260       return false;
03261     }
03262   }
03263 
03264   // First check if the field width, precision, and conversion specifier
03265   // have matching data arguments.
03266   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
03267                     startSpecifier, specifierLen)) {
03268     return false;
03269   }
03270 
03271   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
03272                     startSpecifier, specifierLen)) {
03273     return false;
03274   }
03275 
03276   if (!CS.consumesDataArgument()) {
03277     // FIXME: Technically specifying a precision or field width here
03278     // makes no sense.  Worth issuing a warning at some point.
03279     return true;
03280   }
03281 
03282   // Consume the argument.
03283   unsigned argIndex = FS.getArgIndex();
03284   if (argIndex < NumDataArgs) {
03285     // The check to see if the argIndex is valid will come later.
03286     // We set the bit here because we may exit early from this
03287     // function if we encounter some other error.
03288     CoveredArgs.set(argIndex);
03289   }
03290 
03291   // Check for using an Objective-C specific conversion specifier
03292   // in a non-ObjC literal.
03293   if (!ObjCContext && CS.isObjCArg()) {
03294     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
03295                                                   specifierLen);
03296   }
03297 
03298   // Check for invalid use of field width
03299   if (!FS.hasValidFieldWidth()) {
03300     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
03301         startSpecifier, specifierLen);
03302   }
03303 
03304   // Check for invalid use of precision
03305   if (!FS.hasValidPrecision()) {
03306     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
03307         startSpecifier, specifierLen);
03308   }
03309 
03310   // Check each flag does not conflict with any other component.
03311   if (!FS.hasValidThousandsGroupingPrefix())
03312     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
03313   if (!FS.hasValidLeadingZeros())
03314     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
03315   if (!FS.hasValidPlusPrefix())
03316     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
03317   if (!FS.hasValidSpacePrefix())
03318     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
03319   if (!FS.hasValidAlternativeForm())
03320     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
03321   if (!FS.hasValidLeftJustified())
03322     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
03323 
03324   // Check that flags are not ignored by another flag
03325   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
03326     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
03327         startSpecifier, specifierLen);
03328   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
03329     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
03330             startSpecifier, specifierLen);
03331 
03332   // Check the length modifier is valid with the given conversion specifier.
03333   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
03334     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
03335                                 diag::warn_format_nonsensical_length);
03336   else if (!FS.hasStandardLengthModifier())
03337     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
03338   else if (!FS.hasStandardLengthConversionCombination())
03339     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
03340                                 diag::warn_format_non_standard_conversion_spec);
03341 
03342   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
03343     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
03344 
03345   // The remaining checks depend on the data arguments.
03346   if (HasVAListArg)
03347     return true;
03348 
03349   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
03350     return false;
03351 
03352   const Expr *Arg = getDataArg(argIndex);
03353   if (!Arg)
03354     return true;
03355 
03356   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
03357 }
03358 
03359 static bool requiresParensToAddCast(const Expr *E) {
03360   // FIXME: We should have a general way to reason about operator
03361   // precedence and whether parens are actually needed here.
03362   // Take care of a few common cases where they aren't.
03363   const Expr *Inside = E->IgnoreImpCasts();
03364   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
03365     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
03366 
03367   switch (Inside->getStmtClass()) {
03368   case Stmt::ArraySubscriptExprClass:
03369   case Stmt::CallExprClass:
03370   case Stmt::CharacterLiteralClass:
03371   case Stmt::CXXBoolLiteralExprClass:
03372   case Stmt::DeclRefExprClass:
03373   case Stmt::FloatingLiteralClass:
03374   case Stmt::IntegerLiteralClass:
03375   case Stmt::MemberExprClass:
03376   case Stmt::ObjCArrayLiteralClass:
03377   case Stmt::ObjCBoolLiteralExprClass:
03378   case Stmt::ObjCBoxedExprClass:
03379   case Stmt::ObjCDictionaryLiteralClass:
03380   case Stmt::ObjCEncodeExprClass:
03381   case Stmt::ObjCIvarRefExprClass:
03382   case Stmt::ObjCMessageExprClass:
03383   case Stmt::ObjCPropertyRefExprClass:
03384   case Stmt::ObjCStringLiteralClass:
03385   case Stmt::ObjCSubscriptRefExprClass:
03386   case Stmt::ParenExprClass:
03387   case Stmt::StringLiteralClass:
03388   case Stmt::UnaryOperatorClass:
03389     return false;
03390   default:
03391     return true;
03392   }
03393 }
03394 
03395 static std::pair<QualType, StringRef>
03396 shouldNotPrintDirectly(const ASTContext &Context,
03397                        QualType IntendedTy,
03398                        const Expr *E) {
03399   // Use a 'while' to peel off layers of typedefs.
03400   QualType TyTy = IntendedTy;
03401   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
03402     StringRef Name = UserTy->getDecl()->getName();
03403     QualType CastTy = llvm::StringSwitch<QualType>(Name)
03404       .Case("NSInteger", Context.LongTy)
03405       .Case("NSUInteger", Context.UnsignedLongTy)
03406       .Case("SInt32", Context.IntTy)
03407       .Case("UInt32", Context.UnsignedIntTy)
03408       .Default(QualType());
03409 
03410     if (!CastTy.isNull())
03411       return std::make_pair(CastTy, Name);
03412 
03413     TyTy = UserTy->desugar();
03414   }
03415 
03416   // Strip parens if necessary.
03417   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
03418     return shouldNotPrintDirectly(Context,
03419                                   PE->getSubExpr()->getType(),
03420                                   PE->getSubExpr());
03421 
03422   // If this is a conditional expression, then its result type is constructed
03423   // via usual arithmetic conversions and thus there might be no necessary
03424   // typedef sugar there.  Recurse to operands to check for NSInteger &
03425   // Co. usage condition.
03426   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
03427     QualType TrueTy, FalseTy;
03428     StringRef TrueName, FalseName;
03429 
03430     std::tie(TrueTy, TrueName) =
03431       shouldNotPrintDirectly(Context,
03432                              CO->getTrueExpr()->getType(),
03433                              CO->getTrueExpr());
03434     std::tie(FalseTy, FalseName) =
03435       shouldNotPrintDirectly(Context,
03436                              CO->getFalseExpr()->getType(),
03437                              CO->getFalseExpr());
03438 
03439     if (TrueTy == FalseTy)
03440       return std::make_pair(TrueTy, TrueName);
03441     else if (TrueTy.isNull())
03442       return std::make_pair(FalseTy, FalseName);
03443     else if (FalseTy.isNull())
03444       return std::make_pair(TrueTy, TrueName);
03445   }
03446 
03447   return std::make_pair(QualType(), StringRef());
03448 }
03449 
03450 bool
03451 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
03452                                     const char *StartSpecifier,
03453                                     unsigned SpecifierLen,
03454                                     const Expr *E) {
03455   using namespace analyze_format_string;
03456   using namespace analyze_printf;
03457   // Now type check the data expression that matches the
03458   // format specifier.
03459   const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
03460                                                     ObjCContext);
03461   if (!AT.isValid())
03462     return true;
03463 
03464   QualType ExprTy = E->getType();
03465   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
03466     ExprTy = TET->getUnderlyingExpr()->getType();
03467   }
03468 
03469   if (AT.matchesType(S.Context, ExprTy))
03470     return true;
03471 
03472   // Look through argument promotions for our error message's reported type.
03473   // This includes the integral and floating promotions, but excludes array
03474   // and function pointer decay; seeing that an argument intended to be a
03475   // string has type 'char [6]' is probably more confusing than 'char *'.
03476   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
03477     if (ICE->getCastKind() == CK_IntegralCast ||
03478         ICE->getCastKind() == CK_FloatingCast) {
03479       E = ICE->getSubExpr();
03480       ExprTy = E->getType();
03481 
03482       // Check if we didn't match because of an implicit cast from a 'char'
03483       // or 'short' to an 'int'.  This is done because printf is a varargs
03484       // function.
03485       if (ICE->getType() == S.Context.IntTy ||
03486           ICE->getType() == S.Context.UnsignedIntTy) {
03487         // All further checking is done on the subexpression.
03488         if (AT.matchesType(S.Context, ExprTy))
03489           return true;
03490       }
03491     }
03492   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
03493     // Special case for 'a', which has type 'int' in C.
03494     // Note, however, that we do /not/ want to treat multibyte constants like
03495     // 'MooV' as characters! This form is deprecated but still exists.
03496     if (ExprTy == S.Context.IntTy)
03497       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
03498         ExprTy = S.Context.CharTy;
03499   }
03500 
03501   // Look through enums to their underlying type.
03502   bool IsEnum = false;
03503   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
03504     ExprTy = EnumTy->getDecl()->getIntegerType();
03505     IsEnum = true;
03506   }
03507 
03508   // %C in an Objective-C context prints a unichar, not a wchar_t.
03509   // If the argument is an integer of some kind, believe the %C and suggest
03510   // a cast instead of changing the conversion specifier.
03511   QualType IntendedTy = ExprTy;
03512   if (ObjCContext &&
03513       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
03514     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
03515         !ExprTy->isCharType()) {
03516       // 'unichar' is defined as a typedef of unsigned short, but we should
03517       // prefer using the typedef if it is visible.
03518       IntendedTy = S.Context.UnsignedShortTy;
03519 
03520       // While we are here, check if the value is an IntegerLiteral that happens
03521       // to be within the valid range.
03522       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
03523         const llvm::APInt &V = IL->getValue();
03524         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
03525           return true;
03526       }
03527 
03528       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
03529                           Sema::LookupOrdinaryName);
03530       if (S.LookupName(Result, S.getCurScope())) {
03531         NamedDecl *ND = Result.getFoundDecl();
03532         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
03533           if (TD->getUnderlyingType() == IntendedTy)
03534             IntendedTy = S.Context.getTypedefType(TD);
03535       }
03536     }
03537   }
03538 
03539   // Special-case some of Darwin's platform-independence types by suggesting
03540   // casts to primitive types that are known to be large enough.
03541   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
03542   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
03543     QualType CastTy;
03544     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
03545     if (!CastTy.isNull()) {
03546       IntendedTy = CastTy;
03547       ShouldNotPrintDirectly = true;
03548     }
03549   }
03550 
03551   // We may be able to offer a FixItHint if it is a supported type.
03552   PrintfSpecifier fixedFS = FS;
03553   bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
03554                                  S.Context, ObjCContext);
03555 
03556   if (success) {
03557     // Get the fix string from the fixed format specifier
03558     SmallString<16> buf;
03559     llvm::raw_svector_ostream os(buf);
03560     fixedFS.toString(os);
03561 
03562     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
03563 
03564     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
03565       // In this case, the specifier is wrong and should be changed to match
03566       // the argument.
03567       EmitFormatDiagnostic(
03568         S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
03569           << AT.getRepresentativeTypeName(S.Context) << IntendedTy << IsEnum
03570           << E->getSourceRange(),
03571         E->getLocStart(),
03572         /*IsStringLocation*/false,
03573         SpecRange,
03574         FixItHint::CreateReplacement(SpecRange, os.str()));
03575 
03576     } else {
03577       // The canonical type for formatting this value is different from the
03578       // actual type of the expression. (This occurs, for example, with Darwin's
03579       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
03580       // should be printed as 'long' for 64-bit compatibility.)
03581       // Rather than emitting a normal format/argument mismatch, we want to
03582       // add a cast to the recommended type (and correct the format string
03583       // if necessary).
03584       SmallString<16> CastBuf;
03585       llvm::raw_svector_ostream CastFix(CastBuf);
03586       CastFix << "(";
03587       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
03588       CastFix << ")";
03589 
03590       SmallVector<FixItHint,4> Hints;
03591       if (!AT.matchesType(S.Context, IntendedTy))
03592         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
03593 
03594       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
03595         // If there's already a cast present, just replace it.
03596         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
03597         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
03598 
03599       } else if (!requiresParensToAddCast(E)) {
03600         // If the expression has high enough precedence,
03601         // just write the C-style cast.
03602         Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
03603                                                    CastFix.str()));
03604       } else {
03605         // Otherwise, add parens around the expression as well as the cast.
03606         CastFix << "(";
03607         Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
03608                                                    CastFix.str()));
03609 
03610         SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
03611         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
03612       }
03613 
03614       if (ShouldNotPrintDirectly) {
03615         // The expression has a type that should not be printed directly.
03616         // We extract the name from the typedef because we don't want to show
03617         // the underlying type in the diagnostic.
03618         StringRef Name;
03619         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
03620           Name = TypedefTy->getDecl()->getName();
03621         else
03622           Name = CastTyName;
03623         EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
03624                                << Name << IntendedTy << IsEnum
03625                                << E->getSourceRange(),
03626                              E->getLocStart(), /*IsStringLocation=*/false,
03627                              SpecRange, Hints);
03628       } else {
03629         // In this case, the expression could be printed using a different
03630         // specifier, but we've decided that the specifier is probably correct 
03631         // and we should cast instead. Just use the normal warning message.
03632         EmitFormatDiagnostic(
03633           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
03634             << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
03635             << E->getSourceRange(),
03636           E->getLocStart(), /*IsStringLocation*/false,
03637           SpecRange, Hints);
03638       }
03639     }
03640   } else {
03641     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
03642                                                    SpecifierLen);
03643     // Since the warning for passing non-POD types to variadic functions
03644     // was deferred until now, we emit a warning for non-POD
03645     // arguments here.
03646     switch (S.isValidVarArgType(ExprTy)) {
03647     case Sema::VAK_Valid:
03648     case Sema::VAK_ValidInCXX11:
03649       EmitFormatDiagnostic(
03650         S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
03651           << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
03652           << CSR
03653           << E->getSourceRange(),
03654         E->getLocStart(), /*IsStringLocation*/false, CSR);
03655       break;
03656 
03657     case Sema::VAK_Undefined:
03658     case Sema::VAK_MSVCUndefined:
03659       EmitFormatDiagnostic(
03660         S.PDiag(diag::warn_non_pod_vararg_with_format_string)
03661           << S.getLangOpts().CPlusPlus11
03662           << ExprTy
03663           << CallType
03664           << AT.getRepresentativeTypeName(S.Context)
03665           << CSR
03666           << E->getSourceRange(),
03667         E->getLocStart(), /*IsStringLocation*/false, CSR);
03668       checkForCStrMembers(AT, E);
03669       break;
03670 
03671     case Sema::VAK_Invalid:
03672       if (ExprTy->isObjCObjectType())
03673         EmitFormatDiagnostic(
03674           S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
03675             << S.getLangOpts().CPlusPlus11
03676             << ExprTy
03677             << CallType
03678             << AT.getRepresentativeTypeName(S.Context)
03679             << CSR
03680             << E->getSourceRange(),
03681           E->getLocStart(), /*IsStringLocation*/false, CSR);
03682       else
03683         // FIXME: If this is an initializer list, suggest removing the braces
03684         // or inserting a cast to the target type.
03685         S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
03686           << isa<InitListExpr>(E) << ExprTy << CallType
03687           << AT.getRepresentativeTypeName(S.Context)
03688           << E->getSourceRange();
03689       break;
03690     }
03691 
03692     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
03693            "format string specifier index out of range");
03694     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
03695   }
03696 
03697   return true;
03698 }
03699 
03700 //===--- CHECK: Scanf format string checking ------------------------------===//
03701 
03702 namespace {  
03703 class CheckScanfHandler : public CheckFormatHandler {
03704 public:
03705   CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
03706                     const Expr *origFormatExpr, unsigned firstDataArg,
03707                     unsigned numDataArgs, const char *beg, bool hasVAListArg,
03708                     ArrayRef<const Expr *> Args,
03709                     unsigned formatIdx, bool inFunctionCall,
03710                     Sema::VariadicCallType CallType,
03711                     llvm::SmallBitVector &CheckedVarArgs)
03712     : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
03713                          numDataArgs, beg, hasVAListArg,
03714                          Args, formatIdx, inFunctionCall, CallType,
03715                          CheckedVarArgs)
03716   {}
03717   
03718   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
03719                             const char *startSpecifier,
03720                             unsigned specifierLen) override;
03721   
03722   bool HandleInvalidScanfConversionSpecifier(
03723           const analyze_scanf::ScanfSpecifier &FS,
03724           const char *startSpecifier,
03725           unsigned specifierLen) override;
03726 
03727   void HandleIncompleteScanList(const char *start, const char *end) override;
03728 };
03729 }
03730 
03731 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
03732                                                  const char *end) {
03733   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
03734                        getLocationOfByte(end), /*IsStringLocation*/true,
03735                        getSpecifierRange(start, end - start));
03736 }
03737 
03738 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
03739                                         const analyze_scanf::ScanfSpecifier &FS,
03740                                         const char *startSpecifier,
03741                                         unsigned specifierLen) {
03742 
03743   const analyze_scanf::ScanfConversionSpecifier &CS =
03744     FS.getConversionSpecifier();
03745 
03746   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
03747                                           getLocationOfByte(CS.getStart()),
03748                                           startSpecifier, specifierLen,
03749                                           CS.getStart(), CS.getLength());
03750 }
03751 
03752 bool CheckScanfHandler::HandleScanfSpecifier(
03753                                        const analyze_scanf::ScanfSpecifier &FS,
03754                                        const char *startSpecifier,
03755                                        unsigned specifierLen) {
03756   
03757   using namespace analyze_scanf;
03758   using namespace analyze_format_string;  
03759 
03760   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
03761 
03762   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
03763   // be used to decide if we are using positional arguments consistently.
03764   if (FS.consumesDataArgument()) {
03765     if (atFirstArg) {
03766       atFirstArg = false;
03767       usesPositionalArgs = FS.usesPositionalArg();
03768     }
03769     else if (usesPositionalArgs != FS.usesPositionalArg()) {
03770       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
03771                                         startSpecifier, specifierLen);
03772       return false;
03773     }
03774   }
03775   
03776   // Check if the field with is non-zero.
03777   const OptionalAmount &Amt = FS.getFieldWidth();
03778   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
03779     if (Amt.getConstantAmount() == 0) {
03780       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
03781                                                    Amt.getConstantLength());
03782       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
03783                            getLocationOfByte(Amt.getStart()),
03784                            /*IsStringLocation*/true, R,
03785                            FixItHint::CreateRemoval(R));
03786     }
03787   }
03788   
03789   if (!FS.consumesDataArgument()) {
03790     // FIXME: Technically specifying a precision or field width here
03791     // makes no sense.  Worth issuing a warning at some point.
03792     return true;
03793   }
03794   
03795   // Consume the argument.
03796   unsigned argIndex = FS.getArgIndex();
03797   if (argIndex < NumDataArgs) {
03798       // The check to see if the argIndex is valid will come later.
03799       // We set the bit here because we may exit early from this
03800       // function if we encounter some other error.
03801     CoveredArgs.set(argIndex);
03802   }
03803   
03804   // Check the length modifier is valid with the given conversion specifier.
03805   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
03806     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
03807                                 diag::warn_format_nonsensical_length);
03808   else if (!FS.hasStandardLengthModifier())
03809     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
03810   else if (!FS.hasStandardLengthConversionCombination())
03811     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
03812                                 diag::warn_format_non_standard_conversion_spec);
03813 
03814   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
03815     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
03816 
03817   // The remaining checks depend on the data arguments.
03818   if (HasVAListArg)
03819     return true;
03820   
03821   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
03822     return false;
03823   
03824   // Check that the argument type matches the format specifier.
03825   const Expr *Ex = getDataArg(argIndex);
03826   if (!Ex)
03827     return true;
03828 
03829   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
03830   if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) {
03831     ScanfSpecifier fixedFS = FS;
03832     bool success = fixedFS.fixType(Ex->getType(),
03833                                    Ex->IgnoreImpCasts()->getType(),
03834                                    S.getLangOpts(), S.Context);
03835 
03836     if (success) {
03837       // Get the fix string from the fixed format specifier.
03838       SmallString<128> buf;
03839       llvm::raw_svector_ostream os(buf);
03840       fixedFS.toString(os);
03841 
03842       EmitFormatDiagnostic(
03843         S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
03844           << AT.getRepresentativeTypeName(S.Context) << Ex->getType() << false
03845           << Ex->getSourceRange(),
03846         Ex->getLocStart(),
03847         /*IsStringLocation*/false,
03848         getSpecifierRange(startSpecifier, specifierLen),
03849         FixItHint::CreateReplacement(
03850           getSpecifierRange(startSpecifier, specifierLen),
03851           os.str()));
03852     } else {
03853       EmitFormatDiagnostic(
03854         S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
03855           << AT.getRepresentativeTypeName(S.Context) << Ex->getType() << false
03856           << Ex->getSourceRange(),
03857         Ex->getLocStart(),
03858         /*IsStringLocation*/false,
03859         getSpecifierRange(startSpecifier, specifierLen));
03860     }
03861   }
03862 
03863   return true;
03864 }
03865 
03866 void Sema::CheckFormatString(const StringLiteral *FExpr,
03867                              const Expr *OrigFormatExpr,
03868                              ArrayRef<const Expr *> Args,
03869                              bool HasVAListArg, unsigned format_idx,
03870                              unsigned firstDataArg, FormatStringType Type,
03871                              bool inFunctionCall, VariadicCallType CallType,
03872                              llvm::SmallBitVector &CheckedVarArgs) {
03873   
03874   // CHECK: is the format string a wide literal?
03875   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
03876     CheckFormatHandler::EmitFormatDiagnostic(
03877       *this, inFunctionCall, Args[format_idx],
03878       PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
03879       /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
03880     return;
03881   }
03882   
03883   // Str - The format string.  NOTE: this is NOT null-terminated!
03884   StringRef StrRef = FExpr->getString();
03885   const char *Str = StrRef.data();
03886   // Account for cases where the string literal is truncated in a declaration.
03887   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
03888   assert(T && "String literal not of constant array type!");
03889   size_t TypeSize = T->getSize().getZExtValue();
03890   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
03891   const unsigned numDataArgs = Args.size() - firstDataArg;
03892 
03893   // Emit a warning if the string literal is truncated and does not contain an
03894   // embedded null character.
03895   if (TypeSize <= StrRef.size() &&
03896       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
03897     CheckFormatHandler::EmitFormatDiagnostic(
03898         *this, inFunctionCall, Args[format_idx],
03899         PDiag(diag::warn_printf_format_string_not_null_terminated),
03900         FExpr->getLocStart(),
03901         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
03902     return;
03903   }
03904 
03905   // CHECK: empty format string?
03906   if (StrLen == 0 && numDataArgs > 0) {
03907     CheckFormatHandler::EmitFormatDiagnostic(
03908       *this, inFunctionCall, Args[format_idx],
03909       PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
03910       /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
03911     return;
03912   }
03913   
03914   if (Type == FST_Printf || Type == FST_NSString) {
03915     CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
03916                          numDataArgs, (Type == FST_NSString),
03917                          Str, HasVAListArg, Args, format_idx,
03918                          inFunctionCall, CallType, CheckedVarArgs);
03919   
03920     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
03921                                                   getLangOpts(),
03922                                                   Context.getTargetInfo()))
03923       H.DoneProcessing();
03924   } else if (Type == FST_Scanf) {
03925     CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
03926                         Str, HasVAListArg, Args, format_idx,
03927                         inFunctionCall, CallType, CheckedVarArgs);
03928     
03929     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
03930                                                  getLangOpts(),
03931                                                  Context.getTargetInfo()))
03932       H.DoneProcessing();
03933   } // TODO: handle other formats
03934 }
03935 
03936 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
03937   // Str - The format string.  NOTE: this is NOT null-terminated!
03938   StringRef StrRef = FExpr->getString();
03939   const char *Str = StrRef.data();
03940   // Account for cases where the string literal is truncated in a declaration.
03941   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
03942   assert(T && "String literal not of constant array type!");
03943   size_t TypeSize = T->getSize().getZExtValue();
03944   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
03945   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
03946                                                          getLangOpts(),
03947                                                          Context.getTargetInfo());
03948 }
03949 
03950 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
03951 
03952 // Returns the related absolute value function that is larger, of 0 if one
03953 // does not exist.
03954 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
03955   switch (AbsFunction) {
03956   default:
03957     return 0;
03958 
03959   case Builtin::BI__builtin_abs:
03960     return Builtin::BI__builtin_labs;
03961   case Builtin::BI__builtin_labs:
03962     return Builtin::BI__builtin_llabs;
03963   case Builtin::BI__builtin_llabs:
03964     return 0;
03965 
03966   case Builtin::BI__builtin_fabsf:
03967     return Builtin::BI__builtin_fabs;
03968   case Builtin::BI__builtin_fabs:
03969     return Builtin::BI__builtin_fabsl;
03970   case Builtin::BI__builtin_fabsl:
03971     return 0;
03972 
03973   case Builtin::BI__builtin_cabsf:
03974     return Builtin::BI__builtin_cabs;
03975   case Builtin::BI__builtin_cabs:
03976     return Builtin::BI__builtin_cabsl;
03977   case Builtin::BI__builtin_cabsl:
03978     return 0;
03979 
03980   case Builtin::BIabs:
03981     return Builtin::BIlabs;
03982   case Builtin::BIlabs:
03983     return Builtin::BIllabs;
03984   case Builtin::BIllabs:
03985     return 0;
03986 
03987   case Builtin::BIfabsf:
03988     return Builtin::BIfabs;
03989   case Builtin::BIfabs:
03990     return Builtin::BIfabsl;
03991   case Builtin::BIfabsl:
03992     return 0;
03993 
03994   case Builtin::BIcabsf:
03995    return Builtin::BIcabs;
03996   case Builtin::BIcabs:
03997     return Builtin::BIcabsl;
03998   case Builtin::BIcabsl:
03999     return 0;
04000   }
04001 }
04002 
04003 // Returns the argument type of the absolute value function.
04004 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
04005                                              unsigned AbsType) {
04006   if (AbsType == 0)
04007     return QualType();
04008 
04009   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
04010   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
04011   if (Error != ASTContext::GE_None)
04012     return QualType();
04013 
04014   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
04015   if (!FT)
04016     return QualType();
04017 
04018   if (FT->getNumParams() != 1)
04019     return QualType();
04020 
04021   return FT->getParamType(0);
04022 }
04023 
04024 // Returns the best absolute value function, or zero, based on type and
04025 // current absolute value function.
04026 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
04027                                    unsigned AbsFunctionKind) {
04028   unsigned BestKind = 0;
04029   uint64_t ArgSize = Context.getTypeSize(ArgType);
04030   for (unsigned Kind = AbsFunctionKind; Kind != 0;
04031        Kind = getLargerAbsoluteValueFunction(Kind)) {
04032     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
04033     if (Context.getTypeSize(ParamType) >= ArgSize) {
04034       if (BestKind == 0)
04035         BestKind = Kind;
04036       else if (Context.hasSameType(ParamType, ArgType)) {
04037         BestKind = Kind;
04038         break;
04039       }
04040     }
04041   }
04042   return BestKind;
04043 }
04044 
04045 enum AbsoluteValueKind {
04046   AVK_Integer,
04047   AVK_Floating,
04048   AVK_Complex
04049 };
04050 
04051 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
04052   if (T->isIntegralOrEnumerationType())
04053     return AVK_Integer;
04054   if (T->isRealFloatingType())
04055     return AVK_Floating;
04056   if (T->isAnyComplexType())
04057     return AVK_Complex;
04058 
04059   llvm_unreachable("Type not integer, floating, or complex");
04060 }
04061 
04062 // Changes the absolute value function to a different type.  Preserves whether
04063 // the function is a builtin.
04064 static unsigned changeAbsFunction(unsigned AbsKind,
04065                                   AbsoluteValueKind ValueKind) {
04066   switch (ValueKind) {
04067   case AVK_Integer:
04068     switch (AbsKind) {
04069     default:
04070       return 0;
04071     case Builtin::BI__builtin_fabsf:
04072     case Builtin::BI__builtin_fabs:
04073     case Builtin::BI__builtin_fabsl:
04074     case Builtin::BI__builtin_cabsf:
04075     case Builtin::BI__builtin_cabs:
04076     case Builtin::BI__builtin_cabsl:
04077       return Builtin::BI__builtin_abs;
04078     case Builtin::BIfabsf:
04079     case Builtin::BIfabs:
04080     case Builtin::BIfabsl:
04081     case Builtin::BIcabsf:
04082     case Builtin::BIcabs:
04083     case Builtin::BIcabsl:
04084       return Builtin::BIabs;
04085     }
04086   case AVK_Floating:
04087     switch (AbsKind) {
04088     default:
04089       return 0;
04090     case Builtin::BI__builtin_abs:
04091     case Builtin::BI__builtin_labs:
04092     case Builtin::BI__builtin_llabs:
04093     case Builtin::BI__builtin_cabsf:
04094     case Builtin::BI__builtin_cabs:
04095     case Builtin::BI__builtin_cabsl:
04096       return Builtin::BI__builtin_fabsf;
04097     case Builtin::BIabs:
04098     case Builtin::BIlabs:
04099     case Builtin::BIllabs:
04100     case Builtin::BIcabsf:
04101     case Builtin::BIcabs:
04102     case Builtin::BIcabsl:
04103       return Builtin::BIfabsf;
04104     }
04105   case AVK_Complex:
04106     switch (AbsKind) {
04107     default:
04108       return 0;
04109     case Builtin::BI__builtin_abs:
04110     case Builtin::BI__builtin_labs:
04111     case Builtin::BI__builtin_llabs:
04112     case Builtin::BI__builtin_fabsf:
04113     case Builtin::BI__builtin_fabs:
04114     case Builtin::BI__builtin_fabsl:
04115       return Builtin::BI__builtin_cabsf;
04116     case Builtin::BIabs:
04117     case Builtin::BIlabs:
04118     case Builtin::BIllabs:
04119     case Builtin::BIfabsf:
04120     case Builtin::BIfabs:
04121     case Builtin::BIfabsl:
04122       return Builtin::BIcabsf;
04123     }
04124   }
04125   llvm_unreachable("Unable to convert function");
04126 }
04127 
04128 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
04129   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
04130   if (!FnInfo)
04131     return 0;
04132 
04133   switch (FDecl->getBuiltinID()) {
04134   default:
04135     return 0;
04136   case Builtin::BI__builtin_abs:
04137   case Builtin::BI__builtin_fabs:
04138   case Builtin::BI__builtin_fabsf:
04139   case Builtin::BI__builtin_fabsl:
04140   case Builtin::BI__builtin_labs:
04141   case Builtin::BI__builtin_llabs:
04142   case Builtin::BI__builtin_cabs:
04143   case Builtin::BI__builtin_cabsf:
04144   case Builtin::BI__builtin_cabsl:
04145   case Builtin::BIabs:
04146   case Builtin::BIlabs:
04147   case Builtin::BIllabs:
04148   case Builtin::BIfabs:
04149   case Builtin::BIfabsf:
04150   case Builtin::BIfabsl:
04151   case Builtin::BIcabs:
04152   case Builtin::BIcabsf:
04153   case Builtin::BIcabsl:
04154     return FDecl->getBuiltinID();
04155   }
04156   llvm_unreachable("Unknown Builtin type");
04157 }
04158 
04159 // If the replacement is valid, emit a note with replacement function.
04160 // Additionally, suggest including the proper header if not already included.
04161 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
04162                             unsigned AbsKind, QualType ArgType) {
04163   bool EmitHeaderHint = true;
04164   const char *HeaderName = nullptr;
04165   const char *FunctionName = nullptr;
04166   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
04167     FunctionName = "std::abs";
04168     if (ArgType->isIntegralOrEnumerationType()) {
04169       HeaderName = "cstdlib";
04170     } else if (ArgType->isRealFloatingType()) {
04171       HeaderName = "cmath";
04172     } else {
04173       llvm_unreachable("Invalid Type");
04174     }
04175 
04176     // Lookup all std::abs
04177     if (NamespaceDecl *Std = S.getStdNamespace()) {
04178       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
04179       R.suppressDiagnostics();
04180       S.LookupQualifiedName(R, Std);
04181 
04182       for (const auto *I : R) {
04183         const FunctionDecl *FDecl = nullptr;
04184         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
04185           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
04186         } else {
04187           FDecl = dyn_cast<FunctionDecl>(I);
04188         }
04189         if (!FDecl)
04190           continue;
04191 
04192         // Found std::abs(), check that they are the right ones.
04193         if (FDecl->getNumParams() != 1)
04194           continue;
04195 
04196         // Check that the parameter type can handle the argument.
04197         QualType ParamType = FDecl->getParamDecl(0)->getType();
04198         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
04199             S.Context.getTypeSize(ArgType) <=
04200                 S.Context.getTypeSize(ParamType)) {
04201           // Found a function, don't need the header hint.
04202           EmitHeaderHint = false;
04203           break;
04204         }
04205       }
04206     }
04207   } else {
04208     FunctionName = S.Context.BuiltinInfo.GetName(AbsKind);
04209     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
04210 
04211     if (HeaderName) {
04212       DeclarationName DN(&S.Context.Idents.get(FunctionName));
04213       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
04214       R.suppressDiagnostics();
04215       S.LookupName(R, S.getCurScope());
04216 
04217       if (R.isSingleResult()) {
04218         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
04219         if (FD && FD->getBuiltinID() == AbsKind) {
04220           EmitHeaderHint = false;
04221         } else {
04222           return;
04223         }
04224       } else if (!R.empty()) {
04225         return;
04226       }
04227     }
04228   }
04229 
04230   S.Diag(Loc, diag::note_replace_abs_function)
04231       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
04232 
04233   if (!HeaderName)
04234     return;
04235 
04236   if (!EmitHeaderHint)
04237     return;
04238 
04239   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
04240                                                     << FunctionName;
04241 }
04242 
04243 static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
04244   if (!FDecl)
04245     return false;
04246 
04247   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
04248     return false;
04249 
04250   const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
04251 
04252   while (ND && ND->isInlineNamespace()) {
04253     ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
04254   }
04255 
04256   if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
04257     return false;
04258 
04259   if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
04260     return false;
04261 
04262   return true;
04263 }
04264 
04265 // Warn when using the wrong abs() function.
04266 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
04267                                       const FunctionDecl *FDecl,
04268                                       IdentifierInfo *FnInfo) {
04269   if (Call->getNumArgs() != 1)
04270     return;
04271 
04272   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
04273   bool IsStdAbs = IsFunctionStdAbs(FDecl);
04274   if (AbsKind == 0 && !IsStdAbs)
04275     return;
04276 
04277   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
04278   QualType ParamType = Call->getArg(0)->getType();
04279 
04280   // Unsigned types cannot be negative.  Suggest removing the absolute value
04281   // function call.
04282   if (ArgType->isUnsignedIntegerType()) {
04283     const char *FunctionName =
04284         IsStdAbs ? "std::abs" : Context.BuiltinInfo.GetName(AbsKind);
04285     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
04286     Diag(Call->getExprLoc(), diag::note_remove_abs)
04287         << FunctionName
04288         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
04289     return;
04290   }
04291 
04292   // std::abs has overloads which prevent most of the absolute value problems
04293   // from occurring.
04294   if (IsStdAbs)
04295     return;
04296 
04297   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
04298   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
04299 
04300   // The argument and parameter are the same kind.  Check if they are the right
04301   // size.
04302   if (ArgValueKind == ParamValueKind) {
04303     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
04304       return;
04305 
04306     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
04307     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
04308         << FDecl << ArgType << ParamType;
04309 
04310     if (NewAbsKind == 0)
04311       return;
04312 
04313     emitReplacement(*this, Call->getExprLoc(),
04314                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
04315     return;
04316   }
04317 
04318   // ArgValueKind != ParamValueKind
04319   // The wrong type of absolute value function was used.  Attempt to find the
04320   // proper one.
04321   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
04322   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
04323   if (NewAbsKind == 0)
04324     return;
04325 
04326   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
04327       << FDecl << ParamValueKind << ArgValueKind;
04328 
04329   emitReplacement(*this, Call->getExprLoc(),
04330                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
04331   return;
04332 }
04333 
04334 //===--- CHECK: Standard memory functions ---------------------------------===//
04335 
04336 /// \brief Takes the expression passed to the size_t parameter of functions
04337 /// such as memcmp, strncat, etc and warns if it's a comparison.
04338 ///
04339 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
04340 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
04341                                            IdentifierInfo *FnName,
04342                                            SourceLocation FnLoc,
04343                                            SourceLocation RParenLoc) {
04344   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
04345   if (!Size)
04346     return false;
04347 
04348   // if E is binop and op is >, <, >=, <=, ==, &&, ||:
04349   if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
04350     return false;
04351 
04352   SourceRange SizeRange = Size->getSourceRange();
04353   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
04354       << SizeRange << FnName;
04355   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
04356       << FnName << FixItHint::CreateInsertion(
04357                        S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
04358       << FixItHint::CreateRemoval(RParenLoc);
04359   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
04360       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
04361       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
04362                                     ")");
04363 
04364   return true;
04365 }
04366 
04367 /// \brief Determine whether the given type is or contains a dynamic class type
04368 /// (e.g., whether it has a vtable).
04369 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
04370                                                      bool &IsContained) {
04371   // Look through array types while ignoring qualifiers.
04372   const Type *Ty = T->getBaseElementTypeUnsafe();
04373   IsContained = false;
04374 
04375   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
04376   RD = RD ? RD->getDefinition() : nullptr;
04377   if (!RD)
04378     return nullptr;
04379 
04380   if (RD->isDynamicClass())
04381     return RD;
04382 
04383   // Check all the fields.  If any bases were dynamic, the class is dynamic.
04384   // It's impossible for a class to transitively contain itself by value, so
04385   // infinite recursion is impossible.
04386   for (auto *FD : RD->fields()) {
04387     bool SubContained;
04388     if (const CXXRecordDecl *ContainedRD =
04389             getContainedDynamicClass(FD->getType(), SubContained)) {
04390       IsContained = true;
04391       return ContainedRD;
04392     }
04393   }
04394 
04395   return nullptr;
04396 }
04397 
04398 /// \brief If E is a sizeof expression, returns its argument expression,
04399 /// otherwise returns NULL.
04400 static const Expr *getSizeOfExprArg(const Expr* E) {
04401   if (const UnaryExprOrTypeTraitExpr *SizeOf =
04402       dyn_cast<UnaryExprOrTypeTraitExpr>(E))
04403     if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
04404       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
04405 
04406   return nullptr;
04407 }
04408 
04409 /// \brief If E is a sizeof expression, returns its argument type.
04410 static QualType getSizeOfArgType(const Expr* E) {
04411   if (const UnaryExprOrTypeTraitExpr *SizeOf =
04412       dyn_cast<UnaryExprOrTypeTraitExpr>(E))
04413     if (SizeOf->getKind() == clang::UETT_SizeOf)
04414       return SizeOf->getTypeOfArgument();
04415 
04416   return QualType();
04417 }
04418 
04419 /// \brief Check for dangerous or invalid arguments to memset().
04420 ///
04421 /// This issues warnings on known problematic, dangerous or unspecified
04422 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
04423 /// function calls.
04424 ///
04425 /// \param Call The call expression to diagnose.
04426 void Sema::CheckMemaccessArguments(const CallExpr *Call,
04427                                    unsigned BId,
04428                                    IdentifierInfo *FnName) {
04429   assert(BId != 0);
04430 
04431   // It is possible to have a non-standard definition of memset.  Validate
04432   // we have enough arguments, and if not, abort further checking.
04433   unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
04434   if (Call->getNumArgs() < ExpectedNumArgs)
04435     return;
04436 
04437   unsigned LastArg = (BId == Builtin::BImemset ||
04438                       BId == Builtin::BIstrndup ? 1 : 2);
04439   unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
04440   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
04441 
04442   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
04443                                      Call->getLocStart(), Call->getRParenLoc()))
04444     return;
04445 
04446   // We have special checking when the length is a sizeof expression.
04447   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
04448   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
04449   llvm::FoldingSetNodeID SizeOfArgID;
04450 
04451   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
04452     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
04453     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
04454 
04455     QualType DestTy = Dest->getType();
04456     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
04457       QualType PointeeTy = DestPtrTy->getPointeeType();
04458 
04459       // Never warn about void type pointers. This can be used to suppress
04460       // false positives.
04461       if (PointeeTy->isVoidType())
04462         continue;
04463 
04464       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
04465       // actually comparing the expressions for equality. Because computing the
04466       // expression IDs can be expensive, we only do this if the diagnostic is
04467       // enabled.
04468       if (SizeOfArg &&
04469           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
04470                            SizeOfArg->getExprLoc())) {
04471         // We only compute IDs for expressions if the warning is enabled, and
04472         // cache the sizeof arg's ID.
04473         if (SizeOfArgID == llvm::FoldingSetNodeID())
04474           SizeOfArg->Profile(SizeOfArgID, Context, true);
04475         llvm::FoldingSetNodeID DestID;
04476         Dest->Profile(DestID, Context, true);
04477         if (DestID == SizeOfArgID) {
04478           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
04479           //       over sizeof(src) as well.
04480           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
04481           StringRef ReadableName = FnName->getName();
04482 
04483           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
04484             if (UnaryOp->getOpcode() == UO_AddrOf)
04485               ActionIdx = 1; // If its an address-of operator, just remove it.
04486           if (!PointeeTy->isIncompleteType() &&
04487               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
04488             ActionIdx = 2; // If the pointee's size is sizeof(char),
04489                            // suggest an explicit length.
04490 
04491           // If the function is defined as a builtin macro, do not show macro
04492           // expansion.
04493           SourceLocation SL = SizeOfArg->getExprLoc();
04494           SourceRange DSR = Dest->getSourceRange();
04495           SourceRange SSR = SizeOfArg->getSourceRange();
04496           SourceManager &SM = getSourceManager();
04497 
04498           if (SM.isMacroArgExpansion(SL)) {
04499             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
04500             SL = SM.getSpellingLoc(SL);
04501             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
04502                              SM.getSpellingLoc(DSR.getEnd()));
04503             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
04504                              SM.getSpellingLoc(SSR.getEnd()));
04505           }
04506 
04507           DiagRuntimeBehavior(SL, SizeOfArg,
04508                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
04509                                 << ReadableName
04510                                 << PointeeTy
04511                                 << DestTy
04512                                 << DSR
04513                                 << SSR);
04514           DiagRuntimeBehavior(SL, SizeOfArg,
04515                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
04516                                 << ActionIdx
04517                                 << SSR);
04518 
04519           break;
04520         }
04521       }
04522 
04523       // Also check for cases where the sizeof argument is the exact same
04524       // type as the memory argument, and where it points to a user-defined
04525       // record type.
04526       if (SizeOfArgTy != QualType()) {
04527         if (PointeeTy->isRecordType() &&
04528             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
04529           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
04530                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
04531                                 << FnName << SizeOfArgTy << ArgIdx
04532                                 << PointeeTy << Dest->getSourceRange()
04533                                 << LenExpr->getSourceRange());
04534           break;
04535         }
04536       }
04537 
04538       // Always complain about dynamic classes.
04539       bool IsContained;
04540       if (const CXXRecordDecl *ContainedRD =
04541               getContainedDynamicClass(PointeeTy, IsContained)) {
04542 
04543         unsigned OperationType = 0;
04544         // "overwritten" if we're warning about the destination for any call
04545         // but memcmp; otherwise a verb appropriate to the call.
04546         if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
04547           if (BId == Builtin::BImemcpy)
04548             OperationType = 1;
04549           else if(BId == Builtin::BImemmove)
04550             OperationType = 2;
04551           else if (BId == Builtin::BImemcmp)
04552             OperationType = 3;
04553         }
04554           
04555         DiagRuntimeBehavior(
04556           Dest->getExprLoc(), Dest,
04557           PDiag(diag::warn_dyn_class_memaccess)
04558             << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
04559             << FnName << IsContained << ContainedRD << OperationType
04560             << Call->getCallee()->getSourceRange());
04561       } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
04562                BId != Builtin::BImemset)
04563         DiagRuntimeBehavior(
04564           Dest->getExprLoc(), Dest,
04565           PDiag(diag::warn_arc_object_memaccess)
04566             << ArgIdx << FnName << PointeeTy
04567             << Call->getCallee()->getSourceRange());
04568       else
04569         continue;
04570 
04571       DiagRuntimeBehavior(
04572         Dest->getExprLoc(), Dest,
04573         PDiag(diag::note_bad_memaccess_silence)
04574           << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
04575       break;
04576     }
04577   }
04578 }
04579 
04580 // A little helper routine: ignore addition and subtraction of integer literals.
04581 // This intentionally does not ignore all integer constant expressions because
04582 // we don't want to remove sizeof().
04583 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
04584   Ex = Ex->IgnoreParenCasts();
04585 
04586   for (;;) {
04587     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
04588     if (!BO || !BO->isAdditiveOp())
04589       break;
04590 
04591     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
04592     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
04593     
04594     if (isa<IntegerLiteral>(RHS))
04595       Ex = LHS;
04596     else if (isa<IntegerLiteral>(LHS))
04597       Ex = RHS;
04598     else
04599       break;
04600   }
04601 
04602   return Ex;
04603 }
04604 
04605 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
04606                                                       ASTContext &Context) {
04607   // Only handle constant-sized or VLAs, but not flexible members.
04608   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
04609     // Only issue the FIXIT for arrays of size > 1.
04610     if (CAT->getSize().getSExtValue() <= 1)
04611       return false;
04612   } else if (!Ty->isVariableArrayType()) {
04613     return false;
04614   }
04615   return true;
04616 }
04617 
04618 // Warn if the user has made the 'size' argument to strlcpy or strlcat
04619 // be the size of the source, instead of the destination.
04620 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
04621                                     IdentifierInfo *FnName) {
04622 
04623   // Don't crash if the user has the wrong number of arguments
04624   unsigned NumArgs = Call->getNumArgs();
04625   if ((NumArgs != 3) && (NumArgs != 4))
04626     return;
04627 
04628   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
04629   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
04630   const Expr *CompareWithSrc = nullptr;
04631 
04632   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
04633                                      Call->getLocStart(), Call->getRParenLoc()))
04634     return;
04635   
04636   // Look for 'strlcpy(dst, x, sizeof(x))'
04637   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
04638     CompareWithSrc = Ex;
04639   else {
04640     // Look for 'strlcpy(dst, x, strlen(x))'
04641     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
04642       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
04643           SizeCall->getNumArgs() == 1)
04644         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
04645     }
04646   }
04647 
04648   if (!CompareWithSrc)
04649     return;
04650 
04651   // Determine if the argument to sizeof/strlen is equal to the source
04652   // argument.  In principle there's all kinds of things you could do
04653   // here, for instance creating an == expression and evaluating it with
04654   // EvaluateAsBooleanCondition, but this uses a more direct technique:
04655   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
04656   if (!SrcArgDRE)
04657     return;
04658   
04659   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
04660   if (!CompareWithSrcDRE || 
04661       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
04662     return;
04663   
04664   const Expr *OriginalSizeArg = Call->getArg(2);
04665   Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
04666     << OriginalSizeArg->getSourceRange() << FnName;
04667   
04668   // Output a FIXIT hint if the destination is an array (rather than a
04669   // pointer to an array).  This could be enhanced to handle some
04670   // pointers if we know the actual size, like if DstArg is 'array+2'
04671   // we could say 'sizeof(array)-2'.
04672   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
04673   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
04674     return;
04675 
04676   SmallString<128> sizeString;
04677   llvm::raw_svector_ostream OS(sizeString);
04678   OS << "sizeof(";
04679   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
04680   OS << ")";
04681   
04682   Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
04683     << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
04684                                     OS.str());
04685 }
04686 
04687 /// Check if two expressions refer to the same declaration.
04688 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
04689   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
04690     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
04691       return D1->getDecl() == D2->getDecl();
04692   return false;
04693 }
04694 
04695 static const Expr *getStrlenExprArg(const Expr *E) {
04696   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
04697     const FunctionDecl *FD = CE->getDirectCallee();
04698     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
04699       return nullptr;
04700     return CE->getArg(0)->IgnoreParenCasts();
04701   }
04702   return nullptr;
04703 }
04704 
04705 // Warn on anti-patterns as the 'size' argument to strncat.
04706 // The correct size argument should look like following:
04707 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
04708 void Sema::CheckStrncatArguments(const CallExpr *CE,
04709                                  IdentifierInfo *FnName) {
04710   // Don't crash if the user has the wrong number of arguments.
04711   if (CE->getNumArgs() < 3)
04712     return;
04713   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
04714   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
04715   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
04716 
04717   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
04718                                      CE->getRParenLoc()))
04719     return;
04720 
04721   // Identify common expressions, which are wrongly used as the size argument
04722   // to strncat and may lead to buffer overflows.
04723   unsigned PatternType = 0;
04724   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
04725     // - sizeof(dst)
04726     if (referToTheSameDecl(SizeOfArg, DstArg))
04727       PatternType = 1;
04728     // - sizeof(src)
04729     else if (referToTheSameDecl(SizeOfArg, SrcArg))
04730       PatternType = 2;
04731   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
04732     if (BE->getOpcode() == BO_Sub) {
04733       const Expr *L = BE->getLHS()->IgnoreParenCasts();
04734       const Expr *R = BE->getRHS()->IgnoreParenCasts();
04735       // - sizeof(dst) - strlen(dst)
04736       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
04737           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
04738         PatternType = 1;
04739       // - sizeof(src) - (anything)
04740       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
04741         PatternType = 2;
04742     }
04743   }
04744 
04745   if (PatternType == 0)
04746     return;
04747 
04748   // Generate the diagnostic.
04749   SourceLocation SL = LenArg->getLocStart();
04750   SourceRange SR = LenArg->getSourceRange();
04751   SourceManager &SM = getSourceManager();
04752 
04753   // If the function is defined as a builtin macro, do not show macro expansion.
04754   if (SM.isMacroArgExpansion(SL)) {
04755     SL = SM.getSpellingLoc(SL);
04756     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
04757                      SM.getSpellingLoc(SR.getEnd()));
04758   }
04759 
04760   // Check if the destination is an array (rather than a pointer to an array).
04761   QualType DstTy = DstArg->getType();
04762   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
04763                                                                     Context);
04764   if (!isKnownSizeArray) {
04765     if (PatternType == 1)
04766       Diag(SL, diag::warn_strncat_wrong_size) << SR;
04767     else
04768       Diag(SL, diag::warn_strncat_src_size) << SR;
04769     return;
04770   }
04771 
04772   if (PatternType == 1)
04773     Diag(SL, diag::warn_strncat_large_size) << SR;
04774   else
04775     Diag(SL, diag::warn_strncat_src_size) << SR;
04776 
04777   SmallString<128> sizeString;
04778   llvm::raw_svector_ostream OS(sizeString);
04779   OS << "sizeof(";
04780   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
04781   OS << ") - ";
04782   OS << "strlen(";
04783   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
04784   OS << ") - 1";
04785 
04786   Diag(SL, diag::note_strncat_wrong_size)
04787     << FixItHint::CreateReplacement(SR, OS.str());
04788 }
04789 
04790 //===--- CHECK: Return Address of Stack Variable --------------------------===//
04791 
04792 static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
04793                      Decl *ParentDecl);
04794 static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
04795                       Decl *ParentDecl);
04796 
04797 /// CheckReturnStackAddr - Check if a return statement returns the address
04798 ///   of a stack variable.
04799 static void
04800 CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
04801                      SourceLocation ReturnLoc) {
04802 
04803   Expr *stackE = nullptr;
04804   SmallVector<DeclRefExpr *, 8> refVars;
04805 
04806   // Perform checking for returned stack addresses, local blocks,
04807   // label addresses or references to temporaries.
04808   if (lhsType->isPointerType() ||
04809       (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
04810     stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
04811   } else if (lhsType->isReferenceType()) {
04812     stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
04813   }
04814 
04815   if (!stackE)
04816     return; // Nothing suspicious was found.
04817 
04818   SourceLocation diagLoc;
04819   SourceRange diagRange;
04820   if (refVars.empty()) {
04821     diagLoc = stackE->getLocStart();
04822     diagRange = stackE->getSourceRange();
04823   } else {
04824     // We followed through a reference variable. 'stackE' contains the
04825     // problematic expression but we will warn at the return statement pointing
04826     // at the reference variable. We will later display the "trail" of
04827     // reference variables using notes.
04828     diagLoc = refVars[0]->getLocStart();
04829     diagRange = refVars[0]->getSourceRange();
04830   }
04831 
04832   if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
04833     S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
04834                                              : diag::warn_ret_stack_addr)
04835      << DR->getDecl()->getDeclName() << diagRange;
04836   } else if (isa<BlockExpr>(stackE)) { // local block.
04837     S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
04838   } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
04839     S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
04840   } else { // local temporary.
04841     S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
04842                                                : diag::warn_ret_local_temp_addr)
04843      << diagRange;
04844   }
04845 
04846   // Display the "trail" of reference variables that we followed until we
04847   // found the problematic expression using notes.
04848   for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
04849     VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
04850     // If this var binds to another reference var, show the range of the next
04851     // var, otherwise the var binds to the problematic expression, in which case
04852     // show the range of the expression.
04853     SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
04854                                   : stackE->getSourceRange();
04855     S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
04856         << VD->getDeclName() << range;
04857   }
04858 }
04859 
04860 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
04861 ///  check if the expression in a return statement evaluates to an address
04862 ///  to a location on the stack, a local block, an address of a label, or a
04863 ///  reference to local temporary. The recursion is used to traverse the
04864 ///  AST of the return expression, with recursion backtracking when we
04865 ///  encounter a subexpression that (1) clearly does not lead to one of the
04866 ///  above problematic expressions (2) is something we cannot determine leads to
04867 ///  a problematic expression based on such local checking.
04868 ///
04869 ///  Both EvalAddr and EvalVal follow through reference variables to evaluate
04870 ///  the expression that they point to. Such variables are added to the
04871 ///  'refVars' vector so that we know what the reference variable "trail" was.
04872 ///
04873 ///  EvalAddr processes expressions that are pointers that are used as
04874 ///  references (and not L-values).  EvalVal handles all other values.
04875 ///  At the base case of the recursion is a check for the above problematic
04876 ///  expressions.
04877 ///
04878 ///  This implementation handles:
04879 ///
04880 ///   * pointer-to-pointer casts
04881 ///   * implicit conversions from array references to pointers
04882 ///   * taking the address of fields
04883 ///   * arbitrary interplay between "&" and "*" operators
04884 ///   * pointer arithmetic from an address of a stack variable
04885 ///   * taking the address of an array element where the array is on the stack
04886 static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
04887                       Decl *ParentDecl) {
04888   if (E->isTypeDependent())
04889     return nullptr;
04890 
04891   // We should only be called for evaluating pointer expressions.
04892   assert((E->getType()->isAnyPointerType() ||
04893           E->getType()->isBlockPointerType() ||
04894           E->getType()->isObjCQualifiedIdType()) &&
04895          "EvalAddr only works on pointers");
04896 
04897   E = E->IgnoreParens();
04898 
04899   // Our "symbolic interpreter" is just a dispatch off the currently
04900   // viewed AST node.  We then recursively traverse the AST by calling
04901   // EvalAddr and EvalVal appropriately.
04902   switch (E->getStmtClass()) {
04903   case Stmt::DeclRefExprClass: {
04904     DeclRefExpr *DR = cast<DeclRefExpr>(E);
04905 
04906     // If we leave the immediate function, the lifetime isn't about to end.
04907     if (DR->refersToEnclosingLocal())
04908       return nullptr;
04909 
04910     if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
04911       // If this is a reference variable, follow through to the expression that
04912       // it points to.
04913       if (V->hasLocalStorage() &&
04914           V->getType()->isReferenceType() && V->hasInit()) {
04915         // Add the reference variable to the "trail".
04916         refVars.push_back(DR);
04917         return EvalAddr(V->getInit(), refVars, ParentDecl);
04918       }
04919 
04920     return nullptr;
04921   }
04922 
04923   case Stmt::UnaryOperatorClass: {
04924     // The only unary operator that make sense to handle here
04925     // is AddrOf.  All others don't make sense as pointers.
04926     UnaryOperator *U = cast<UnaryOperator>(E);
04927 
04928     if (U->getOpcode() == UO_AddrOf)
04929       return EvalVal(U->getSubExpr(), refVars, ParentDecl);
04930     else
04931       return nullptr;
04932   }
04933 
04934   case Stmt::BinaryOperatorClass: {
04935     // Handle pointer arithmetic.  All other binary operators are not valid
04936     // in this context.
04937     BinaryOperator *B = cast<BinaryOperator>(E);
04938     BinaryOperatorKind op = B->getOpcode();
04939 
04940     if (op != BO_Add && op != BO_Sub)
04941       return nullptr;
04942 
04943     Expr *Base = B->getLHS();
04944 
04945     // Determine which argument is the real pointer base.  It could be
04946     // the RHS argument instead of the LHS.
04947     if (!Base->getType()->isPointerType()) Base = B->getRHS();
04948 
04949     assert (Base->getType()->isPointerType());
04950     return EvalAddr(Base, refVars, ParentDecl);
04951   }
04952 
04953   // For conditional operators we need to see if either the LHS or RHS are
04954   // valid DeclRefExpr*s.  If one of them is valid, we return it.
04955   case Stmt::ConditionalOperatorClass: {
04956     ConditionalOperator *C = cast<ConditionalOperator>(E);
04957 
04958     // Handle the GNU extension for missing LHS.
04959     // FIXME: That isn't a ConditionalOperator, so doesn't get here.
04960     if (Expr *LHSExpr = C->getLHS()) {
04961       // In C++, we can have a throw-expression, which has 'void' type.
04962       if (!LHSExpr->getType()->isVoidType())
04963         if (Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
04964           return LHS;
04965     }
04966 
04967     // In C++, we can have a throw-expression, which has 'void' type.
04968     if (C->getRHS()->getType()->isVoidType())
04969       return nullptr;
04970 
04971     return EvalAddr(C->getRHS(), refVars, ParentDecl);
04972   }
04973 
04974   case Stmt::BlockExprClass:
04975     if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
04976       return E; // local block.
04977     return nullptr;
04978 
04979   case Stmt::AddrLabelExprClass:
04980     return E; // address of label.
04981 
04982   case Stmt::ExprWithCleanupsClass:
04983     return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
04984                     ParentDecl);
04985 
04986   // For casts, we need to handle conversions from arrays to
04987   // pointer values, and pointer-to-pointer conversions.
04988   case Stmt::ImplicitCastExprClass:
04989   case Stmt::CStyleCastExprClass:
04990   case Stmt::CXXFunctionalCastExprClass:
04991   case Stmt::ObjCBridgedCastExprClass:
04992   case Stmt::CXXStaticCastExprClass:
04993   case Stmt::CXXDynamicCastExprClass:
04994   case Stmt::CXXConstCastExprClass:
04995   case Stmt::CXXReinterpretCastExprClass: {
04996     Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
04997     switch (cast<CastExpr>(E)->getCastKind()) {
04998     case CK_LValueToRValue:
04999     case CK_NoOp:
05000     case CK_BaseToDerived:
05001     case CK_DerivedToBase:
05002     case CK_UncheckedDerivedToBase:
05003     case CK_Dynamic:
05004     case CK_CPointerToObjCPointerCast:
05005     case CK_BlockPointerToObjCPointerCast:
05006     case CK_AnyPointerToBlockPointerCast:
05007       return EvalAddr(SubExpr, refVars, ParentDecl);
05008 
05009     case CK_ArrayToPointerDecay:
05010       return EvalVal(SubExpr, refVars, ParentDecl);
05011 
05012     case CK_BitCast:
05013       if (SubExpr->getType()->isAnyPointerType() ||
05014           SubExpr->getType()->isBlockPointerType() ||
05015           SubExpr->getType()->isObjCQualifiedIdType())
05016         return EvalAddr(SubExpr, refVars, ParentDecl);
05017       else
05018         return nullptr;
05019 
05020     default:
05021       return nullptr;
05022     }
05023   }
05024 
05025   case Stmt::MaterializeTemporaryExprClass:
05026     if (Expr *Result = EvalAddr(
05027                          cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
05028                                 refVars, ParentDecl))
05029       return Result;
05030       
05031     return E;
05032       
05033   // Everything else: we simply don't reason about them.
05034   default:
05035     return nullptr;
05036   }
05037 }
05038 
05039 
05040 ///  EvalVal - This function is complements EvalAddr in the mutual recursion.
05041 ///   See the comments for EvalAddr for more details.
05042 static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
05043                      Decl *ParentDecl) {
05044 do {
05045   // We should only be called for evaluating non-pointer expressions, or
05046   // expressions with a pointer type that are not used as references but instead
05047   // are l-values (e.g., DeclRefExpr with a pointer type).
05048 
05049   // Our "symbolic interpreter" is just a dispatch off the currently
05050   // viewed AST node.  We then recursively traverse the AST by calling
05051   // EvalAddr and EvalVal appropriately.
05052 
05053   E = E->IgnoreParens();
05054   switch (E->getStmtClass()) {
05055   case Stmt::ImplicitCastExprClass: {
05056     ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
05057     if (IE->getValueKind() == VK_LValue) {
05058       E = IE->getSubExpr();
05059       continue;
05060     }
05061     return nullptr;
05062   }
05063 
05064   case Stmt::ExprWithCleanupsClass:
05065     return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
05066 
05067   case Stmt::DeclRefExprClass: {
05068     // When we hit a DeclRefExpr we are looking at code that refers to a
05069     // variable's name. If it's not a reference variable we check if it has
05070     // local storage within the function, and if so, return the expression.
05071     DeclRefExpr *DR = cast<DeclRefExpr>(E);
05072 
05073     // If we leave the immediate function, the lifetime isn't about to end.
05074     if (DR->refersToEnclosingLocal())
05075       return nullptr;
05076 
05077     if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
05078       // Check if it refers to itself, e.g. "int& i = i;".
05079       if (V == ParentDecl)
05080         return DR;
05081 
05082       if (V->hasLocalStorage()) {
05083         if (!V->getType()->isReferenceType())
05084           return DR;
05085 
05086         // Reference variable, follow through to the expression that
05087         // it points to.
05088         if (V->hasInit()) {
05089           // Add the reference variable to the "trail".
05090           refVars.push_back(DR);
05091           return EvalVal(V->getInit(), refVars, V);
05092         }
05093       }
05094     }
05095 
05096     return nullptr;
05097   }
05098 
05099   case Stmt::UnaryOperatorClass: {
05100     // The only unary operator that make sense to handle here
05101     // is Deref.  All others don't resolve to a "name."  This includes
05102     // handling all sorts of rvalues passed to a unary operator.
05103     UnaryOperator *U = cast<UnaryOperator>(E);
05104 
05105     if (U->getOpcode() == UO_Deref)
05106       return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
05107 
05108     return nullptr;
05109   }
05110 
05111   case Stmt::ArraySubscriptExprClass: {
05112     // Array subscripts are potential references to data on the stack.  We
05113     // retrieve the DeclRefExpr* for the array variable if it indeed
05114     // has local storage.
05115     return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
05116   }
05117 
05118   case Stmt::ConditionalOperatorClass: {
05119     // For conditional operators we need to see if either the LHS or RHS are
05120     // non-NULL Expr's.  If one is non-NULL, we return it.
05121     ConditionalOperator *C = cast<ConditionalOperator>(E);
05122 
05123     // Handle the GNU extension for missing LHS.
05124     if (Expr *LHSExpr = C->getLHS()) {
05125       // In C++, we can have a throw-expression, which has 'void' type.
05126       if (!LHSExpr->getType()->isVoidType())
05127         if (Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
05128           return LHS;
05129     }
05130 
05131     // In C++, we can have a throw-expression, which has 'void' type.
05132     if (C->getRHS()->getType()->isVoidType())
05133       return nullptr;
05134 
05135     return EvalVal(C->getRHS(), refVars, ParentDecl);
05136   }
05137 
05138   // Accesses to members are potential references to data on the stack.
05139   case Stmt::MemberExprClass: {
05140     MemberExpr *M = cast<MemberExpr>(E);
05141 
05142     // Check for indirect access.  We only want direct field accesses.
05143     if (M->isArrow())
05144       return nullptr;
05145 
05146     // Check whether the member type is itself a reference, in which case
05147     // we're not going to refer to the member, but to what the member refers to.
05148     if (M->getMemberDecl()->getType()->isReferenceType())
05149       return nullptr;
05150 
05151     return EvalVal(M->getBase(), refVars, ParentDecl);
05152   }
05153 
05154   case Stmt::MaterializeTemporaryExprClass:
05155     if (Expr *Result = EvalVal(
05156                           cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
05157                                refVars, ParentDecl))
05158       return Result;
05159       
05160     return E;
05161 
05162   default:
05163     // Check that we don't return or take the address of a reference to a
05164     // temporary. This is only useful in C++.
05165     if (!E->isTypeDependent() && E->isRValue())
05166       return E;
05167 
05168     // Everything else: we simply don't reason about them.
05169     return nullptr;
05170   }
05171 } while (true);
05172 }
05173 
05174 void
05175 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
05176                          SourceLocation ReturnLoc,
05177                          bool isObjCMethod,
05178                          const AttrVec *Attrs,
05179                          const FunctionDecl *FD) {
05180   CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
05181 
05182   // Check if the return value is null but should not be.
05183   if (Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs) &&
05184       CheckNonNullExpr(*this, RetValExp))
05185     Diag(ReturnLoc, diag::warn_null_ret)
05186       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
05187 
05188   // C++11 [basic.stc.dynamic.allocation]p4:
05189   //   If an allocation function declared with a non-throwing
05190   //   exception-specification fails to allocate storage, it shall return
05191   //   a null pointer. Any other allocation function that fails to allocate
05192   //   storage shall indicate failure only by throwing an exception [...]
05193   if (FD) {
05194     OverloadedOperatorKind Op = FD->getOverloadedOperator();
05195     if (Op == OO_New || Op == OO_Array_New) {
05196       const FunctionProtoType *Proto
05197         = FD->getType()->castAs<FunctionProtoType>();
05198       if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
05199           CheckNonNullExpr(*this, RetValExp))
05200         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
05201           << FD << getLangOpts().CPlusPlus11;
05202     }
05203   }
05204 }
05205 
05206 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
05207 
05208 /// Check for comparisons of floating point operands using != and ==.
05209 /// Issue a warning if these are no self-comparisons, as they are not likely
05210 /// to do what the programmer intended.
05211 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
05212   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
05213   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
05214 
05215   // Special case: check for x == x (which is OK).
05216   // Do not emit warnings for such cases.
05217   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
05218     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
05219       if (DRL->getDecl() == DRR->getDecl())
05220         return;
05221 
05222 
05223   // Special case: check for comparisons against literals that can be exactly
05224   //  represented by APFloat.  In such cases, do not emit a warning.  This
05225   //  is a heuristic: often comparison against such literals are used to
05226   //  detect if a value in a variable has not changed.  This clearly can
05227   //  lead to false negatives.
05228   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
05229     if (FLL->isExact())
05230       return;
05231   } else
05232     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
05233       if (FLR->isExact())
05234         return;
05235 
05236   // Check for comparisons with builtin types.
05237   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
05238     if (CL->getBuiltinCallee())
05239       return;
05240 
05241   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
05242     if (CR->getBuiltinCallee())
05243       return;
05244 
05245   // Emit the diagnostic.
05246   Diag(Loc, diag::warn_floatingpoint_eq)
05247     << LHS->getSourceRange() << RHS->getSourceRange();
05248 }
05249 
05250 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
05251 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
05252 
05253 namespace {
05254 
05255 /// Structure recording the 'active' range of an integer-valued
05256 /// expression.
05257 struct IntRange {
05258   /// The number of bits active in the int.
05259   unsigned Width;
05260 
05261   /// True if the int is known not to have negative values.
05262   bool NonNegative;
05263 
05264   IntRange(unsigned Width, bool NonNegative)
05265     : Width(Width), NonNegative(NonNegative)
05266   {}
05267 
05268   /// Returns the range of the bool type.
05269   static IntRange forBoolType() {
05270     return IntRange(1, true);
05271   }
05272 
05273   /// Returns the range of an opaque value of the given integral type.
05274   static IntRange forValueOfType(ASTContext &C, QualType T) {
05275     return forValueOfCanonicalType(C,
05276                           T->getCanonicalTypeInternal().getTypePtr());
05277   }
05278 
05279   /// Returns the range of an opaque value of a canonical integral type.
05280   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
05281     assert(T->isCanonicalUnqualified());
05282 
05283     if (const VectorType *VT = dyn_cast<VectorType>(T))
05284       T = VT->getElementType().getTypePtr();
05285     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
05286       T = CT->getElementType().getTypePtr();
05287     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
05288       T = AT->getValueType().getTypePtr();
05289 
05290     // For enum types, use the known bit width of the enumerators.
05291     if (const EnumType *ET = dyn_cast<EnumType>(T)) {
05292       EnumDecl *Enum = ET->getDecl();
05293       if (!Enum->isCompleteDefinition())
05294         return IntRange(C.getIntWidth(QualType(T, 0)), false);
05295 
05296       unsigned NumPositive = Enum->getNumPositiveBits();
05297       unsigned NumNegative = Enum->getNumNegativeBits();
05298 
05299       if (NumNegative == 0)
05300         return IntRange(NumPositive, true/*NonNegative*/);
05301       else
05302         return IntRange(std::max(NumPositive + 1, NumNegative),
05303                         false/*NonNegative*/);
05304     }
05305 
05306     const BuiltinType *BT = cast<BuiltinType>(T);
05307     assert(BT->isInteger());
05308 
05309     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
05310   }
05311 
05312   /// Returns the "target" range of a canonical integral type, i.e.
05313   /// the range of values expressible in the type.
05314   ///
05315   /// This matches forValueOfCanonicalType except that enums have the
05316   /// full range of their type, not the range of their enumerators.
05317   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
05318     assert(T->isCanonicalUnqualified());
05319 
05320     if (const VectorType *VT = dyn_cast<VectorType>(T))
05321       T = VT->getElementType().getTypePtr();
05322     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
05323       T = CT->getElementType().getTypePtr();
05324     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
05325       T = AT->getValueType().getTypePtr();
05326     if (const EnumType *ET = dyn_cast<EnumType>(T))
05327       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
05328 
05329     const BuiltinType *BT = cast<BuiltinType>(T);
05330     assert(BT->isInteger());
05331 
05332     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
05333   }
05334 
05335   /// Returns the supremum of two ranges: i.e. their conservative merge.
05336   static IntRange join(IntRange L, IntRange R) {
05337     return IntRange(std::max(L.Width, R.Width),
05338                     L.NonNegative && R.NonNegative);
05339   }
05340 
05341   /// Returns the infinum of two ranges: i.e. their aggressive merge.
05342   static IntRange meet(IntRange L, IntRange R) {
05343     return IntRange(std::min(L.Width, R.Width),
05344                     L.NonNegative || R.NonNegative);
05345   }
05346 };
05347 
05348 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
05349                               unsigned MaxWidth) {
05350   if (value.isSigned() && value.isNegative())
05351     return IntRange(value.getMinSignedBits(), false);
05352 
05353   if (value.getBitWidth() > MaxWidth)
05354     value = value.trunc(MaxWidth);
05355 
05356   // isNonNegative() just checks the sign bit without considering
05357   // signedness.
05358   return IntRange(value.getActiveBits(), true);
05359 }
05360 
05361 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
05362                               unsigned MaxWidth) {
05363   if (result.isInt())
05364     return GetValueRange(C, result.getInt(), MaxWidth);
05365 
05366   if (result.isVector()) {
05367     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
05368     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
05369       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
05370       R = IntRange::join(R, El);
05371     }
05372     return R;
05373   }
05374 
05375   if (result.isComplexInt()) {
05376     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
05377     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
05378     return IntRange::join(R, I);
05379   }
05380 
05381   // This can happen with lossless casts to intptr_t of "based" lvalues.
05382   // Assume it might use arbitrary bits.
05383   // FIXME: The only reason we need to pass the type in here is to get
05384   // the sign right on this one case.  It would be nice if APValue
05385   // preserved this.
05386   assert(result.isLValue() || result.isAddrLabelDiff());
05387   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
05388 }
05389 
05390 static QualType GetExprType(Expr *E) {
05391   QualType Ty = E->getType();
05392   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
05393     Ty = AtomicRHS->getValueType();
05394   return Ty;
05395 }
05396 
05397 /// Pseudo-evaluate the given integer expression, estimating the
05398 /// range of values it might take.
05399 ///
05400 /// \param MaxWidth - the width to which the value will be truncated
05401 static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
05402   E = E->IgnoreParens();
05403 
05404   // Try a full evaluation first.
05405   Expr::EvalResult result;
05406   if (E->EvaluateAsRValue(result, C))
05407     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
05408 
05409   // I think we only want to look through implicit casts here; if the
05410   // user has an explicit widening cast, we should treat the value as
05411   // being of the new, wider type.
05412   if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
05413     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
05414       return GetExprRange(C, CE->getSubExpr(), MaxWidth);
05415 
05416     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
05417 
05418     bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
05419 
05420     // Assume that non-integer casts can span the full range of the type.
05421     if (!isIntegerCast)
05422       return OutputTypeRange;
05423 
05424     IntRange SubRange
05425       = GetExprRange(C, CE->getSubExpr(),
05426                      std::min(MaxWidth, OutputTypeRange.Width));
05427 
05428     // Bail out if the subexpr's range is as wide as the cast type.
05429     if (SubRange.Width >= OutputTypeRange.Width)
05430       return OutputTypeRange;
05431 
05432     // Otherwise, we take the smaller width, and we're non-negative if
05433     // either the output type or the subexpr is.
05434     return IntRange(SubRange.Width,
05435                     SubRange.NonNegative || OutputTypeRange.NonNegative);
05436   }
05437 
05438   if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
05439     // If we can fold the condition, just take that operand.
05440     bool CondResult;
05441     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
05442       return GetExprRange(C, CondResult ? CO->getTrueExpr()
05443                                         : CO->getFalseExpr(),
05444                           MaxWidth);
05445 
05446     // Otherwise, conservatively merge.
05447     IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
05448     IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
05449     return IntRange::join(L, R);
05450   }
05451 
05452   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
05453     switch (BO->getOpcode()) {
05454 
05455     // Boolean-valued operations are single-bit and positive.
05456     case BO_LAnd:
05457     case BO_LOr:
05458     case BO_LT:
05459     case BO_GT:
05460     case BO_LE:
05461     case BO_GE:
05462     case BO_EQ:
05463     case BO_NE:
05464       return IntRange::forBoolType();
05465 
05466     // The type of the assignments is the type of the LHS, so the RHS
05467     // is not necessarily the same type.
05468     case BO_MulAssign:
05469     case BO_DivAssign:
05470     case BO_RemAssign:
05471     case BO_AddAssign:
05472     case BO_SubAssign:
05473     case BO_XorAssign:
05474     case BO_OrAssign:
05475       // TODO: bitfields?
05476       return IntRange::forValueOfType(C, GetExprType(E));
05477 
05478     // Simple assignments just pass through the RHS, which will have
05479     // been coerced to the LHS type.
05480     case BO_Assign:
05481       // TODO: bitfields?
05482       return GetExprRange(C, BO->getRHS(), MaxWidth);
05483 
05484     // Operations with opaque sources are black-listed.
05485     case BO_PtrMemD:
05486     case BO_PtrMemI:
05487       return IntRange::forValueOfType(C, GetExprType(E));
05488 
05489     // Bitwise-and uses the *infinum* of the two source ranges.
05490     case BO_And:
05491     case BO_AndAssign:
05492       return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
05493                             GetExprRange(C, BO->getRHS(), MaxWidth));
05494 
05495     // Left shift gets black-listed based on a judgement call.
05496     case BO_Shl:
05497       // ...except that we want to treat '1 << (blah)' as logically
05498       // positive.  It's an important idiom.
05499       if (IntegerLiteral *I
05500             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
05501         if (I->getValue() == 1) {
05502           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
05503           return IntRange(R.Width, /*NonNegative*/ true);
05504         }
05505       }
05506       // fallthrough
05507 
05508     case BO_ShlAssign:
05509       return IntRange::forValueOfType(C, GetExprType(E));
05510 
05511     // Right shift by a constant can narrow its left argument.
05512     case BO_Shr:
05513     case BO_ShrAssign: {
05514       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
05515 
05516       // If the shift amount is a positive constant, drop the width by
05517       // that much.
05518       llvm::APSInt shift;
05519       if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
05520           shift.isNonNegative()) {
05521         unsigned zext = shift.getZExtValue();
05522         if (zext >= L.Width)
05523           L.Width = (L.NonNegative ? 0 : 1);
05524         else
05525           L.Width -= zext;
05526       }
05527 
05528       return L;
05529     }
05530 
05531     // Comma acts as its right operand.
05532     case BO_Comma:
05533       return GetExprRange(C, BO->getRHS(), MaxWidth);
05534 
05535     // Black-list pointer subtractions.
05536     case BO_Sub:
05537       if (BO->getLHS()->getType()->isPointerType())
05538         return IntRange::forValueOfType(C, GetExprType(E));
05539       break;
05540 
05541     // The width of a division result is mostly determined by the size
05542     // of the LHS.
05543     case BO_Div: {
05544       // Don't 'pre-truncate' the operands.
05545       unsigned opWidth = C.getIntWidth(GetExprType(E));
05546       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
05547 
05548       // If the divisor is constant, use that.
05549       llvm::APSInt divisor;
05550       if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
05551         unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
05552         if (log2 >= L.Width)
05553           L.Width = (L.NonNegative ? 0 : 1);
05554         else
05555           L.Width = std::min(L.Width - log2, MaxWidth);
05556         return L;
05557       }
05558 
05559       // Otherwise, just use the LHS's width.
05560       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
05561       return IntRange(L.Width, L.NonNegative && R.NonNegative);
05562     }
05563 
05564     // The result of a remainder can't be larger than the result of
05565     // either side.
05566     case BO_Rem: {
05567       // Don't 'pre-truncate' the operands.
05568       unsigned opWidth = C.getIntWidth(GetExprType(E));
05569       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
05570       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
05571 
05572       IntRange meet = IntRange::meet(L, R);
05573       meet.Width = std::min(meet.Width, MaxWidth);
05574       return meet;
05575     }
05576 
05577     // The default behavior is okay for these.
05578     case BO_Mul:
05579     case BO_Add:
05580     case BO_Xor:
05581     case BO_Or:
05582       break;
05583     }
05584 
05585     // The default case is to treat the operation as if it were closed
05586     // on the narrowest type that encompasses both operands.
05587     IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
05588     IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
05589     return IntRange::join(L, R);
05590   }
05591 
05592   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
05593     switch (UO->getOpcode()) {
05594     // Boolean-valued operations are white-listed.
05595     case UO_LNot:
05596       return IntRange::forBoolType();
05597 
05598     // Operations with opaque sources are black-listed.
05599     case UO_Deref:
05600     case UO_AddrOf: // should be impossible
05601       return IntRange::forValueOfType(C, GetExprType(E));
05602 
05603     default:
05604       return GetExprRange(C, UO->getSubExpr(), MaxWidth);
05605     }
05606   }
05607 
05608   if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
05609     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
05610 
05611   if (FieldDecl *BitField = E->getSourceBitField())
05612     return IntRange(BitField->getBitWidthValue(C),
05613                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
05614 
05615   return IntRange::forValueOfType(C, GetExprType(E));
05616 }
05617 
05618 static IntRange GetExprRange(ASTContext &C, Expr *E) {
05619   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
05620 }
05621 
05622 /// Checks whether the given value, which currently has the given
05623 /// source semantics, has the same value when coerced through the
05624 /// target semantics.
05625 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
05626                                  const llvm::fltSemantics &Src,
05627                                  const llvm::fltSemantics &Tgt) {
05628   llvm::APFloat truncated = value;
05629 
05630   bool ignored;
05631   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
05632   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
05633 
05634   return truncated.bitwiseIsEqual(value);
05635 }
05636 
05637 /// Checks whether the given value, which currently has the given
05638 /// source semantics, has the same value when coerced through the
05639 /// target semantics.
05640 ///
05641 /// The value might be a vector of floats (or a complex number).
05642 static bool IsSameFloatAfterCast(const APValue &value,
05643                                  const llvm::fltSemantics &Src,
05644                                  const llvm::fltSemantics &Tgt) {
05645   if (value.isFloat())
05646     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
05647 
05648   if (value.isVector()) {
05649     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
05650       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
05651         return false;
05652     return true;
05653   }
05654 
05655   assert(value.isComplexFloat());
05656   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
05657           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
05658 }
05659 
05660 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
05661 
05662 static bool IsZero(Sema &S, Expr *E) {
05663   // Suppress cases where we are comparing against an enum constant.
05664   if (const DeclRefExpr *DR =
05665       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
05666     if (isa<EnumConstantDecl>(DR->getDecl()))
05667       return false;
05668 
05669   // Suppress cases where the '0' value is expanded from a macro.
05670   if (E->getLocStart().isMacroID())
05671     return false;
05672 
05673   llvm::APSInt Value;
05674   return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
05675 }
05676 
05677 static bool HasEnumType(Expr *E) {
05678   // Strip off implicit integral promotions.
05679   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
05680     if (ICE->getCastKind() != CK_IntegralCast &&
05681         ICE->getCastKind() != CK_NoOp)
05682       break;
05683     E = ICE->getSubExpr();
05684   }
05685 
05686   return E->getType()->isEnumeralType();
05687 }
05688 
05689 static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
05690   // Disable warning in template instantiations.
05691   if (!S.ActiveTemplateInstantiations.empty())
05692     return;
05693 
05694   BinaryOperatorKind op = E->getOpcode();
05695   if (E->isValueDependent())
05696     return;
05697 
05698   if (op == BO_LT && IsZero(S, E->getRHS())) {
05699     S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
05700       << "< 0" << "false" << HasEnumType(E->getLHS())
05701       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
05702   } else if (op == BO_GE && IsZero(S, E->getRHS())) {
05703     S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
05704       << ">= 0" << "true" << HasEnumType(E->getLHS())
05705       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
05706   } else if (op == BO_GT && IsZero(S, E->getLHS())) {
05707     S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
05708       << "0 >" << "false" << HasEnumType(E->getRHS())
05709       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
05710   } else if (op == BO_LE && IsZero(S, E->getLHS())) {
05711     S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
05712       << "0 <=" << "true" << HasEnumType(E->getRHS())
05713       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
05714   }
05715 }
05716 
05717 static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
05718                                          Expr *Constant, Expr *Other,
05719                                          llvm::APSInt Value,
05720                                          bool RhsConstant) {
05721   // Disable warning in template instantiations.
05722   if (!S.ActiveTemplateInstantiations.empty())
05723     return;
05724 
05725   // TODO: Investigate using GetExprRange() to get tighter bounds
05726   // on the bit ranges.
05727   QualType OtherT = Other->getType();
05728   if (const AtomicType *AT = dyn_cast<AtomicType>(OtherT))
05729     OtherT = AT->getValueType();
05730   IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
05731   unsigned OtherWidth = OtherRange.Width;
05732 
05733   bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
05734 
05735   // 0 values are handled later by CheckTrivialUnsignedComparison().
05736   if ((Value == 0) && (!OtherIsBooleanType))
05737     return;
05738 
05739   BinaryOperatorKind op = E->getOpcode();
05740   bool IsTrue = true;
05741 
05742   // Used for diagnostic printout.
05743   enum {
05744     LiteralConstant = 0,
05745     CXXBoolLiteralTrue,
05746     CXXBoolLiteralFalse
05747   } LiteralOrBoolConstant = LiteralConstant;
05748 
05749   if (!OtherIsBooleanType) {
05750     QualType ConstantT = Constant->getType();
05751     QualType CommonT = E->getLHS()->getType();
05752 
05753     if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
05754       return;
05755     assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
05756            "comparison with non-integer type");
05757 
05758     bool ConstantSigned = ConstantT->isSignedIntegerType();
05759     bool CommonSigned = CommonT->isSignedIntegerType();
05760 
05761     bool EqualityOnly = false;
05762 
05763     if (CommonSigned) {
05764       // The common type is signed, therefore no signed to unsigned conversion.
05765       if (!OtherRange.NonNegative) {
05766         // Check that the constant is representable in type OtherT.
05767         if (ConstantSigned) {
05768           if (OtherWidth >= Value.getMinSignedBits())
05769             return;
05770         } else { // !ConstantSigned
05771           if (OtherWidth >= Value.getActiveBits() + 1)
05772             return;
05773         }
05774       } else { // !OtherSigned
05775                // Check that the constant is representable in type OtherT.
05776         // Negative values are out of range.
05777         if (ConstantSigned) {
05778           if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
05779             return;
05780         } else { // !ConstantSigned
05781           if (OtherWidth >= Value.getActiveBits())
05782             return;
05783         }
05784       }
05785     } else { // !CommonSigned
05786       if (OtherRange.NonNegative) {
05787         if (OtherWidth >= Value.getActiveBits())
05788           return;
05789       } else { // OtherSigned
05790         assert(!ConstantSigned &&
05791                "Two signed types converted to unsigned types.");
05792         // Check to see if the constant is representable in OtherT.
05793         if (OtherWidth > Value.getActiveBits())
05794           return;
05795         // Check to see if the constant is equivalent to a negative value
05796         // cast to CommonT.
05797         if (S.Context.getIntWidth(ConstantT) ==
05798                 S.Context.getIntWidth(CommonT) &&
05799             Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
05800           return;
05801         // The constant value rests between values that OtherT can represent
05802         // after conversion.  Relational comparison still works, but equality
05803         // comparisons will be tautological.
05804         EqualityOnly = true;
05805       }
05806     }
05807 
05808     bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
05809 
05810     if (op == BO_EQ || op == BO_NE) {
05811       IsTrue = op == BO_NE;
05812     } else if (EqualityOnly) {
05813       return;
05814     } else if (RhsConstant) {
05815       if (op == BO_GT || op == BO_GE)
05816         IsTrue = !PositiveConstant;
05817       else // op == BO_LT || op == BO_LE
05818         IsTrue = PositiveConstant;
05819     } else {
05820       if (op == BO_LT || op == BO_LE)
05821         IsTrue = !PositiveConstant;
05822       else // op == BO_GT || op == BO_GE
05823         IsTrue = PositiveConstant;
05824     }
05825   } else {
05826     // Other isKnownToHaveBooleanValue
05827     enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
05828     enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
05829     enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
05830 
05831     static const struct LinkedConditions {
05832       CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
05833       CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
05834       CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
05835       CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
05836       CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
05837       CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
05838 
05839     } TruthTable = {
05840         // Constant on LHS.              | Constant on RHS.              |
05841         // LT_Zero| Zero  | One   |GT_One| LT_Zero| Zero  | One   |GT_One|
05842         { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
05843         { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
05844         { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
05845         { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
05846         { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
05847         { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
05848       };
05849 
05850     bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
05851 
05852     enum ConstantValue ConstVal = Zero;
05853     if (Value.isUnsigned() || Value.isNonNegative()) {
05854       if (Value == 0) {
05855         LiteralOrBoolConstant =
05856             ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
05857         ConstVal = Zero;
05858       } else if (Value == 1) {
05859         LiteralOrBoolConstant =
05860             ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
05861         ConstVal = One;
05862       } else {
05863         LiteralOrBoolConstant = LiteralConstant;
05864         ConstVal = GT_One;
05865       }
05866     } else {
05867       ConstVal = LT_Zero;
05868     }
05869 
05870     CompareBoolWithConstantResult CmpRes;
05871 
05872     switch (op) {
05873     case BO_LT:
05874       CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
05875       break;
05876     case BO_GT:
05877       CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
05878       break;
05879     case BO_LE:
05880       CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
05881       break;
05882     case BO_GE:
05883       CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
05884       break;
05885     case BO_EQ:
05886       CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
05887       break;
05888     case BO_NE:
05889       CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
05890       break;
05891     default:
05892       CmpRes = Unkwn;
05893       break;
05894     }
05895 
05896     if (CmpRes == AFals) {
05897       IsTrue = false;
05898     } else if (CmpRes == ATrue) {
05899       IsTrue = true;
05900     } else {
05901       return;
05902     }
05903   }
05904 
05905   // If this is a comparison to an enum constant, include that
05906   // constant in the diagnostic.
05907   const EnumConstantDecl *ED = nullptr;
05908   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
05909     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
05910 
05911   SmallString<64> PrettySourceValue;
05912   llvm::raw_svector_ostream OS(PrettySourceValue);
05913   if (ED)
05914     OS << '\'' << *ED << "' (" << Value << ")";
05915   else
05916     OS << Value;
05917 
05918   S.DiagRuntimeBehavior(
05919     E->getOperatorLoc(), E,
05920     S.PDiag(diag::warn_out_of_range_compare)
05921         << OS.str() << LiteralOrBoolConstant
05922         << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
05923         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
05924 }
05925 
05926 /// Analyze the operands of the given comparison.  Implements the
05927 /// fallback case from AnalyzeComparison.
05928 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
05929   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
05930   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
05931 }
05932 
05933 /// \brief Implements -Wsign-compare.
05934 ///
05935 /// \param E the binary operator to check for warnings
05936 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
05937   // The type the comparison is being performed in.
05938   QualType T = E->getLHS()->getType();
05939 
05940   // Only analyze comparison operators where both sides have been converted to
05941   // the same type.
05942   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
05943     return AnalyzeImpConvsInComparison(S, E);
05944 
05945   // Don't analyze value-dependent comparisons directly.
05946   if (E->isValueDependent())
05947     return AnalyzeImpConvsInComparison(S, E);
05948 
05949   Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
05950   Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
05951   
05952   bool IsComparisonConstant = false;
05953   
05954   // Check whether an integer constant comparison results in a value
05955   // of 'true' or 'false'.
05956   if (T->isIntegralType(S.Context)) {
05957     llvm::APSInt RHSValue;
05958     bool IsRHSIntegralLiteral = 
05959       RHS->isIntegerConstantExpr(RHSValue, S.Context);
05960     llvm::APSInt LHSValue;
05961     bool IsLHSIntegralLiteral = 
05962       LHS->isIntegerConstantExpr(LHSValue, S.Context);
05963     if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
05964         DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
05965     else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
05966       DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
05967     else
05968       IsComparisonConstant = 
05969         (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
05970   } else if (!T->hasUnsignedIntegerRepresentation())
05971       IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
05972   
05973   // We don't do anything special if this isn't an unsigned integral
05974   // comparison:  we're only interested in integral comparisons, and
05975   // signed comparisons only happen in cases we don't care to warn about.
05976   //
05977   // We also don't care about value-dependent expressions or expressions
05978   // whose result is a constant.
05979   if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
05980     return AnalyzeImpConvsInComparison(S, E);
05981   
05982   // Check to see if one of the (unmodified) operands is of different
05983   // signedness.
05984   Expr *signedOperand, *unsignedOperand;
05985   if (LHS->getType()->hasSignedIntegerRepresentation()) {
05986     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
05987            "unsigned comparison between two signed integer expressions?");
05988     signedOperand = LHS;
05989     unsignedOperand = RHS;
05990   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
05991     signedOperand = RHS;
05992     unsignedOperand = LHS;
05993   } else {
05994     CheckTrivialUnsignedComparison(S, E);
05995     return AnalyzeImpConvsInComparison(S, E);
05996   }
05997 
05998   // Otherwise, calculate the effective range of the signed operand.
05999   IntRange signedRange = GetExprRange(S.Context, signedOperand);
06000 
06001   // Go ahead and analyze implicit conversions in the operands.  Note
06002   // that we skip the implicit conversions on both sides.
06003   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
06004   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
06005 
06006   // If the signed range is non-negative, -Wsign-compare won't fire,
06007   // but we should still check for comparisons which are always true
06008   // or false.
06009   if (signedRange.NonNegative)
06010     return CheckTrivialUnsignedComparison(S, E);
06011 
06012   // For (in)equality comparisons, if the unsigned operand is a
06013   // constant which cannot collide with a overflowed signed operand,
06014   // then reinterpreting the signed operand as unsigned will not
06015   // change the result of the comparison.
06016   if (E->isEqualityOp()) {
06017     unsigned comparisonWidth = S.Context.getIntWidth(T);
06018     IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
06019 
06020     // We should never be unable to prove that the unsigned operand is
06021     // non-negative.
06022     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
06023 
06024     if (unsignedRange.Width < comparisonWidth)
06025       return;
06026   }
06027 
06028   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
06029     S.PDiag(diag::warn_mixed_sign_comparison)
06030       << LHS->getType() << RHS->getType()
06031       << LHS->getSourceRange() << RHS->getSourceRange());
06032 }
06033 
06034 /// Analyzes an attempt to assign the given value to a bitfield.
06035 ///
06036 /// Returns true if there was something fishy about the attempt.
06037 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
06038                                       SourceLocation InitLoc) {
06039   assert(Bitfield->isBitField());
06040   if (Bitfield->isInvalidDecl())
06041     return false;
06042 
06043   // White-list bool bitfields.
06044   if (Bitfield->getType()->isBooleanType())
06045     return false;
06046 
06047   // Ignore value- or type-dependent expressions.
06048   if (Bitfield->getBitWidth()->isValueDependent() ||
06049       Bitfield->getBitWidth()->isTypeDependent() ||
06050       Init->isValueDependent() ||
06051       Init->isTypeDependent())
06052     return false;
06053 
06054   Expr *OriginalInit = Init->IgnoreParenImpCasts();
06055 
06056   llvm::APSInt Value;
06057   if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
06058     return false;
06059 
06060   unsigned OriginalWidth = Value.getBitWidth();
06061   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
06062 
06063   if (OriginalWidth <= FieldWidth)
06064     return false;
06065 
06066   // Compute the value which the bitfield will contain.
06067   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
06068   TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
06069 
06070   // Check whether the stored value is equal to the original value.
06071   TruncatedValue = TruncatedValue.extend(OriginalWidth);
06072   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
06073     return false;
06074 
06075   // Special-case bitfields of width 1: booleans are naturally 0/1, and
06076   // therefore don't strictly fit into a signed bitfield of width 1.
06077   if (FieldWidth == 1 && Value == 1)
06078     return false;
06079 
06080   std::string PrettyValue = Value.toString(10);
06081   std::string PrettyTrunc = TruncatedValue.toString(10);
06082 
06083   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
06084     << PrettyValue << PrettyTrunc << OriginalInit->getType()
06085     << Init->getSourceRange();
06086 
06087   return true;
06088 }
06089 
06090 /// Analyze the given simple or compound assignment for warning-worthy
06091 /// operations.
06092 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
06093   // Just recurse on the LHS.
06094   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
06095 
06096   // We want to recurse on the RHS as normal unless we're assigning to
06097   // a bitfield.
06098   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
06099     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
06100                                   E->getOperatorLoc())) {
06101       // Recurse, ignoring any implicit conversions on the RHS.
06102       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
06103                                         E->getOperatorLoc());
06104     }
06105   }
06106 
06107   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
06108 }
06109 
06110 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
06111 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 
06112                             SourceLocation CContext, unsigned diag,
06113                             bool pruneControlFlow = false) {
06114   if (pruneControlFlow) {
06115     S.DiagRuntimeBehavior(E->getExprLoc(), E,
06116                           S.PDiag(diag)
06117                             << SourceType << T << E->getSourceRange()
06118                             << SourceRange(CContext));
06119     return;
06120   }
06121   S.Diag(E->getExprLoc(), diag)
06122     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
06123 }
06124 
06125 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
06126 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
06127                             SourceLocation CContext, unsigned diag,
06128                             bool pruneControlFlow = false) {
06129   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
06130 }
06131 
06132 /// Diagnose an implicit cast from a literal expression. Does not warn when the
06133 /// cast wouldn't lose information.
06134 void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
06135                                     SourceLocation CContext) {
06136   // Try to convert the literal exactly to an integer. If we can, don't warn.
06137   bool isExact = false;
06138   const llvm::APFloat &Value = FL->getValue();
06139   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
06140                             T->hasUnsignedIntegerRepresentation());
06141   if (Value.convertToInteger(IntegerValue,
06142                              llvm::APFloat::rmTowardZero, &isExact)
06143       == llvm::APFloat::opOK && isExact)
06144     return;
06145 
06146   // FIXME: Force the precision of the source value down so we don't print
06147   // digits which are usually useless (we don't really care here if we
06148   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
06149   // would automatically print the shortest representation, but it's a bit
06150   // tricky to implement.
06151   SmallString<16> PrettySourceValue;
06152   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
06153   precision = (precision * 59 + 195) / 196;
06154   Value.toString(PrettySourceValue, precision);
06155 
06156   SmallString<16> PrettyTargetValue;
06157   if (T->isSpecificBuiltinType(BuiltinType::Bool))
06158     PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
06159   else
06160     IntegerValue.toString(PrettyTargetValue);
06161 
06162   S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
06163     << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
06164     << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
06165 }
06166 
06167 std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
06168   if (!Range.Width) return "0";
06169 
06170   llvm::APSInt ValueInRange = Value;
06171   ValueInRange.setIsSigned(!Range.NonNegative);
06172   ValueInRange = ValueInRange.trunc(Range.Width);
06173   return ValueInRange.toString(10);
06174 }
06175 
06176 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
06177   if (!isa<ImplicitCastExpr>(Ex))
06178     return false;
06179 
06180   Expr *InnerE = Ex->IgnoreParenImpCasts();
06181   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
06182   const Type *Source =
06183     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
06184   if (Target->isDependentType())
06185     return false;
06186 
06187   const BuiltinType *FloatCandidateBT =
06188     dyn_cast<BuiltinType>(ToBool ? Source : Target);
06189   const Type *BoolCandidateType = ToBool ? Target : Source;
06190 
06191   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
06192           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
06193 }
06194 
06195 void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
06196                                       SourceLocation CC) {
06197   unsigned NumArgs = TheCall->getNumArgs();
06198   for (unsigned i = 0; i < NumArgs; ++i) {
06199     Expr *CurrA = TheCall->getArg(i);
06200     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
06201       continue;
06202 
06203     bool IsSwapped = ((i > 0) &&
06204         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
06205     IsSwapped |= ((i < (NumArgs - 1)) &&
06206         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
06207     if (IsSwapped) {
06208       // Warn on this floating-point to bool conversion.
06209       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
06210                       CurrA->getType(), CC,
06211                       diag::warn_impcast_floating_point_to_bool);
06212     }
06213   }
06214 }
06215 
06216 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
06217                                    SourceLocation CC) {
06218   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
06219                         E->getExprLoc()))
06220     return;
06221 
06222   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
06223   const Expr::NullPointerConstantKind NullKind =
06224       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
06225   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
06226     return;
06227 
06228   // Return if target type is a safe conversion.
06229   if (T->isAnyPointerType() || T->isBlockPointerType() ||
06230       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
06231     return;
06232 
06233   SourceLocation Loc = E->getSourceRange().getBegin();
06234 
06235   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
06236   if (NullKind == Expr::NPCK_GNUNull) {
06237     if (Loc.isMacroID())
06238       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
06239   }
06240 
06241   // Only warn if the null and context location are in the same macro expansion.
06242   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
06243     return;
06244 
06245   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
06246       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
06247       << FixItHint::CreateReplacement(Loc,
06248                                       S.getFixItZeroLiteralForType(T, Loc));
06249 }
06250 
06251 void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
06252                              SourceLocation CC, bool *ICContext = nullptr) {
06253   if (E->isTypeDependent() || E->isValueDependent()) return;
06254 
06255   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
06256   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
06257   if (Source == Target) return;
06258   if (Target->isDependentType()) return;
06259 
06260   // If the conversion context location is invalid don't complain. We also
06261   // don't want to emit a warning if the issue occurs from the expansion of
06262   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
06263   // delay this check as long as possible. Once we detect we are in that
06264   // scenario, we just return.
06265   if (CC.isInvalid())
06266     return;
06267 
06268   // Diagnose implicit casts to bool.
06269   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
06270     if (isa<StringLiteral>(E))
06271       // Warn on string literal to bool.  Checks for string literals in logical
06272       // and expressions, for instance, assert(0 && "error here"), are
06273       // prevented by a check in AnalyzeImplicitConversions().
06274       return DiagnoseImpCast(S, E, T, CC,
06275                              diag::warn_impcast_string_literal_to_bool);
06276     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
06277         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
06278       // This covers the literal expressions that evaluate to Objective-C
06279       // objects.
06280       return DiagnoseImpCast(S, E, T, CC,
06281                              diag::warn_impcast_objective_c_literal_to_bool);
06282     }
06283     if (Source->isPointerType() || Source->canDecayToPointerType()) {
06284       // Warn on pointer to bool conversion that is always true.
06285       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
06286                                      SourceRange(CC));
06287     }
06288   }
06289 
06290   // Strip vector types.
06291   if (isa<VectorType>(Source)) {
06292     if (!isa<VectorType>(Target)) {
06293       if (S.SourceMgr.isInSystemMacro(CC))
06294         return;
06295       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
06296     }
06297     
06298     // If the vector cast is cast between two vectors of the same size, it is
06299     // a bitcast, not a conversion.
06300     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
06301       return;
06302 
06303     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
06304     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
06305   }
06306   if (auto VecTy = dyn_cast<VectorType>(Target))
06307     Target = VecTy->getElementType().getTypePtr();
06308 
06309   // Strip complex types.
06310   if (isa<ComplexType>(Source)) {
06311     if (!isa<ComplexType>(Target)) {
06312       if (S.SourceMgr.isInSystemMacro(CC))
06313         return;
06314 
06315       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
06316     }
06317 
06318     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
06319     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
06320   }
06321 
06322   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
06323   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
06324 
06325   // If the source is floating point...
06326   if (SourceBT && SourceBT->isFloatingPoint()) {
06327     // ...and the target is floating point...
06328     if (TargetBT && TargetBT->isFloatingPoint()) {
06329       // ...then warn if we're dropping FP rank.
06330 
06331       // Builtin FP kinds are ordered by increasing FP rank.
06332       if (SourceBT->getKind() > TargetBT->getKind()) {
06333         // Don't warn about float constants that are precisely
06334         // representable in the target type.
06335         Expr::EvalResult result;
06336         if (E->EvaluateAsRValue(result, S.Context)) {
06337           // Value might be a float, a float vector, or a float complex.
06338           if (IsSameFloatAfterCast(result.Val,
06339                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
06340                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
06341             return;
06342         }
06343 
06344         if (S.SourceMgr.isInSystemMacro(CC))
06345           return;
06346 
06347         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
06348       }
06349       return;
06350     }
06351 
06352     // If the target is integral, always warn.    
06353     if (TargetBT && TargetBT->isInteger()) {
06354       if (S.SourceMgr.isInSystemMacro(CC))
06355         return;
06356       
06357       Expr *InnerE = E->IgnoreParenImpCasts();
06358       // We also want to warn on, e.g., "int i = -1.234"
06359       if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
06360         if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
06361           InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
06362 
06363       if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
06364         DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
06365       } else {
06366         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
06367       }
06368     }
06369 
06370     // If the target is bool, warn if expr is a function or method call.
06371     if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
06372         isa<CallExpr>(E)) {
06373       // Check last argument of function call to see if it is an
06374       // implicit cast from a type matching the type the result
06375       // is being cast to.
06376       CallExpr *CEx = cast<CallExpr>(E);
06377       unsigned NumArgs = CEx->getNumArgs();
06378       if (NumArgs > 0) {
06379         Expr *LastA = CEx->getArg(NumArgs - 1);
06380         Expr *InnerE = LastA->IgnoreParenImpCasts();
06381         const Type *InnerType =
06382           S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
06383         if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
06384           // Warn on this floating-point to bool conversion
06385           DiagnoseImpCast(S, E, T, CC,
06386                           diag::warn_impcast_floating_point_to_bool);
06387         }
06388       }
06389     }
06390     return;
06391   }
06392 
06393   DiagnoseNullConversion(S, E, T, CC);
06394 
06395   if (!Source->isIntegerType() || !Target->isIntegerType())
06396     return;
06397 
06398   // TODO: remove this early return once the false positives for constant->bool
06399   // in templates, macros, etc, are reduced or removed.
06400   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
06401     return;
06402 
06403   IntRange SourceRange = GetExprRange(S.Context, E);
06404   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
06405 
06406   if (SourceRange.Width > TargetRange.Width) {
06407     // If the source is a constant, use a default-on diagnostic.
06408     // TODO: this should happen for bitfield stores, too.
06409     llvm::APSInt Value(32);
06410     if (E->isIntegerConstantExpr(Value, S.Context)) {
06411       if (S.SourceMgr.isInSystemMacro(CC))
06412         return;
06413 
06414       std::string PrettySourceValue = Value.toString(10);
06415       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
06416 
06417       S.DiagRuntimeBehavior(E->getExprLoc(), E,
06418         S.PDiag(diag::warn_impcast_integer_precision_constant)
06419             << PrettySourceValue << PrettyTargetValue
06420             << E->getType() << T << E->getSourceRange()
06421             << clang::SourceRange(CC));
06422       return;
06423     }
06424 
06425     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
06426     if (S.SourceMgr.isInSystemMacro(CC))
06427       return;
06428 
06429     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
06430       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
06431                              /* pruneControlFlow */ true);
06432     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
06433   }
06434 
06435   if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
06436       (!TargetRange.NonNegative && SourceRange.NonNegative &&
06437        SourceRange.Width == TargetRange.Width)) {
06438         
06439     if (S.SourceMgr.isInSystemMacro(CC))
06440       return;
06441 
06442     unsigned DiagID = diag::warn_impcast_integer_sign;
06443 
06444     // Traditionally, gcc has warned about this under -Wsign-compare.
06445     // We also want to warn about it in -Wconversion.
06446     // So if -Wconversion is off, use a completely identical diagnostic
06447     // in the sign-compare group.
06448     // The conditional-checking code will 
06449     if (ICContext) {
06450       DiagID = diag::warn_impcast_integer_sign_conditional;
06451       *ICContext = true;
06452     }
06453 
06454     return DiagnoseImpCast(S, E, T, CC, DiagID);
06455   }
06456 
06457   // Diagnose conversions between different enumeration types.
06458   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
06459   // type, to give us better diagnostics.
06460   QualType SourceType = E->getType();
06461   if (!S.getLangOpts().CPlusPlus) {
06462     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
06463       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
06464         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
06465         SourceType = S.Context.getTypeDeclType(Enum);
06466         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
06467       }
06468   }
06469   
06470   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
06471     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
06472       if (SourceEnum->getDecl()->hasNameForLinkage() &&
06473           TargetEnum->getDecl()->hasNameForLinkage() &&
06474           SourceEnum != TargetEnum) {
06475         if (S.SourceMgr.isInSystemMacro(CC))
06476           return;
06477 
06478         return DiagnoseImpCast(S, E, SourceType, T, CC, 
06479                                diag::warn_impcast_different_enum_types);
06480       }
06481   
06482   return;
06483 }
06484 
06485 void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
06486                               SourceLocation CC, QualType T);
06487 
06488 void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
06489                              SourceLocation CC, bool &ICContext) {
06490   E = E->IgnoreParenImpCasts();
06491 
06492   if (isa<ConditionalOperator>(E))
06493     return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
06494 
06495   AnalyzeImplicitConversions(S, E, CC);
06496   if (E->getType() != T)
06497     return CheckImplicitConversion(S, E, T, CC, &ICContext);
06498   return;
06499 }
06500 
06501 void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
06502                               SourceLocation CC, QualType T) {
06503   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
06504 
06505   bool Suspicious = false;
06506   CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
06507   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
06508 
06509   // If -Wconversion would have warned about either of the candidates
06510   // for a signedness conversion to the context type...
06511   if (!Suspicious) return;
06512 
06513   // ...but it's currently ignored...
06514   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
06515     return;
06516 
06517   // ...then check whether it would have warned about either of the
06518   // candidates for a signedness conversion to the condition type.
06519   if (E->getType() == T) return;
06520  
06521   Suspicious = false;
06522   CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
06523                           E->getType(), CC, &Suspicious);
06524   if (!Suspicious)
06525     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
06526                             E->getType(), CC, &Suspicious);
06527 }
06528 
06529 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
06530 /// Input argument E is a logical expression.
06531 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
06532   if (S.getLangOpts().Bool)
06533     return;
06534   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
06535 }
06536 
06537 /// AnalyzeImplicitConversions - Find and report any interesting
06538 /// implicit conversions in the given expression.  There are a couple
06539 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
06540 void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
06541   QualType T = OrigE->getType();
06542   Expr *E = OrigE->IgnoreParenImpCasts();
06543 
06544   if (E->isTypeDependent() || E->isValueDependent())
06545     return;
06546   
06547   // For conditional operators, we analyze the arguments as if they
06548   // were being fed directly into the output.
06549   if (isa<ConditionalOperator>(E)) {
06550     ConditionalOperator *CO = cast<ConditionalOperator>(E);
06551     CheckConditionalOperator(S, CO, CC, T);
06552     return;
06553   }
06554 
06555   // Check implicit argument conversions for function calls.
06556   if (CallExpr *Call = dyn_cast<CallExpr>(E))
06557     CheckImplicitArgumentConversions(S, Call, CC);
06558 
06559   // Go ahead and check any implicit conversions we might have skipped.
06560   // The non-canonical typecheck is just an optimization;
06561   // CheckImplicitConversion will filter out dead implicit conversions.
06562   if (E->getType() != T)
06563     CheckImplicitConversion(S, E, T, CC);
06564 
06565   // Now continue drilling into this expression.
06566   
06567   if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
06568     if (POE->getResultExpr())
06569       E = POE->getResultExpr();
06570   }
06571   
06572   if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
06573     return AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
06574   
06575   // Skip past explicit casts.
06576   if (isa<ExplicitCastExpr>(E)) {
06577     E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
06578     return AnalyzeImplicitConversions(S, E, CC);
06579   }
06580 
06581   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
06582     // Do a somewhat different check with comparison operators.
06583     if (BO->isComparisonOp())
06584       return AnalyzeComparison(S, BO);
06585 
06586     // And with simple assignments.
06587     if (BO->getOpcode() == BO_Assign)
06588       return AnalyzeAssignment(S, BO);
06589   }
06590 
06591   // These break the otherwise-useful invariant below.  Fortunately,
06592   // we don't really need to recurse into them, because any internal
06593   // expressions should have been analyzed already when they were
06594   // built into statements.
06595   if (isa<StmtExpr>(E)) return;
06596 
06597   // Don't descend into unevaluated contexts.
06598   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
06599 
06600   // Now just recurse over the expression's children.
06601   CC = E->getExprLoc();
06602   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
06603   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
06604   for (Stmt::child_range I = E->children(); I; ++I) {
06605     Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
06606     if (!ChildExpr)
06607       continue;
06608 
06609     if (IsLogicalAndOperator &&
06610         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
06611       // Ignore checking string literals that are in logical and operators.
06612       // This is a common pattern for asserts.
06613       continue;
06614     AnalyzeImplicitConversions(S, ChildExpr, CC);
06615   }
06616   if (BO && BO->isLogicalOp()) {
06617     ::CheckBoolLikeConversion(S, BO->getLHS(), BO->getLHS()->getExprLoc());
06618     ::CheckBoolLikeConversion(S, BO->getRHS(), BO->getRHS()->getExprLoc());
06619   }
06620   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
06621     if (U->getOpcode() == UO_LNot)
06622       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
06623 }
06624 
06625 } // end anonymous namespace
06626 
06627 enum {
06628   AddressOf,
06629   FunctionPointer,
06630   ArrayPointer
06631 };
06632 
06633 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
06634 // Returns true when emitting a warning about taking the address of a reference.
06635 static bool CheckForReference(Sema &SemaRef, const Expr *E,
06636                               PartialDiagnostic PD) {
06637   E = E->IgnoreParenImpCasts();
06638 
06639   const FunctionDecl *FD = nullptr;
06640 
06641   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
06642     if (!DRE->getDecl()->getType()->isReferenceType())
06643       return false;
06644   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
06645     if (!M->getMemberDecl()->getType()->isReferenceType())
06646       return false;
06647   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
06648     if (!Call->getCallReturnType()->isReferenceType())
06649       return false;
06650     FD = Call->getDirectCallee();
06651   } else {
06652     return false;
06653   }
06654 
06655   SemaRef.Diag(E->getExprLoc(), PD);
06656 
06657   // If possible, point to location of function.
06658   if (FD) {
06659     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
06660   }
06661 
06662   return true;
06663 }
06664 
06665 // Returns true if the SourceLocation is expanded from any macro body.
06666 // Returns false if the SourceLocation is invalid, is from not in a macro
06667 // expansion, or is from expanded from a top-level macro argument.
06668 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
06669   if (Loc.isInvalid())
06670     return false;
06671 
06672   while (Loc.isMacroID()) {
06673     if (SM.isMacroBodyExpansion(Loc))
06674       return true;
06675     Loc = SM.getImmediateMacroCallerLoc(Loc);
06676   }
06677 
06678   return false;
06679 }
06680 
06681 /// \brief Diagnose pointers that are always non-null.
06682 /// \param E the expression containing the pointer
06683 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
06684 /// compared to a null pointer
06685 /// \param IsEqual True when the comparison is equal to a null pointer
06686 /// \param Range Extra SourceRange to highlight in the diagnostic
06687 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
06688                                         Expr::NullPointerConstantKind NullKind,
06689                                         bool IsEqual, SourceRange Range) {
06690   if (!E)
06691     return;
06692 
06693   // Don't warn inside macros.
06694   if (E->getExprLoc().isMacroID()) {
06695     const SourceManager &SM = getSourceManager();
06696     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
06697         IsInAnyMacroBody(SM, Range.getBegin()))
06698       return;
06699   }
06700   E = E->IgnoreImpCasts();
06701 
06702   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
06703 
06704   if (isa<CXXThisExpr>(E)) {
06705     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
06706                                 : diag::warn_this_bool_conversion;
06707     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
06708     return;
06709   }
06710 
06711   bool IsAddressOf = false;
06712 
06713   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
06714     if (UO->getOpcode() != UO_AddrOf)
06715       return;
06716     IsAddressOf = true;
06717     E = UO->getSubExpr();
06718   }
06719 
06720   if (IsAddressOf) {
06721     unsigned DiagID = IsCompare
06722                           ? diag::warn_address_of_reference_null_compare
06723                           : diag::warn_address_of_reference_bool_conversion;
06724     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
06725                                          << IsEqual;
06726     if (CheckForReference(*this, E, PD)) {
06727       return;
06728     }
06729   }
06730 
06731   // Expect to find a single Decl.  Skip anything more complicated.
06732   ValueDecl *D = nullptr;
06733   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
06734     D = R->getDecl();
06735   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
06736     D = M->getMemberDecl();
06737   }
06738 
06739   // Weak Decls can be null.
06740   if (!D || D->isWeak())
06741     return;
06742     
06743   QualType T = D->getType();
06744   const bool IsArray = T->isArrayType();
06745   const bool IsFunction = T->isFunctionType();
06746 
06747   // Address of function is used to silence the function warning.
06748   if (IsAddressOf && IsFunction) {
06749     return;
06750   }
06751 
06752   // Found nothing.
06753   if (!IsAddressOf && !IsFunction && !IsArray)
06754     return;
06755 
06756   // Pretty print the expression for the diagnostic.
06757   std::string Str;
06758   llvm::raw_string_ostream S(Str);
06759   E->printPretty(S, nullptr, getPrintingPolicy());
06760 
06761   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
06762                               : diag::warn_impcast_pointer_to_bool;
06763   unsigned DiagType;
06764   if (IsAddressOf)
06765     DiagType = AddressOf;
06766   else if (IsFunction)
06767     DiagType = FunctionPointer;
06768   else if (IsArray)
06769     DiagType = ArrayPointer;
06770   else
06771     llvm_unreachable("Could not determine diagnostic.");
06772   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
06773                                 << Range << IsEqual;
06774 
06775   if (!IsFunction)
06776     return;
06777 
06778   // Suggest '&' to silence the function warning.
06779   Diag(E->getExprLoc(), diag::note_function_warning_silence)
06780       << FixItHint::CreateInsertion(E->getLocStart(), "&");
06781 
06782   // Check to see if '()' fixit should be emitted.
06783   QualType ReturnType;
06784   UnresolvedSet<4> NonTemplateOverloads;
06785   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
06786   if (ReturnType.isNull())
06787     return;
06788 
06789   if (IsCompare) {
06790     // There are two cases here.  If there is null constant, the only suggest
06791     // for a pointer return type.  If the null is 0, then suggest if the return
06792     // type is a pointer or an integer type.
06793     if (!ReturnType->isPointerType()) {
06794       if (NullKind == Expr::NPCK_ZeroExpression ||
06795           NullKind == Expr::NPCK_ZeroLiteral) {
06796         if (!ReturnType->isIntegerType())
06797           return;
06798       } else {
06799         return;
06800       }
06801     }
06802   } else { // !IsCompare
06803     // For function to bool, only suggest if the function pointer has bool
06804     // return type.
06805     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
06806       return;
06807   }
06808   Diag(E->getExprLoc(), diag::note_function_to_function_call)
06809       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
06810 }
06811 
06812 
06813 /// Diagnoses "dangerous" implicit conversions within the given
06814 /// expression (which is a full expression).  Implements -Wconversion
06815 /// and -Wsign-compare.
06816 ///
06817 /// \param CC the "context" location of the implicit conversion, i.e.
06818 ///   the most location of the syntactic entity requiring the implicit
06819 ///   conversion
06820 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
06821   // Don't diagnose in unevaluated contexts.
06822   if (isUnevaluatedContext())
06823     return;
06824 
06825   // Don't diagnose for value- or type-dependent expressions.
06826   if (E->isTypeDependent() || E->isValueDependent())
06827     return;
06828 
06829   // Check for array bounds violations in cases where the check isn't triggered
06830   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
06831   // ArraySubscriptExpr is on the RHS of a variable initialization.
06832   CheckArrayAccess(E);
06833 
06834   // This is not the right CC for (e.g.) a variable initialization.
06835   AnalyzeImplicitConversions(*this, E, CC);
06836 }
06837 
06838 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
06839 /// Input argument E is a logical expression.
06840 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
06841   ::CheckBoolLikeConversion(*this, E, CC);
06842 }
06843 
06844 /// Diagnose when expression is an integer constant expression and its evaluation
06845 /// results in integer overflow
06846 void Sema::CheckForIntOverflow (Expr *E) {
06847   if (isa<BinaryOperator>(E->IgnoreParenCasts()))
06848     E->IgnoreParenCasts()->EvaluateForOverflow(Context);
06849 }
06850 
06851 namespace {
06852 /// \brief Visitor for expressions which looks for unsequenced operations on the
06853 /// same object.
06854 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
06855   typedef EvaluatedExprVisitor<SequenceChecker> Base;
06856 
06857   /// \brief A tree of sequenced regions within an expression. Two regions are
06858   /// unsequenced if one is an ancestor or a descendent of the other. When we
06859   /// finish processing an expression with sequencing, such as a comma
06860   /// expression, we fold its tree nodes into its parent, since they are
06861   /// unsequenced with respect to nodes we will visit later.
06862   class SequenceTree {
06863     struct Value {
06864       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
06865       unsigned Parent : 31;
06866       bool Merged : 1;
06867     };
06868     SmallVector<Value, 8> Values;
06869 
06870   public:
06871     /// \brief A region within an expression which may be sequenced with respect
06872     /// to some other region.
06873     class Seq {
06874       explicit Seq(unsigned N) : Index(N) {}
06875       unsigned Index;
06876       friend class SequenceTree;
06877     public:
06878       Seq() : Index(0) {}
06879     };
06880 
06881     SequenceTree() { Values.push_back(Value(0)); }
06882     Seq root() const { return Seq(0); }
06883 
06884     /// \brief Create a new sequence of operations, which is an unsequenced
06885     /// subset of \p Parent. This sequence of operations is sequenced with
06886     /// respect to other children of \p Parent.
06887     Seq allocate(Seq Parent) {
06888       Values.push_back(Value(Parent.Index));
06889       return Seq(Values.size() - 1);
06890     }
06891 
06892     /// \brief Merge a sequence of operations into its parent.
06893     void merge(Seq S) {
06894       Values[S.Index].Merged = true;
06895     }
06896 
06897     /// \brief Determine whether two operations are unsequenced. This operation
06898     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
06899     /// should have been merged into its parent as appropriate.
06900     bool isUnsequenced(Seq Cur, Seq Old) {
06901       unsigned C = representative(Cur.Index);
06902       unsigned Target = representative(Old.Index);
06903       while (C >= Target) {
06904         if (C == Target)
06905           return true;
06906         C = Values[C].Parent;
06907       }
06908       return false;
06909     }
06910 
06911   private:
06912     /// \brief Pick a representative for a sequence.
06913     unsigned representative(unsigned K) {
06914       if (Values[K].Merged)
06915         // Perform path compression as we go.
06916         return Values[K].Parent = representative(Values[K].Parent);
06917       return K;
06918     }
06919   };
06920 
06921   /// An object for which we can track unsequenced uses.
06922   typedef NamedDecl *Object;
06923 
06924   /// Different flavors of object usage which we track. We only track the
06925   /// least-sequenced usage of each kind.
06926   enum UsageKind {
06927     /// A read of an object. Multiple unsequenced reads are OK.
06928     UK_Use,
06929     /// A modification of an object which is sequenced before the value
06930     /// computation of the expression, such as ++n in C++.
06931     UK_ModAsValue,
06932     /// A modification of an object which is not sequenced before the value
06933     /// computation of the expression, such as n++.
06934     UK_ModAsSideEffect,
06935 
06936     UK_Count = UK_ModAsSideEffect + 1
06937   };
06938 
06939   struct Usage {
06940     Usage() : Use(nullptr), Seq() {}
06941     Expr *Use;
06942     SequenceTree::Seq Seq;
06943   };
06944 
06945   struct UsageInfo {
06946     UsageInfo() : Diagnosed(false) {}
06947     Usage Uses[UK_Count];
06948     /// Have we issued a diagnostic for this variable already?
06949     bool Diagnosed;
06950   };
06951   typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
06952 
06953   Sema &SemaRef;
06954   /// Sequenced regions within the expression.
06955   SequenceTree Tree;
06956   /// Declaration modifications and references which we have seen.
06957   UsageInfoMap UsageMap;
06958   /// The region we are currently within.
06959   SequenceTree::Seq Region;
06960   /// Filled in with declarations which were modified as a side-effect
06961   /// (that is, post-increment operations).
06962   SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
06963   /// Expressions to check later. We defer checking these to reduce
06964   /// stack usage.
06965   SmallVectorImpl<Expr *> &WorkList;
06966 
06967   /// RAII object wrapping the visitation of a sequenced subexpression of an
06968   /// expression. At the end of this process, the side-effects of the evaluation
06969   /// become sequenced with respect to the value computation of the result, so
06970   /// we downgrade any UK_ModAsSideEffect within the evaluation to
06971   /// UK_ModAsValue.
06972   struct SequencedSubexpression {
06973     SequencedSubexpression(SequenceChecker &Self)
06974       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
06975       Self.ModAsSideEffect = &ModAsSideEffect;
06976     }
06977     ~SequencedSubexpression() {
06978       for (unsigned I = 0, E = ModAsSideEffect.size(); I != E; ++I) {
06979         UsageInfo &U = Self.UsageMap[ModAsSideEffect[I].first];
06980         U.Uses[UK_ModAsSideEffect] = ModAsSideEffect[I].second;
06981         Self.addUsage(U, ModAsSideEffect[I].first,
06982                       ModAsSideEffect[I].second.Use, UK_ModAsValue);
06983       }
06984       Self.ModAsSideEffect = OldModAsSideEffect;
06985     }
06986 
06987     SequenceChecker &Self;
06988     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
06989     SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
06990   };
06991 
06992   /// RAII object wrapping the visitation of a subexpression which we might
06993   /// choose to evaluate as a constant. If any subexpression is evaluated and
06994   /// found to be non-constant, this allows us to suppress the evaluation of
06995   /// the outer expression.
06996   class EvaluationTracker {
06997   public:
06998     EvaluationTracker(SequenceChecker &Self)
06999         : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
07000       Self.EvalTracker = this;
07001     }
07002     ~EvaluationTracker() {
07003       Self.EvalTracker = Prev;
07004       if (Prev)
07005         Prev->EvalOK &= EvalOK;
07006     }
07007 
07008     bool evaluate(const Expr *E, bool &Result) {
07009       if (!EvalOK || E->isValueDependent())
07010         return false;
07011       EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
07012       return EvalOK;
07013     }
07014 
07015   private:
07016     SequenceChecker &Self;
07017     EvaluationTracker *Prev;
07018     bool EvalOK;
07019   } *EvalTracker;
07020 
07021   /// \brief Find the object which is produced by the specified expression,
07022   /// if any.
07023   Object getObject(Expr *E, bool Mod) const {
07024     E = E->IgnoreParenCasts();
07025     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
07026       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
07027         return getObject(UO->getSubExpr(), Mod);
07028     } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
07029       if (BO->getOpcode() == BO_Comma)
07030         return getObject(BO->getRHS(), Mod);
07031       if (Mod && BO->isAssignmentOp())
07032         return getObject(BO->getLHS(), Mod);
07033     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
07034       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
07035       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
07036         return ME->getMemberDecl();
07037     } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
07038       // FIXME: If this is a reference, map through to its value.
07039       return DRE->getDecl();
07040     return nullptr;
07041   }
07042 
07043   /// \brief Note that an object was modified or used by an expression.
07044   void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
07045     Usage &U = UI.Uses[UK];
07046     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
07047       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
07048         ModAsSideEffect->push_back(std::make_pair(O, U));
07049       U.Use = Ref;
07050       U.Seq = Region;
07051     }
07052   }
07053   /// \brief Check whether a modification or use conflicts with a prior usage.
07054   void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
07055                   bool IsModMod) {
07056     if (UI.Diagnosed)
07057       return;
07058 
07059     const Usage &U = UI.Uses[OtherKind];
07060     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
07061       return;
07062 
07063     Expr *Mod = U.Use;
07064     Expr *ModOrUse = Ref;
07065     if (OtherKind == UK_Use)
07066       std::swap(Mod, ModOrUse);
07067 
07068     SemaRef.Diag(Mod->getExprLoc(),
07069                  IsModMod ? diag::warn_unsequenced_mod_mod
07070                           : diag::warn_unsequenced_mod_use)
07071       << O << SourceRange(ModOrUse->getExprLoc());
07072     UI.Diagnosed = true;
07073   }
07074 
07075   void notePreUse(Object O, Expr *Use) {
07076     UsageInfo &U = UsageMap[O];
07077     // Uses conflict with other modifications.
07078     checkUsage(O, U, Use, UK_ModAsValue, false);
07079   }
07080   void notePostUse(Object O, Expr *Use) {
07081     UsageInfo &U = UsageMap[O];
07082     checkUsage(O, U, Use, UK_ModAsSideEffect, false);
07083     addUsage(U, O, Use, UK_Use);
07084   }
07085 
07086   void notePreMod(Object O, Expr *Mod) {
07087     UsageInfo &U = UsageMap[O];
07088     // Modifications conflict with other modifications and with uses.
07089     checkUsage(O, U, Mod, UK_ModAsValue, true);
07090     checkUsage(O, U, Mod, UK_Use, false);
07091   }
07092   void notePostMod(Object O, Expr *Use, UsageKind UK) {
07093     UsageInfo &U = UsageMap[O];
07094     checkUsage(O, U, Use, UK_ModAsSideEffect, true);
07095     addUsage(U, O, Use, UK);
07096   }
07097 
07098 public:
07099   SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
07100       : Base(S.Context), SemaRef(S), Region(Tree.root()),
07101         ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
07102     Visit(E);
07103   }
07104 
07105   void VisitStmt(Stmt *S) {
07106     // Skip all statements which aren't expressions for now.
07107   }
07108 
07109   void VisitExpr(Expr *E) {
07110     // By default, just recurse to evaluated subexpressions.
07111     Base::VisitStmt(E);
07112   }
07113 
07114   void VisitCastExpr(CastExpr *E) {
07115     Object O = Object();
07116     if (E->getCastKind() == CK_LValueToRValue)
07117       O = getObject(E->getSubExpr(), false);
07118 
07119     if (O)
07120       notePreUse(O, E);
07121     VisitExpr(E);
07122     if (O)
07123       notePostUse(O, E);
07124   }
07125 
07126   void VisitBinComma(BinaryOperator *BO) {
07127     // C++11 [expr.comma]p1:
07128     //   Every value computation and side effect associated with the left
07129     //   expression is sequenced before every value computation and side
07130     //   effect associated with the right expression.
07131     SequenceTree::Seq LHS = Tree.allocate(Region);
07132     SequenceTree::Seq RHS = Tree.allocate(Region);
07133     SequenceTree::Seq OldRegion = Region;
07134 
07135     {
07136       SequencedSubexpression SeqLHS(*this);
07137       Region = LHS;
07138       Visit(BO->getLHS());
07139     }
07140 
07141     Region = RHS;
07142     Visit(BO->getRHS());
07143 
07144     Region = OldRegion;
07145 
07146     // Forget that LHS and RHS are sequenced. They are both unsequenced
07147     // with respect to other stuff.
07148     Tree.merge(LHS);
07149     Tree.merge(RHS);
07150   }
07151 
07152   void VisitBinAssign(BinaryOperator *BO) {
07153     // The modification is sequenced after the value computation of the LHS
07154     // and RHS, so check it before inspecting the operands and update the
07155     // map afterwards.
07156     Object O = getObject(BO->getLHS(), true);
07157     if (!O)
07158       return VisitExpr(BO);
07159 
07160     notePreMod(O, BO);
07161 
07162     // C++11 [expr.ass]p7:
07163     //   E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
07164     //   only once.
07165     //
07166     // Therefore, for a compound assignment operator, O is considered used
07167     // everywhere except within the evaluation of E1 itself.
07168     if (isa<CompoundAssignOperator>(BO))
07169       notePreUse(O, BO);
07170 
07171     Visit(BO->getLHS());
07172 
07173     if (isa<CompoundAssignOperator>(BO))
07174       notePostUse(O, BO);
07175 
07176     Visit(BO->getRHS());
07177 
07178     // C++11 [expr.ass]p1:
07179     //   the assignment is sequenced [...] before the value computation of the
07180     //   assignment expression.
07181     // C11 6.5.16/3 has no such rule.
07182     notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
07183                                                        : UK_ModAsSideEffect);
07184   }
07185   void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
07186     VisitBinAssign(CAO);
07187   }
07188 
07189   void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
07190   void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
07191   void VisitUnaryPreIncDec(UnaryOperator *UO) {
07192     Object O = getObject(UO->getSubExpr(), true);
07193     if (!O)
07194       return VisitExpr(UO);
07195 
07196     notePreMod(O, UO);
07197     Visit(UO->getSubExpr());
07198     // C++11 [expr.pre.incr]p1:
07199     //   the expression ++x is equivalent to x+=1
07200     notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
07201                                                        : UK_ModAsSideEffect);
07202   }
07203 
07204   void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
07205   void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
07206   void VisitUnaryPostIncDec(UnaryOperator *UO) {
07207     Object O = getObject(UO->getSubExpr(), true);
07208     if (!O)
07209       return VisitExpr(UO);
07210 
07211     notePreMod(O, UO);
07212     Visit(UO->getSubExpr());
07213     notePostMod(O, UO, UK_ModAsSideEffect);
07214   }
07215 
07216   /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
07217   void VisitBinLOr(BinaryOperator *BO) {
07218     // The side-effects of the LHS of an '&&' are sequenced before the
07219     // value computation of the RHS, and hence before the value computation
07220     // of the '&&' itself, unless the LHS evaluates to zero. We treat them
07221     // as if they were unconditionally sequenced.
07222     EvaluationTracker Eval(*this);
07223     {
07224       SequencedSubexpression Sequenced(*this);
07225       Visit(BO->getLHS());
07226     }
07227 
07228     bool Result;
07229     if (Eval.evaluate(BO->getLHS(), Result)) {
07230       if (!Result)
07231         Visit(BO->getRHS());
07232     } else {
07233       // Check for unsequenced operations in the RHS, treating it as an
07234       // entirely separate evaluation.
07235       //
07236       // FIXME: If there are operations in the RHS which are unsequenced
07237       // with respect to operations outside the RHS, and those operations
07238       // are unconditionally evaluated, diagnose them.
07239       WorkList.push_back(BO->getRHS());
07240     }
07241   }
07242   void VisitBinLAnd(BinaryOperator *BO) {
07243     EvaluationTracker Eval(*this);
07244     {
07245       SequencedSubexpression Sequenced(*this);
07246       Visit(BO->getLHS());
07247     }
07248 
07249     bool Result;
07250     if (Eval.evaluate(BO->getLHS(), Result)) {
07251       if (Result)
07252         Visit(BO->getRHS());
07253     } else {
07254       WorkList.push_back(BO->getRHS());
07255     }
07256   }
07257 
07258   // Only visit the condition, unless we can be sure which subexpression will
07259   // be chosen.
07260   void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
07261     EvaluationTracker Eval(*this);
07262     {
07263       SequencedSubexpression Sequenced(*this);
07264       Visit(CO->getCond());
07265     }
07266 
07267     bool Result;
07268     if (Eval.evaluate(CO->getCond(), Result))
07269       Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
07270     else {
07271       WorkList.push_back(CO->getTrueExpr());
07272       WorkList.push_back(CO->getFalseExpr());
07273     }
07274   }
07275 
07276   void VisitCallExpr(CallExpr *CE) {
07277     // C++11 [intro.execution]p15:
07278     //   When calling a function [...], every value computation and side effect
07279     //   associated with any argument expression, or with the postfix expression
07280     //   designating the called function, is sequenced before execution of every
07281     //   expression or statement in the body of the function [and thus before
07282     //   the value computation of its result].
07283     SequencedSubexpression Sequenced(*this);
07284     Base::VisitCallExpr(CE);
07285 
07286     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
07287   }
07288 
07289   void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
07290     // This is a call, so all subexpressions are sequenced before the result.
07291     SequencedSubexpression Sequenced(*this);
07292 
07293     if (!CCE->isListInitialization())
07294       return VisitExpr(CCE);
07295 
07296     // In C++11, list initializations are sequenced.
07297     SmallVector<SequenceTree::Seq, 32> Elts;
07298     SequenceTree::Seq Parent = Region;
07299     for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
07300                                         E = CCE->arg_end();
07301          I != E; ++I) {
07302       Region = Tree.allocate(Parent);
07303       Elts.push_back(Region);
07304       Visit(*I);
07305     }
07306 
07307     // Forget that the initializers are sequenced.
07308     Region = Parent;
07309     for (unsigned I = 0; I < Elts.size(); ++I)
07310       Tree.merge(Elts[I]);
07311   }
07312 
07313   void VisitInitListExpr(InitListExpr *ILE) {
07314     if (!SemaRef.getLangOpts().CPlusPlus11)
07315       return VisitExpr(ILE);
07316 
07317     // In C++11, list initializations are sequenced.
07318     SmallVector<SequenceTree::Seq, 32> Elts;
07319     SequenceTree::Seq Parent = Region;
07320     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
07321       Expr *E = ILE->getInit(I);
07322       if (!E) continue;
07323       Region = Tree.allocate(Parent);
07324       Elts.push_back(Region);
07325       Visit(E);
07326     }
07327 
07328     // Forget that the initializers are sequenced.
07329     Region = Parent;
07330     for (unsigned I = 0; I < Elts.size(); ++I)
07331       Tree.merge(Elts[I]);
07332   }
07333 };
07334 }
07335 
07336 void Sema::CheckUnsequencedOperations(Expr *E) {
07337   SmallVector<Expr *, 8> WorkList;
07338   WorkList.push_back(E);
07339   while (!WorkList.empty()) {
07340     Expr *Item = WorkList.pop_back_val();
07341     SequenceChecker(*this, Item, WorkList);
07342   }
07343 }
07344 
07345 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
07346                               bool IsConstexpr) {
07347   CheckImplicitConversions(E, CheckLoc);
07348   CheckUnsequencedOperations(E);
07349   if (!IsConstexpr && !E->isValueDependent())
07350     CheckForIntOverflow(E);
07351 }
07352 
07353 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
07354                                        FieldDecl *BitField,
07355                                        Expr *Init) {
07356   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
07357 }
07358 
07359 /// CheckParmsForFunctionDef - Check that the parameters of the given
07360 /// function are appropriate for the definition of a function. This
07361 /// takes care of any checks that cannot be performed on the
07362 /// declaration itself, e.g., that the types of each of the function
07363 /// parameters are complete.
07364 bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
07365                                     ParmVarDecl *const *PEnd,
07366                                     bool CheckParameterNames) {
07367   bool HasInvalidParm = false;
07368   for (; P != PEnd; ++P) {
07369     ParmVarDecl *Param = *P;
07370     
07371     // C99 6.7.5.3p4: the parameters in a parameter type list in a
07372     // function declarator that is part of a function definition of
07373     // that function shall not have incomplete type.
07374     //
07375     // This is also C++ [dcl.fct]p6.
07376     if (!Param->isInvalidDecl() &&
07377         RequireCompleteType(Param->getLocation(), Param->getType(),
07378                             diag::err_typecheck_decl_incomplete_type)) {
07379       Param->setInvalidDecl();
07380       HasInvalidParm = true;
07381     }
07382 
07383     // C99 6.9.1p5: If the declarator includes a parameter type list, the
07384     // declaration of each parameter shall include an identifier.
07385     if (CheckParameterNames &&
07386         Param->getIdentifier() == nullptr &&
07387         !Param->isImplicit() &&
07388         !getLangOpts().CPlusPlus)
07389       Diag(Param->getLocation(), diag::err_parameter_name_omitted);
07390 
07391     // C99 6.7.5.3p12:
07392     //   If the function declarator is not part of a definition of that
07393     //   function, parameters may have incomplete type and may use the [*]
07394     //   notation in their sequences of declarator specifiers to specify
07395     //   variable length array types.
07396     QualType PType = Param->getOriginalType();
07397     while (const ArrayType *AT = Context.getAsArrayType(PType)) {
07398       if (AT->getSizeModifier() == ArrayType::Star) {
07399         // FIXME: This diagnostic should point the '[*]' if source-location
07400         // information is added for it.
07401         Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
07402         break;
07403       }
07404       PType= AT->getElementType();
07405     }
07406 
07407     // MSVC destroys objects passed by value in the callee.  Therefore a
07408     // function definition which takes such a parameter must be able to call the
07409     // object's destructor.  However, we don't perform any direct access check
07410     // on the dtor.
07411     if (getLangOpts().CPlusPlus && Context.getTargetInfo()
07412                                        .getCXXABI()
07413                                        .areArgsDestroyedLeftToRightInCallee()) {
07414       if (!Param->isInvalidDecl()) {
07415         if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
07416           CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
07417           if (!ClassDecl->isInvalidDecl() &&
07418               !ClassDecl->hasIrrelevantDestructor() &&
07419               !ClassDecl->isDependentContext()) {
07420             CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
07421             MarkFunctionReferenced(Param->getLocation(), Destructor);
07422             DiagnoseUseOfDecl(Destructor, Param->getLocation());
07423           }
07424         }
07425       }
07426     }
07427   }
07428 
07429   return HasInvalidParm;
07430 }
07431 
07432 /// CheckCastAlign - Implements -Wcast-align, which warns when a
07433 /// pointer cast increases the alignment requirements.
07434 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
07435   // This is actually a lot of work to potentially be doing on every
07436   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
07437   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
07438     return;
07439 
07440   // Ignore dependent types.
07441   if (T->isDependentType() || Op->getType()->isDependentType())
07442     return;
07443 
07444   // Require that the destination be a pointer type.
07445   const PointerType *DestPtr = T->getAs<PointerType>();
07446   if (!DestPtr) return;
07447 
07448   // If the destination has alignment 1, we're done.
07449   QualType DestPointee = DestPtr->getPointeeType();
07450   if (DestPointee->isIncompleteType()) return;
07451   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
07452   if (DestAlign.isOne()) return;
07453 
07454   // Require that the source be a pointer type.
07455   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
07456   if (!SrcPtr) return;
07457   QualType SrcPointee = SrcPtr->getPointeeType();
07458 
07459   // Whitelist casts from cv void*.  We already implicitly
07460   // whitelisted casts to cv void*, since they have alignment 1.
07461   // Also whitelist casts involving incomplete types, which implicitly
07462   // includes 'void'.
07463   if (SrcPointee->isIncompleteType()) return;
07464 
07465   CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
07466   if (SrcAlign >= DestAlign) return;
07467 
07468   Diag(TRange.getBegin(), diag::warn_cast_align)
07469     << Op->getType() << T
07470     << static_cast<unsigned>(SrcAlign.getQuantity())
07471     << static_cast<unsigned>(DestAlign.getQuantity())
07472     << TRange << Op->getSourceRange();
07473 }
07474 
07475 static const Type* getElementType(const Expr *BaseExpr) {
07476   const Type* EltType = BaseExpr->getType().getTypePtr();
07477   if (EltType->isAnyPointerType())
07478     return EltType->getPointeeType().getTypePtr();
07479   else if (EltType->isArrayType())
07480     return EltType->getBaseElementTypeUnsafe();
07481   return EltType;
07482 }
07483 
07484 /// \brief Check whether this array fits the idiom of a size-one tail padded
07485 /// array member of a struct.
07486 ///
07487 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
07488 /// commonly used to emulate flexible arrays in C89 code.
07489 static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
07490                                     const NamedDecl *ND) {
07491   if (Size != 1 || !ND) return false;
07492 
07493   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
07494   if (!FD) return false;
07495 
07496   // Don't consider sizes resulting from macro expansions or template argument
07497   // substitution to form C89 tail-padded arrays.
07498 
07499   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
07500   while (TInfo) {
07501     TypeLoc TL = TInfo->getTypeLoc();
07502     // Look through typedefs.
07503     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
07504       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
07505       TInfo = TDL->getTypeSourceInfo();
07506       continue;
07507     }
07508     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
07509       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
07510       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
07511         return false;
07512     }
07513     break;
07514   }
07515 
07516   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
07517   if (!RD) return false;
07518   if (RD->isUnion()) return false;
07519   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
07520     if (!CRD->isStandardLayout()) return false;
07521   }
07522 
07523   // See if this is the last field decl in the record.
07524   const Decl *D = FD;
07525   while ((D = D->getNextDeclInContext()))
07526     if (isa<FieldDecl>(D))
07527       return false;
07528   return true;
07529 }
07530 
07531 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
07532                             const ArraySubscriptExpr *ASE,
07533                             bool AllowOnePastEnd, bool IndexNegated) {
07534   IndexExpr = IndexExpr->IgnoreParenImpCasts();
07535   if (IndexExpr->isValueDependent())
07536     return;
07537 
07538   const Type *EffectiveType = getElementType(BaseExpr);
07539   BaseExpr = BaseExpr->IgnoreParenCasts();
07540   const ConstantArrayType *ArrayTy =
07541     Context.getAsConstantArrayType(BaseExpr->getType());
07542   if (!ArrayTy)
07543     return;
07544 
07545   llvm::APSInt index;
07546   if (!IndexExpr->EvaluateAsInt(index, Context))
07547     return;
07548   if (IndexNegated)
07549     index = -index;
07550 
07551   const NamedDecl *ND = nullptr;
07552   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
07553     ND = dyn_cast<NamedDecl>(DRE->getDecl());
07554   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
07555     ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
07556 
07557   if (index.isUnsigned() || !index.isNegative()) {
07558     llvm::APInt size = ArrayTy->getSize();
07559     if (!size.isStrictlyPositive())
07560       return;
07561 
07562     const Type* BaseType = getElementType(BaseExpr);
07563     if (BaseType != EffectiveType) {
07564       // Make sure we're comparing apples to apples when comparing index to size
07565       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
07566       uint64_t array_typesize = Context.getTypeSize(BaseType);
07567       // Handle ptrarith_typesize being zero, such as when casting to void*
07568       if (!ptrarith_typesize) ptrarith_typesize = 1;
07569       if (ptrarith_typesize != array_typesize) {
07570         // There's a cast to a different size type involved
07571         uint64_t ratio = array_typesize / ptrarith_typesize;
07572         // TODO: Be smarter about handling cases where array_typesize is not a
07573         // multiple of ptrarith_typesize
07574         if (ptrarith_typesize * ratio == array_typesize)
07575           size *= llvm::APInt(size.getBitWidth(), ratio);
07576       }
07577     }
07578 
07579     if (size.getBitWidth() > index.getBitWidth())
07580       index = index.zext(size.getBitWidth());
07581     else if (size.getBitWidth() < index.getBitWidth())
07582       size = size.zext(index.getBitWidth());
07583 
07584     // For array subscripting the index must be less than size, but for pointer
07585     // arithmetic also allow the index (offset) to be equal to size since
07586     // computing the next address after the end of the array is legal and
07587     // commonly done e.g. in C++ iterators and range-based for loops.
07588     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
07589       return;
07590 
07591     // Also don't warn for arrays of size 1 which are members of some
07592     // structure. These are often used to approximate flexible arrays in C89
07593     // code.
07594     if (IsTailPaddedMemberArray(*this, size, ND))
07595       return;
07596 
07597     // Suppress the warning if the subscript expression (as identified by the
07598     // ']' location) and the index expression are both from macro expansions
07599     // within a system header.
07600     if (ASE) {
07601       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
07602           ASE->getRBracketLoc());
07603       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
07604         SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
07605             IndexExpr->getLocStart());
07606         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
07607           return;
07608       }
07609     }
07610 
07611     unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
07612     if (ASE)
07613       DiagID = diag::warn_array_index_exceeds_bounds;
07614 
07615     DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
07616                         PDiag(DiagID) << index.toString(10, true)
07617                           << size.toString(10, true)
07618                           << (unsigned)size.getLimitedValue(~0U)
07619                           << IndexExpr->getSourceRange());
07620   } else {
07621     unsigned DiagID = diag::warn_array_index_precedes_bounds;
07622     if (!ASE) {
07623       DiagID = diag::warn_ptr_arith_precedes_bounds;
07624       if (index.isNegative()) index = -index;
07625     }
07626 
07627     DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
07628                         PDiag(DiagID) << index.toString(10, true)
07629                           << IndexExpr->getSourceRange());
07630   }
07631 
07632   if (!ND) {
07633     // Try harder to find a NamedDecl to point at in the note.
07634     while (const ArraySubscriptExpr *ASE =
07635            dyn_cast<ArraySubscriptExpr>(BaseExpr))
07636       BaseExpr = ASE->getBase()->IgnoreParenCasts();
07637     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
07638       ND = dyn_cast<NamedDecl>(DRE->getDecl());
07639     if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
07640       ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
07641   }
07642 
07643   if (ND)
07644     DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
07645                         PDiag(diag::note_array_index_out_of_bounds)
07646                           << ND->getDeclName());
07647 }
07648 
07649 void Sema::CheckArrayAccess(const Expr *expr) {
07650   int AllowOnePastEnd = 0;
07651   while (expr) {
07652     expr = expr->IgnoreParenImpCasts();
07653     switch (expr->getStmtClass()) {
07654       case Stmt::ArraySubscriptExprClass: {
07655         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
07656         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
07657                          AllowOnePastEnd > 0);
07658         return;
07659       }
07660       case Stmt::UnaryOperatorClass: {
07661         // Only unwrap the * and & unary operators
07662         const UnaryOperator *UO = cast<UnaryOperator>(expr);
07663         expr = UO->getSubExpr();
07664         switch (UO->getOpcode()) {
07665           case UO_AddrOf:
07666             AllowOnePastEnd++;
07667             break;
07668           case UO_Deref:
07669             AllowOnePastEnd--;
07670             break;
07671           default:
07672             return;
07673         }
07674         break;
07675       }
07676       case Stmt::ConditionalOperatorClass: {
07677         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
07678         if (const Expr *lhs = cond->getLHS())
07679           CheckArrayAccess(lhs);
07680         if (const Expr *rhs = cond->getRHS())
07681           CheckArrayAccess(rhs);
07682         return;
07683       }
07684       default:
07685         return;
07686     }
07687   }
07688 }
07689 
07690 //===--- CHECK: Objective-C retain cycles ----------------------------------//
07691 
07692 namespace {
07693   struct RetainCycleOwner {
07694     RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
07695     VarDecl *Variable;
07696     SourceRange Range;
07697     SourceLocation Loc;
07698     bool Indirect;
07699 
07700     void setLocsFrom(Expr *e) {
07701       Loc = e->getExprLoc();
07702       Range = e->getSourceRange();
07703     }
07704   };
07705 }
07706 
07707 /// Consider whether capturing the given variable can possibly lead to
07708 /// a retain cycle.
07709 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
07710   // In ARC, it's captured strongly iff the variable has __strong
07711   // lifetime.  In MRR, it's captured strongly if the variable is
07712   // __block and has an appropriate type.
07713   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
07714     return false;
07715 
07716   owner.Variable = var;
07717   if (ref)
07718     owner.setLocsFrom(ref);
07719   return true;
07720 }
07721 
07722 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
07723   while (true) {
07724     e = e->IgnoreParens();
07725     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
07726       switch (cast->getCastKind()) {
07727       case CK_BitCast:
07728       case CK_LValueBitCast:
07729       case CK_LValueToRValue:
07730       case CK_ARCReclaimReturnedObject:
07731         e = cast->getSubExpr();
07732         continue;
07733 
07734       default:
07735         return false;
07736       }
07737     }
07738 
07739     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
07740       ObjCIvarDecl *ivar = ref->getDecl();
07741       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
07742         return false;
07743 
07744       // Try to find a retain cycle in the base.
07745       if (!findRetainCycleOwner(S, ref->getBase(), owner))
07746         return false;
07747 
07748       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
07749       owner.Indirect = true;
07750       return true;
07751     }
07752 
07753     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
07754       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
07755       if (!var) return false;
07756       return considerVariable(var, ref, owner);
07757     }
07758 
07759     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
07760       if (member->isArrow()) return false;
07761 
07762       // Don't count this as an indirect ownership.
07763       e = member->getBase();
07764       continue;
07765     }
07766 
07767     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
07768       // Only pay attention to pseudo-objects on property references.
07769       ObjCPropertyRefExpr *pre
07770         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
07771                                               ->IgnoreParens());
07772       if (!pre) return false;
07773       if (pre->isImplicitProperty()) return false;
07774       ObjCPropertyDecl *property = pre->getExplicitProperty();
07775       if (!property->isRetaining() &&
07776           !(property->getPropertyIvarDecl() &&
07777             property->getPropertyIvarDecl()->getType()
07778               .getObjCLifetime() == Qualifiers::OCL_Strong))
07779           return false;
07780 
07781       owner.Indirect = true;
07782       if (pre->isSuperReceiver()) {
07783         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
07784         if (!owner.Variable)
07785           return false;
07786         owner.Loc = pre->getLocation();
07787         owner.Range = pre->getSourceRange();
07788         return true;
07789       }
07790       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
07791                               ->getSourceExpr());
07792       continue;
07793     }
07794 
07795     // Array ivars?
07796 
07797     return false;
07798   }
07799 }
07800 
07801 namespace {
07802   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
07803     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
07804       : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
07805         Context(Context), Variable(variable), Capturer(nullptr),
07806         VarWillBeReased(false) {}
07807     ASTContext &Context;
07808     VarDecl *Variable;
07809     Expr *Capturer;
07810     bool VarWillBeReased;
07811 
07812     void VisitDeclRefExpr(DeclRefExpr *ref) {
07813       if (ref->getDecl() == Variable && !Capturer)
07814         Capturer = ref;
07815     }
07816 
07817     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
07818       if (Capturer) return;
07819       Visit(ref->getBase());
07820       if (Capturer && ref->isFreeIvar())
07821         Capturer = ref;
07822     }
07823 
07824     void VisitBlockExpr(BlockExpr *block) {
07825       // Look inside nested blocks 
07826       if (block->getBlockDecl()->capturesVariable(Variable))
07827         Visit(block->getBlockDecl()->getBody());
07828     }
07829     
07830     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
07831       if (Capturer) return;
07832       if (OVE->getSourceExpr())
07833         Visit(OVE->getSourceExpr());
07834     }
07835     void VisitBinaryOperator(BinaryOperator *BinOp) {
07836       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
07837         return;
07838       Expr *LHS = BinOp->getLHS();
07839       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
07840         if (DRE->getDecl() != Variable)
07841           return;
07842         if (Expr *RHS = BinOp->getRHS()) {
07843           RHS = RHS->IgnoreParenCasts();
07844           llvm::APSInt Value;
07845           VarWillBeReased =
07846             (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
07847         }
07848       }
07849     }
07850   };
07851 }
07852 
07853 /// Check whether the given argument is a block which captures a
07854 /// variable.
07855 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
07856   assert(owner.Variable && owner.Loc.isValid());
07857 
07858   e = e->IgnoreParenCasts();
07859 
07860   // Look through [^{...} copy] and Block_copy(^{...}).
07861   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
07862     Selector Cmd = ME->getSelector();
07863     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
07864       e = ME->getInstanceReceiver();
07865       if (!e)
07866         return nullptr;
07867       e = e->IgnoreParenCasts();
07868     }
07869   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
07870     if (CE->getNumArgs() == 1) {
07871       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
07872       if (Fn) {
07873         const IdentifierInfo *FnI = Fn->getIdentifier();
07874         if (FnI && FnI->isStr("_Block_copy")) {
07875           e = CE->getArg(0)->IgnoreParenCasts();
07876         }
07877       }
07878     }
07879   }
07880   
07881   BlockExpr *block = dyn_cast<BlockExpr>(e);
07882   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
07883     return nullptr;
07884 
07885   FindCaptureVisitor visitor(S.Context, owner.Variable);
07886   visitor.Visit(block->getBlockDecl()->getBody());
07887   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
07888 }
07889 
07890 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
07891                                 RetainCycleOwner &owner) {
07892   assert(capturer);
07893   assert(owner.Variable && owner.Loc.isValid());
07894 
07895   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
07896     << owner.Variable << capturer->getSourceRange();
07897   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
07898     << owner.Indirect << owner.Range;
07899 }
07900 
07901 /// Check for a keyword selector that starts with the word 'add' or
07902 /// 'set'.
07903 static bool isSetterLikeSelector(Selector sel) {
07904   if (sel.isUnarySelector()) return false;
07905 
07906   StringRef str = sel.getNameForSlot(0);
07907   while (!str.empty() && str.front() == '_') str = str.substr(1);
07908   if (str.startswith("set"))
07909     str = str.substr(3);
07910   else if (str.startswith("add")) {
07911     // Specially whitelist 'addOperationWithBlock:'.
07912     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
07913       return false;
07914     str = str.substr(3);
07915   }
07916   else
07917     return false;
07918 
07919   if (str.empty()) return true;
07920   return !isLowercase(str.front());
07921 }
07922 
07923 /// Check a message send to see if it's likely to cause a retain cycle.
07924 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
07925   // Only check instance methods whose selector looks like a setter.
07926   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
07927     return;
07928 
07929   // Try to find a variable that the receiver is strongly owned by.
07930   RetainCycleOwner owner;
07931   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
07932     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
07933       return;
07934   } else {
07935     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
07936     owner.Variable = getCurMethodDecl()->getSelfDecl();
07937     owner.Loc = msg->getSuperLoc();
07938     owner.Range = msg->getSuperLoc();
07939   }
07940 
07941   // Check whether the receiver is captured by any of the arguments.
07942   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
07943     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
07944       return diagnoseRetainCycle(*this, capturer, owner);
07945 }
07946 
07947 /// Check a property assign to see if it's likely to cause a retain cycle.
07948 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
07949   RetainCycleOwner owner;
07950   if (!findRetainCycleOwner(*this, receiver, owner))
07951     return;
07952 
07953   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
07954     diagnoseRetainCycle(*this, capturer, owner);
07955 }
07956 
07957 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
07958   RetainCycleOwner Owner;
07959   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
07960     return;
07961   
07962   // Because we don't have an expression for the variable, we have to set the
07963   // location explicitly here.
07964   Owner.Loc = Var->getLocation();
07965   Owner.Range = Var->getSourceRange();
07966   
07967   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
07968     diagnoseRetainCycle(*this, Capturer, Owner);
07969 }
07970 
07971 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
07972                                      Expr *RHS, bool isProperty) {
07973   // Check if RHS is an Objective-C object literal, which also can get
07974   // immediately zapped in a weak reference.  Note that we explicitly
07975   // allow ObjCStringLiterals, since those are designed to never really die.
07976   RHS = RHS->IgnoreParenImpCasts();
07977 
07978   // This enum needs to match with the 'select' in
07979   // warn_objc_arc_literal_assign (off-by-1).
07980   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
07981   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
07982     return false;
07983 
07984   S.Diag(Loc, diag::warn_arc_literal_assign)
07985     << (unsigned) Kind
07986     << (isProperty ? 0 : 1)
07987     << RHS->getSourceRange();
07988 
07989   return true;
07990 }
07991 
07992 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
07993                                     Qualifiers::ObjCLifetime LT,
07994                                     Expr *RHS, bool isProperty) {
07995   // Strip off any implicit cast added to get to the one ARC-specific.
07996   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
07997     if (cast->getCastKind() == CK_ARCConsumeObject) {
07998       S.Diag(Loc, diag::warn_arc_retained_assign)
07999         << (LT == Qualifiers::OCL_ExplicitNone)
08000         << (isProperty ? 0 : 1)
08001         << RHS->getSourceRange();
08002       return true;
08003     }
08004     RHS = cast->getSubExpr();
08005   }
08006 
08007   if (LT == Qualifiers::OCL_Weak &&
08008       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
08009     return true;
08010 
08011   return false;
08012 }
08013 
08014 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
08015                               QualType LHS, Expr *RHS) {
08016   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
08017 
08018   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
08019     return false;
08020 
08021   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
08022     return true;
08023 
08024   return false;
08025 }
08026 
08027 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
08028                               Expr *LHS, Expr *RHS) {
08029   QualType LHSType;
08030   // PropertyRef on LHS type need be directly obtained from
08031   // its declaration as it has a PseudoType.
08032   ObjCPropertyRefExpr *PRE
08033     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
08034   if (PRE && !PRE->isImplicitProperty()) {
08035     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
08036     if (PD)
08037       LHSType = PD->getType();
08038   }
08039   
08040   if (LHSType.isNull())
08041     LHSType = LHS->getType();
08042 
08043   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
08044 
08045   if (LT == Qualifiers::OCL_Weak) {
08046     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
08047       getCurFunction()->markSafeWeakUse(LHS);
08048   }
08049 
08050   if (checkUnsafeAssigns(Loc, LHSType, RHS))
08051     return;
08052 
08053   // FIXME. Check for other life times.
08054   if (LT != Qualifiers::OCL_None)
08055     return;
08056   
08057   if (PRE) {
08058     if (PRE->isImplicitProperty())
08059       return;
08060     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
08061     if (!PD)
08062       return;
08063     
08064     unsigned Attributes = PD->getPropertyAttributes();
08065     if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
08066       // when 'assign' attribute was not explicitly specified
08067       // by user, ignore it and rely on property type itself
08068       // for lifetime info.
08069       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
08070       if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
08071           LHSType->isObjCRetainableType())
08072         return;
08073         
08074       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
08075         if (cast->getCastKind() == CK_ARCConsumeObject) {
08076           Diag(Loc, diag::warn_arc_retained_property_assign)
08077           << RHS->getSourceRange();
08078           return;
08079         }
08080         RHS = cast->getSubExpr();
08081       }
08082     }
08083     else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
08084       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
08085         return;
08086     }
08087   }
08088 }
08089 
08090 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
08091 
08092 namespace {
08093 bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
08094                                  SourceLocation StmtLoc,
08095                                  const NullStmt *Body) {
08096   // Do not warn if the body is a macro that expands to nothing, e.g:
08097   //
08098   // #define CALL(x)
08099   // if (condition)
08100   //   CALL(0);
08101   //
08102   if (Body->hasLeadingEmptyMacro())
08103     return false;
08104 
08105   // Get line numbers of statement and body.
08106   bool StmtLineInvalid;
08107   unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
08108                                                       &StmtLineInvalid);
08109   if (StmtLineInvalid)
08110     return false;
08111 
08112   bool BodyLineInvalid;
08113   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
08114                                                       &BodyLineInvalid);
08115   if (BodyLineInvalid)
08116     return false;
08117 
08118   // Warn if null statement and body are on the same line.
08119   if (StmtLine != BodyLine)
08120     return false;
08121 
08122   return true;
08123 }
08124 } // Unnamed namespace
08125 
08126 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
08127                                  const Stmt *Body,
08128                                  unsigned DiagID) {
08129   // Since this is a syntactic check, don't emit diagnostic for template
08130   // instantiations, this just adds noise.
08131   if (CurrentInstantiationScope)
08132     return;
08133 
08134   // The body should be a null statement.
08135   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
08136   if (!NBody)
08137     return;
08138 
08139   // Do the usual checks.
08140   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
08141     return;
08142 
08143   Diag(NBody->getSemiLoc(), DiagID);
08144   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
08145 }
08146 
08147 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
08148                                  const Stmt *PossibleBody) {
08149   assert(!CurrentInstantiationScope); // Ensured by caller
08150 
08151   SourceLocation StmtLoc;
08152   const Stmt *Body;
08153   unsigned DiagID;
08154   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
08155     StmtLoc = FS->getRParenLoc();
08156     Body = FS->getBody();
08157     DiagID = diag::warn_empty_for_body;
08158   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
08159     StmtLoc = WS->getCond()->getSourceRange().getEnd();
08160     Body = WS->getBody();
08161     DiagID = diag::warn_empty_while_body;
08162   } else
08163     return; // Neither `for' nor `while'.
08164 
08165   // The body should be a null statement.
08166   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
08167   if (!NBody)
08168     return;
08169 
08170   // Skip expensive checks if diagnostic is disabled.
08171   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
08172     return;
08173 
08174   // Do the usual checks.
08175   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
08176     return;
08177 
08178   // `for(...);' and `while(...);' are popular idioms, so in order to keep
08179   // noise level low, emit diagnostics only if for/while is followed by a
08180   // CompoundStmt, e.g.:
08181   //    for (int i = 0; i < n; i++);
08182   //    {
08183   //      a(i);
08184   //    }
08185   // or if for/while is followed by a statement with more indentation
08186   // than for/while itself:
08187   //    for (int i = 0; i < n; i++);
08188   //      a(i);
08189   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
08190   if (!ProbableTypo) {
08191     bool BodyColInvalid;
08192     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
08193                              PossibleBody->getLocStart(),
08194                              &BodyColInvalid);
08195     if (BodyColInvalid)
08196       return;
08197 
08198     bool StmtColInvalid;
08199     unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
08200                              S->getLocStart(),
08201                              &StmtColInvalid);
08202     if (StmtColInvalid)
08203       return;
08204 
08205     if (BodyCol > StmtCol)
08206       ProbableTypo = true;
08207   }
08208 
08209   if (ProbableTypo) {
08210     Diag(NBody->getSemiLoc(), DiagID);
08211     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
08212   }
08213 }
08214 
08215 //===--- Layout compatibility ----------------------------------------------//
08216 
08217 namespace {
08218 
08219 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
08220 
08221 /// \brief Check if two enumeration types are layout-compatible.
08222 bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
08223   // C++11 [dcl.enum] p8:
08224   // Two enumeration types are layout-compatible if they have the same
08225   // underlying type.
08226   return ED1->isComplete() && ED2->isComplete() &&
08227          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
08228 }
08229 
08230 /// \brief Check if two fields are layout-compatible.
08231 bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
08232   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
08233     return false;
08234 
08235   if (Field1->isBitField() != Field2->isBitField())
08236     return false;
08237 
08238   if (Field1->isBitField()) {
08239     // Make sure that the bit-fields are the same length.
08240     unsigned Bits1 = Field1->getBitWidthValue(C);
08241     unsigned Bits2 = Field2->getBitWidthValue(C);
08242 
08243     if (Bits1 != Bits2)
08244       return false;
08245   }
08246 
08247   return true;
08248 }
08249 
08250 /// \brief Check if two standard-layout structs are layout-compatible.
08251 /// (C++11 [class.mem] p17)
08252 bool isLayoutCompatibleStruct(ASTContext &C,
08253                               RecordDecl *RD1,
08254                               RecordDecl *RD2) {
08255   // If both records are C++ classes, check that base classes match.
08256   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
08257     // If one of records is a CXXRecordDecl we are in C++ mode,
08258     // thus the other one is a CXXRecordDecl, too.
08259     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
08260     // Check number of base classes.
08261     if (D1CXX->getNumBases() != D2CXX->getNumBases())
08262       return false;
08263 
08264     // Check the base classes.
08265     for (CXXRecordDecl::base_class_const_iterator
08266                Base1 = D1CXX->bases_begin(),
08267            BaseEnd1 = D1CXX->bases_end(),
08268               Base2 = D2CXX->bases_begin();
08269          Base1 != BaseEnd1;
08270          ++Base1, ++Base2) {
08271       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
08272         return false;
08273     }
08274   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
08275     // If only RD2 is a C++ class, it should have zero base classes.
08276     if (D2CXX->getNumBases() > 0)
08277       return false;
08278   }
08279 
08280   // Check the fields.
08281   RecordDecl::field_iterator Field2 = RD2->field_begin(),
08282                              Field2End = RD2->field_end(),
08283                              Field1 = RD1->field_begin(),
08284                              Field1End = RD1->field_end();
08285   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
08286     if (!isLayoutCompatible(C, *Field1, *Field2))
08287       return false;
08288   }
08289   if (Field1 != Field1End || Field2 != Field2End)
08290     return false;
08291 
08292   return true;
08293 }
08294 
08295 /// \brief Check if two standard-layout unions are layout-compatible.
08296 /// (C++11 [class.mem] p18)
08297 bool isLayoutCompatibleUnion(ASTContext &C,
08298                              RecordDecl *RD1,
08299                              RecordDecl *RD2) {
08300   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
08301   for (auto *Field2 : RD2->fields())
08302     UnmatchedFields.insert(Field2);
08303 
08304   for (auto *Field1 : RD1->fields()) {
08305     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
08306         I = UnmatchedFields.begin(),
08307         E = UnmatchedFields.end();
08308 
08309     for ( ; I != E; ++I) {
08310       if (isLayoutCompatible(C, Field1, *I)) {
08311         bool Result = UnmatchedFields.erase(*I);
08312         (void) Result;
08313         assert(Result);
08314         break;
08315       }
08316     }
08317     if (I == E)
08318       return false;
08319   }
08320 
08321   return UnmatchedFields.empty();
08322 }
08323 
08324 bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
08325   if (RD1->isUnion() != RD2->isUnion())
08326     return false;
08327 
08328   if (RD1->isUnion())
08329     return isLayoutCompatibleUnion(C, RD1, RD2);
08330   else
08331     return isLayoutCompatibleStruct(C, RD1, RD2);
08332 }
08333 
08334 /// \brief Check if two types are layout-compatible in C++11 sense.
08335 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
08336   if (T1.isNull() || T2.isNull())
08337     return false;
08338 
08339   // C++11 [basic.types] p11:
08340   // If two types T1 and T2 are the same type, then T1 and T2 are
08341   // layout-compatible types.
08342   if (C.hasSameType(T1, T2))
08343     return true;
08344 
08345   T1 = T1.getCanonicalType().getUnqualifiedType();
08346   T2 = T2.getCanonicalType().getUnqualifiedType();
08347 
08348   const Type::TypeClass TC1 = T1->getTypeClass();
08349   const Type::TypeClass TC2 = T2->getTypeClass();
08350 
08351   if (TC1 != TC2)
08352     return false;
08353 
08354   if (TC1 == Type::Enum) {
08355     return isLayoutCompatible(C,
08356                               cast<EnumType>(T1)->getDecl(),
08357                               cast<EnumType>(T2)->getDecl());
08358   } else if (TC1 == Type::Record) {
08359     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
08360       return false;
08361 
08362     return isLayoutCompatible(C,
08363                               cast<RecordType>(T1)->getDecl(),
08364                               cast<RecordType>(T2)->getDecl());
08365   }
08366 
08367   return false;
08368 }
08369 }
08370 
08371 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
08372 
08373 namespace {
08374 /// \brief Given a type tag expression find the type tag itself.
08375 ///
08376 /// \param TypeExpr Type tag expression, as it appears in user's code.
08377 ///
08378 /// \param VD Declaration of an identifier that appears in a type tag.
08379 ///
08380 /// \param MagicValue Type tag magic value.
08381 bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
08382                      const ValueDecl **VD, uint64_t *MagicValue) {
08383   while(true) {
08384     if (!TypeExpr)
08385       return false;
08386 
08387     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
08388 
08389     switch (TypeExpr->getStmtClass()) {
08390     case Stmt::UnaryOperatorClass: {
08391       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
08392       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
08393         TypeExpr = UO->getSubExpr();
08394         continue;
08395       }
08396       return false;
08397     }
08398 
08399     case Stmt::DeclRefExprClass: {
08400       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
08401       *VD = DRE->getDecl();
08402       return true;
08403     }
08404 
08405     case Stmt::IntegerLiteralClass: {
08406       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
08407       llvm::APInt MagicValueAPInt = IL->getValue();
08408       if (MagicValueAPInt.getActiveBits() <= 64) {
08409         *MagicValue = MagicValueAPInt.getZExtValue();
08410         return true;
08411       } else
08412         return false;
08413     }
08414 
08415     case Stmt::BinaryConditionalOperatorClass:
08416     case Stmt::ConditionalOperatorClass: {
08417       const AbstractConditionalOperator *ACO =
08418           cast<AbstractConditionalOperator>(TypeExpr);
08419       bool Result;
08420       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
08421         if (Result)
08422           TypeExpr = ACO->getTrueExpr();
08423         else
08424           TypeExpr = ACO->getFalseExpr();
08425         continue;
08426       }
08427       return false;
08428     }
08429 
08430     case Stmt::BinaryOperatorClass: {
08431       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
08432       if (BO->getOpcode() == BO_Comma) {
08433         TypeExpr = BO->getRHS();
08434         continue;
08435       }
08436       return false;
08437     }
08438 
08439     default:
08440       return false;
08441     }
08442   }
08443 }
08444 
08445 /// \brief Retrieve the C type corresponding to type tag TypeExpr.
08446 ///
08447 /// \param TypeExpr Expression that specifies a type tag.
08448 ///
08449 /// \param MagicValues Registered magic values.
08450 ///
08451 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
08452 ///        kind.
08453 ///
08454 /// \param TypeInfo Information about the corresponding C type.
08455 ///
08456 /// \returns true if the corresponding C type was found.
08457 bool GetMatchingCType(
08458         const IdentifierInfo *ArgumentKind,
08459         const Expr *TypeExpr, const ASTContext &Ctx,
08460         const llvm::DenseMap<Sema::TypeTagMagicValue,
08461                              Sema::TypeTagData> *MagicValues,
08462         bool &FoundWrongKind,
08463         Sema::TypeTagData &TypeInfo) {
08464   FoundWrongKind = false;
08465 
08466   // Variable declaration that has type_tag_for_datatype attribute.
08467   const ValueDecl *VD = nullptr;
08468 
08469   uint64_t MagicValue;
08470 
08471   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
08472     return false;
08473 
08474   if (VD) {
08475     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
08476       if (I->getArgumentKind() != ArgumentKind) {
08477         FoundWrongKind = true;
08478         return false;
08479       }
08480       TypeInfo.Type = I->getMatchingCType();
08481       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
08482       TypeInfo.MustBeNull = I->getMustBeNull();
08483       return true;
08484     }
08485     return false;
08486   }
08487 
08488   if (!MagicValues)
08489     return false;
08490 
08491   llvm::DenseMap<Sema::TypeTagMagicValue,
08492                  Sema::TypeTagData>::const_iterator I =
08493       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
08494   if (I == MagicValues->end())
08495     return false;
08496 
08497   TypeInfo = I->second;
08498   return true;
08499 }
08500 } // unnamed namespace
08501 
08502 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
08503                                       uint64_t MagicValue, QualType Type,
08504                                       bool LayoutCompatible,
08505                                       bool MustBeNull) {
08506   if (!TypeTagForDatatypeMagicValues)
08507     TypeTagForDatatypeMagicValues.reset(
08508         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
08509 
08510   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
08511   (*TypeTagForDatatypeMagicValues)[Magic] =
08512       TypeTagData(Type, LayoutCompatible, MustBeNull);
08513 }
08514 
08515 namespace {
08516 bool IsSameCharType(QualType T1, QualType T2) {
08517   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
08518   if (!BT1)
08519     return false;
08520 
08521   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
08522   if (!BT2)
08523     return false;
08524 
08525   BuiltinType::Kind T1Kind = BT1->getKind();
08526   BuiltinType::Kind T2Kind = BT2->getKind();
08527 
08528   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
08529          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
08530          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
08531          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
08532 }
08533 } // unnamed namespace
08534 
08535 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
08536                                     const Expr * const *ExprArgs) {
08537   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
08538   bool IsPointerAttr = Attr->getIsPointer();
08539 
08540   const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
08541   bool FoundWrongKind;
08542   TypeTagData TypeInfo;
08543   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
08544                         TypeTagForDatatypeMagicValues.get(),
08545                         FoundWrongKind, TypeInfo)) {
08546     if (FoundWrongKind)
08547       Diag(TypeTagExpr->getExprLoc(),
08548            diag::warn_type_tag_for_datatype_wrong_kind)
08549         << TypeTagExpr->getSourceRange();
08550     return;
08551   }
08552 
08553   const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
08554   if (IsPointerAttr) {
08555     // Skip implicit cast of pointer to `void *' (as a function argument).
08556     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
08557       if (ICE->getType()->isVoidPointerType() &&
08558           ICE->getCastKind() == CK_BitCast)
08559         ArgumentExpr = ICE->getSubExpr();
08560   }
08561   QualType ArgumentType = ArgumentExpr->getType();
08562 
08563   // Passing a `void*' pointer shouldn't trigger a warning.
08564   if (IsPointerAttr && ArgumentType->isVoidPointerType())
08565     return;
08566 
08567   if (TypeInfo.MustBeNull) {
08568     // Type tag with matching void type requires a null pointer.
08569     if (!ArgumentExpr->isNullPointerConstant(Context,
08570                                              Expr::NPC_ValueDependentIsNotNull)) {
08571       Diag(ArgumentExpr->getExprLoc(),
08572            diag::warn_type_safety_null_pointer_required)
08573           << ArgumentKind->getName()
08574           << ArgumentExpr->getSourceRange()
08575           << TypeTagExpr->getSourceRange();
08576     }
08577     return;
08578   }
08579 
08580   QualType RequiredType = TypeInfo.Type;
08581   if (IsPointerAttr)
08582     RequiredType = Context.getPointerType(RequiredType);
08583 
08584   bool mismatch = false;
08585   if (!TypeInfo.LayoutCompatible) {
08586     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
08587 
08588     // C++11 [basic.fundamental] p1:
08589     // Plain char, signed char, and unsigned char are three distinct types.
08590     //
08591     // But we treat plain `char' as equivalent to `signed char' or `unsigned
08592     // char' depending on the current char signedness mode.
08593     if (mismatch)
08594       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
08595                                            RequiredType->getPointeeType())) ||
08596           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
08597         mismatch = false;
08598   } else
08599     if (IsPointerAttr)
08600       mismatch = !isLayoutCompatible(Context,
08601                                      ArgumentType->getPointeeType(),
08602                                      RequiredType->getPointeeType());
08603     else
08604       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
08605 
08606   if (mismatch)
08607     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
08608         << ArgumentType << ArgumentKind
08609         << TypeInfo.LayoutCompatible << RequiredType
08610         << ArgumentExpr->getSourceRange()
08611         << TypeTagExpr->getSourceRange();
08612 }
08613