1 1.1 joerg //===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===// 2 1.1 joerg // 3 1.1 joerg // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 1.1 joerg // See https://llvm.org/LICENSE.txt for license information. 5 1.1 joerg // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 1.1 joerg // 7 1.1 joerg //===----------------------------------------------------------------------===// 8 1.1 joerg // 9 1.1 joerg // This file implements the Expr constant evaluator. 10 1.1 joerg // 11 1.1 joerg // Constant expression evaluation produces four main results: 12 1.1 joerg // 13 1.1 joerg // * A success/failure flag indicating whether constant folding was successful. 14 1.1 joerg // This is the 'bool' return value used by most of the code in this file. A 15 1.1 joerg // 'false' return value indicates that constant folding has failed, and any 16 1.1 joerg // appropriate diagnostic has already been produced. 17 1.1 joerg // 18 1.1 joerg // * An evaluated result, valid only if constant folding has not failed. 19 1.1 joerg // 20 1.1 joerg // * A flag indicating if evaluation encountered (unevaluated) side-effects. 21 1.1 joerg // These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1), 22 1.1 joerg // where it is possible to determine the evaluated result regardless. 23 1.1 joerg // 24 1.1 joerg // * A set of notes indicating why the evaluation was not a constant expression 25 1.1 joerg // (under the C++11 / C++1y rules only, at the moment), or, if folding failed 26 1.1 joerg // too, why the expression could not be folded. 27 1.1 joerg // 28 1.1 joerg // If we are checking for a potential constant expression, failure to constant 29 1.1 joerg // fold a potential constant sub-expression will be indicated by a 'false' 30 1.1 joerg // return value (the expression could not be folded) and no diagnostic (the 31 1.1 joerg // expression is not necessarily non-constant). 32 1.1 joerg // 33 1.1 joerg //===----------------------------------------------------------------------===// 34 1.1 joerg 35 1.1 joerg #include "Interp/Context.h" 36 1.1 joerg #include "Interp/Frame.h" 37 1.1 joerg #include "Interp/State.h" 38 1.1 joerg #include "clang/AST/APValue.h" 39 1.1 joerg #include "clang/AST/ASTContext.h" 40 1.1 joerg #include "clang/AST/ASTDiagnostic.h" 41 1.1 joerg #include "clang/AST/ASTLambda.h" 42 1.1.1.2 joerg #include "clang/AST/Attr.h" 43 1.1 joerg #include "clang/AST/CXXInheritance.h" 44 1.1 joerg #include "clang/AST/CharUnits.h" 45 1.1 joerg #include "clang/AST/CurrentSourceLocExprScope.h" 46 1.1 joerg #include "clang/AST/Expr.h" 47 1.1 joerg #include "clang/AST/OSLog.h" 48 1.1 joerg #include "clang/AST/OptionalDiagnostic.h" 49 1.1 joerg #include "clang/AST/RecordLayout.h" 50 1.1 joerg #include "clang/AST/StmtVisitor.h" 51 1.1 joerg #include "clang/AST/TypeLoc.h" 52 1.1 joerg #include "clang/Basic/Builtins.h" 53 1.1 joerg #include "clang/Basic/TargetInfo.h" 54 1.1.1.2 joerg #include "llvm/ADT/APFixedPoint.h" 55 1.1 joerg #include "llvm/ADT/Optional.h" 56 1.1 joerg #include "llvm/ADT/SmallBitVector.h" 57 1.1.1.2 joerg #include "llvm/Support/Debug.h" 58 1.1 joerg #include "llvm/Support/SaveAndRestore.h" 59 1.1 joerg #include "llvm/Support/raw_ostream.h" 60 1.1.1.2 joerg #include <cstring> 61 1.1.1.2 joerg #include <functional> 62 1.1 joerg 63 1.1 joerg #define DEBUG_TYPE "exprconstant" 64 1.1 joerg 65 1.1 joerg using namespace clang; 66 1.1.1.2 joerg using llvm::APFixedPoint; 67 1.1 joerg using llvm::APInt; 68 1.1 joerg using llvm::APSInt; 69 1.1 joerg using llvm::APFloat; 70 1.1.1.2 joerg using llvm::FixedPointSemantics; 71 1.1 joerg using llvm::Optional; 72 1.1 joerg 73 1.1 joerg namespace { 74 1.1 joerg struct LValue; 75 1.1 joerg class CallStackFrame; 76 1.1 joerg class EvalInfo; 77 1.1 joerg 78 1.1 joerg using SourceLocExprScopeGuard = 79 1.1 joerg CurrentSourceLocExprScope::SourceLocExprScopeGuard; 80 1.1 joerg 81 1.1 joerg static QualType getType(APValue::LValueBase B) { 82 1.1.1.2 joerg return B.getType(); 83 1.1 joerg } 84 1.1 joerg 85 1.1 joerg /// Get an LValue path entry, which is known to not be an array index, as a 86 1.1 joerg /// field declaration. 87 1.1 joerg static const FieldDecl *getAsField(APValue::LValuePathEntry E) { 88 1.1 joerg return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer()); 89 1.1 joerg } 90 1.1 joerg /// Get an LValue path entry, which is known to not be an array index, as a 91 1.1 joerg /// base class declaration. 92 1.1 joerg static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) { 93 1.1 joerg return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer()); 94 1.1 joerg } 95 1.1 joerg /// Determine whether this LValue path entry for a base class names a virtual 96 1.1 joerg /// base class. 97 1.1 joerg static bool isVirtualBaseClass(APValue::LValuePathEntry E) { 98 1.1 joerg return E.getAsBaseOrMember().getInt(); 99 1.1 joerg } 100 1.1 joerg 101 1.1 joerg /// Given an expression, determine the type used to store the result of 102 1.1 joerg /// evaluating that expression. 103 1.1 joerg static QualType getStorageType(const ASTContext &Ctx, const Expr *E) { 104 1.1 joerg if (E->isRValue()) 105 1.1 joerg return E->getType(); 106 1.1 joerg return Ctx.getLValueReferenceType(E->getType()); 107 1.1 joerg } 108 1.1 joerg 109 1.1 joerg /// Given a CallExpr, try to get the alloc_size attribute. May return null. 110 1.1 joerg static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) { 111 1.1.1.2 joerg if (const FunctionDecl *DirectCallee = CE->getDirectCallee()) 112 1.1.1.2 joerg return DirectCallee->getAttr<AllocSizeAttr>(); 113 1.1.1.2 joerg if (const Decl *IndirectCallee = CE->getCalleeDecl()) 114 1.1.1.2 joerg return IndirectCallee->getAttr<AllocSizeAttr>(); 115 1.1.1.2 joerg return nullptr; 116 1.1 joerg } 117 1.1 joerg 118 1.1 joerg /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr. 119 1.1 joerg /// This will look through a single cast. 120 1.1 joerg /// 121 1.1 joerg /// Returns null if we couldn't unwrap a function with alloc_size. 122 1.1 joerg static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) { 123 1.1 joerg if (!E->getType()->isPointerType()) 124 1.1 joerg return nullptr; 125 1.1 joerg 126 1.1 joerg E = E->IgnoreParens(); 127 1.1 joerg // If we're doing a variable assignment from e.g. malloc(N), there will 128 1.1 joerg // probably be a cast of some kind. In exotic cases, we might also see a 129 1.1 joerg // top-level ExprWithCleanups. Ignore them either way. 130 1.1 joerg if (const auto *FE = dyn_cast<FullExpr>(E)) 131 1.1 joerg E = FE->getSubExpr()->IgnoreParens(); 132 1.1 joerg 133 1.1 joerg if (const auto *Cast = dyn_cast<CastExpr>(E)) 134 1.1 joerg E = Cast->getSubExpr()->IgnoreParens(); 135 1.1 joerg 136 1.1 joerg if (const auto *CE = dyn_cast<CallExpr>(E)) 137 1.1 joerg return getAllocSizeAttr(CE) ? CE : nullptr; 138 1.1 joerg return nullptr; 139 1.1 joerg } 140 1.1 joerg 141 1.1 joerg /// Determines whether or not the given Base contains a call to a function 142 1.1 joerg /// with the alloc_size attribute. 143 1.1 joerg static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) { 144 1.1 joerg const auto *E = Base.dyn_cast<const Expr *>(); 145 1.1 joerg return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E); 146 1.1 joerg } 147 1.1 joerg 148 1.1.1.2 joerg /// Determines whether the given kind of constant expression is only ever 149 1.1.1.2 joerg /// used for name mangling. If so, it's permitted to reference things that we 150 1.1.1.2 joerg /// can't generate code for (in particular, dllimported functions). 151 1.1.1.2 joerg static bool isForManglingOnly(ConstantExprKind Kind) { 152 1.1.1.2 joerg switch (Kind) { 153 1.1.1.2 joerg case ConstantExprKind::Normal: 154 1.1.1.2 joerg case ConstantExprKind::ClassTemplateArgument: 155 1.1.1.2 joerg case ConstantExprKind::ImmediateInvocation: 156 1.1.1.2 joerg // Note that non-type template arguments of class type are emitted as 157 1.1.1.2 joerg // template parameter objects. 158 1.1.1.2 joerg return false; 159 1.1.1.2 joerg 160 1.1.1.2 joerg case ConstantExprKind::NonClassTemplateArgument: 161 1.1.1.2 joerg return true; 162 1.1.1.2 joerg } 163 1.1.1.2 joerg llvm_unreachable("unknown ConstantExprKind"); 164 1.1.1.2 joerg } 165 1.1.1.2 joerg 166 1.1.1.2 joerg static bool isTemplateArgument(ConstantExprKind Kind) { 167 1.1.1.2 joerg switch (Kind) { 168 1.1.1.2 joerg case ConstantExprKind::Normal: 169 1.1.1.2 joerg case ConstantExprKind::ImmediateInvocation: 170 1.1.1.2 joerg return false; 171 1.1.1.2 joerg 172 1.1.1.2 joerg case ConstantExprKind::ClassTemplateArgument: 173 1.1.1.2 joerg case ConstantExprKind::NonClassTemplateArgument: 174 1.1.1.2 joerg return true; 175 1.1.1.2 joerg } 176 1.1.1.2 joerg llvm_unreachable("unknown ConstantExprKind"); 177 1.1.1.2 joerg } 178 1.1.1.2 joerg 179 1.1 joerg /// The bound to claim that an array of unknown bound has. 180 1.1 joerg /// The value in MostDerivedArraySize is undefined in this case. So, set it 181 1.1 joerg /// to an arbitrary value that's likely to loudly break things if it's used. 182 1.1 joerg static const uint64_t AssumedSizeForUnsizedArray = 183 1.1 joerg std::numeric_limits<uint64_t>::max() / 2; 184 1.1 joerg 185 1.1 joerg /// Determines if an LValue with the given LValueBase will have an unsized 186 1.1 joerg /// array in its designator. 187 1.1 joerg /// Find the path length and type of the most-derived subobject in the given 188 1.1 joerg /// path, and find the size of the containing array, if any. 189 1.1 joerg static unsigned 190 1.1 joerg findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base, 191 1.1 joerg ArrayRef<APValue::LValuePathEntry> Path, 192 1.1 joerg uint64_t &ArraySize, QualType &Type, bool &IsArray, 193 1.1 joerg bool &FirstEntryIsUnsizedArray) { 194 1.1 joerg // This only accepts LValueBases from APValues, and APValues don't support 195 1.1 joerg // arrays that lack size info. 196 1.1 joerg assert(!isBaseAnAllocSizeCall(Base) && 197 1.1 joerg "Unsized arrays shouldn't appear here"); 198 1.1 joerg unsigned MostDerivedLength = 0; 199 1.1 joerg Type = getType(Base); 200 1.1 joerg 201 1.1 joerg for (unsigned I = 0, N = Path.size(); I != N; ++I) { 202 1.1 joerg if (Type->isArrayType()) { 203 1.1 joerg const ArrayType *AT = Ctx.getAsArrayType(Type); 204 1.1 joerg Type = AT->getElementType(); 205 1.1 joerg MostDerivedLength = I + 1; 206 1.1 joerg IsArray = true; 207 1.1 joerg 208 1.1 joerg if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) { 209 1.1 joerg ArraySize = CAT->getSize().getZExtValue(); 210 1.1 joerg } else { 211 1.1 joerg assert(I == 0 && "unexpected unsized array designator"); 212 1.1 joerg FirstEntryIsUnsizedArray = true; 213 1.1 joerg ArraySize = AssumedSizeForUnsizedArray; 214 1.1 joerg } 215 1.1 joerg } else if (Type->isAnyComplexType()) { 216 1.1 joerg const ComplexType *CT = Type->castAs<ComplexType>(); 217 1.1 joerg Type = CT->getElementType(); 218 1.1 joerg ArraySize = 2; 219 1.1 joerg MostDerivedLength = I + 1; 220 1.1 joerg IsArray = true; 221 1.1 joerg } else if (const FieldDecl *FD = getAsField(Path[I])) { 222 1.1 joerg Type = FD->getType(); 223 1.1 joerg ArraySize = 0; 224 1.1 joerg MostDerivedLength = I + 1; 225 1.1 joerg IsArray = false; 226 1.1 joerg } else { 227 1.1 joerg // Path[I] describes a base class. 228 1.1 joerg ArraySize = 0; 229 1.1 joerg IsArray = false; 230 1.1 joerg } 231 1.1 joerg } 232 1.1 joerg return MostDerivedLength; 233 1.1 joerg } 234 1.1 joerg 235 1.1 joerg /// A path from a glvalue to a subobject of that glvalue. 236 1.1 joerg struct SubobjectDesignator { 237 1.1 joerg /// True if the subobject was named in a manner not supported by C++11. Such 238 1.1 joerg /// lvalues can still be folded, but they are not core constant expressions 239 1.1 joerg /// and we cannot perform lvalue-to-rvalue conversions on them. 240 1.1 joerg unsigned Invalid : 1; 241 1.1 joerg 242 1.1 joerg /// Is this a pointer one past the end of an object? 243 1.1 joerg unsigned IsOnePastTheEnd : 1; 244 1.1 joerg 245 1.1 joerg /// Indicator of whether the first entry is an unsized array. 246 1.1 joerg unsigned FirstEntryIsAnUnsizedArray : 1; 247 1.1 joerg 248 1.1 joerg /// Indicator of whether the most-derived object is an array element. 249 1.1 joerg unsigned MostDerivedIsArrayElement : 1; 250 1.1 joerg 251 1.1 joerg /// The length of the path to the most-derived object of which this is a 252 1.1 joerg /// subobject. 253 1.1 joerg unsigned MostDerivedPathLength : 28; 254 1.1 joerg 255 1.1 joerg /// The size of the array of which the most-derived object is an element. 256 1.1 joerg /// This will always be 0 if the most-derived object is not an array 257 1.1 joerg /// element. 0 is not an indicator of whether or not the most-derived object 258 1.1 joerg /// is an array, however, because 0-length arrays are allowed. 259 1.1 joerg /// 260 1.1 joerg /// If the current array is an unsized array, the value of this is 261 1.1 joerg /// undefined. 262 1.1 joerg uint64_t MostDerivedArraySize; 263 1.1 joerg 264 1.1 joerg /// The type of the most derived object referred to by this address. 265 1.1 joerg QualType MostDerivedType; 266 1.1 joerg 267 1.1 joerg typedef APValue::LValuePathEntry PathEntry; 268 1.1 joerg 269 1.1 joerg /// The entries on the path from the glvalue to the designated subobject. 270 1.1 joerg SmallVector<PathEntry, 8> Entries; 271 1.1 joerg 272 1.1 joerg SubobjectDesignator() : Invalid(true) {} 273 1.1 joerg 274 1.1 joerg explicit SubobjectDesignator(QualType T) 275 1.1 joerg : Invalid(false), IsOnePastTheEnd(false), 276 1.1 joerg FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false), 277 1.1 joerg MostDerivedPathLength(0), MostDerivedArraySize(0), 278 1.1 joerg MostDerivedType(T) {} 279 1.1 joerg 280 1.1 joerg SubobjectDesignator(ASTContext &Ctx, const APValue &V) 281 1.1 joerg : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false), 282 1.1 joerg FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false), 283 1.1 joerg MostDerivedPathLength(0), MostDerivedArraySize(0) { 284 1.1 joerg assert(V.isLValue() && "Non-LValue used to make an LValue designator?"); 285 1.1 joerg if (!Invalid) { 286 1.1 joerg IsOnePastTheEnd = V.isLValueOnePastTheEnd(); 287 1.1 joerg ArrayRef<PathEntry> VEntries = V.getLValuePath(); 288 1.1 joerg Entries.insert(Entries.end(), VEntries.begin(), VEntries.end()); 289 1.1 joerg if (V.getLValueBase()) { 290 1.1 joerg bool IsArray = false; 291 1.1 joerg bool FirstIsUnsizedArray = false; 292 1.1 joerg MostDerivedPathLength = findMostDerivedSubobject( 293 1.1 joerg Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize, 294 1.1 joerg MostDerivedType, IsArray, FirstIsUnsizedArray); 295 1.1 joerg MostDerivedIsArrayElement = IsArray; 296 1.1 joerg FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray; 297 1.1 joerg } 298 1.1 joerg } 299 1.1 joerg } 300 1.1 joerg 301 1.1 joerg void truncate(ASTContext &Ctx, APValue::LValueBase Base, 302 1.1 joerg unsigned NewLength) { 303 1.1 joerg if (Invalid) 304 1.1 joerg return; 305 1.1 joerg 306 1.1 joerg assert(Base && "cannot truncate path for null pointer"); 307 1.1 joerg assert(NewLength <= Entries.size() && "not a truncation"); 308 1.1 joerg 309 1.1 joerg if (NewLength == Entries.size()) 310 1.1 joerg return; 311 1.1 joerg Entries.resize(NewLength); 312 1.1 joerg 313 1.1 joerg bool IsArray = false; 314 1.1 joerg bool FirstIsUnsizedArray = false; 315 1.1 joerg MostDerivedPathLength = findMostDerivedSubobject( 316 1.1 joerg Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray, 317 1.1 joerg FirstIsUnsizedArray); 318 1.1 joerg MostDerivedIsArrayElement = IsArray; 319 1.1 joerg FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray; 320 1.1 joerg } 321 1.1 joerg 322 1.1 joerg void setInvalid() { 323 1.1 joerg Invalid = true; 324 1.1 joerg Entries.clear(); 325 1.1 joerg } 326 1.1 joerg 327 1.1 joerg /// Determine whether the most derived subobject is an array without a 328 1.1 joerg /// known bound. 329 1.1 joerg bool isMostDerivedAnUnsizedArray() const { 330 1.1 joerg assert(!Invalid && "Calling this makes no sense on invalid designators"); 331 1.1 joerg return Entries.size() == 1 && FirstEntryIsAnUnsizedArray; 332 1.1 joerg } 333 1.1 joerg 334 1.1 joerg /// Determine what the most derived array's size is. Results in an assertion 335 1.1 joerg /// failure if the most derived array lacks a size. 336 1.1 joerg uint64_t getMostDerivedArraySize() const { 337 1.1 joerg assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size"); 338 1.1 joerg return MostDerivedArraySize; 339 1.1 joerg } 340 1.1 joerg 341 1.1 joerg /// Determine whether this is a one-past-the-end pointer. 342 1.1 joerg bool isOnePastTheEnd() const { 343 1.1 joerg assert(!Invalid); 344 1.1 joerg if (IsOnePastTheEnd) 345 1.1 joerg return true; 346 1.1 joerg if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement && 347 1.1 joerg Entries[MostDerivedPathLength - 1].getAsArrayIndex() == 348 1.1 joerg MostDerivedArraySize) 349 1.1 joerg return true; 350 1.1 joerg return false; 351 1.1 joerg } 352 1.1 joerg 353 1.1 joerg /// Get the range of valid index adjustments in the form 354 1.1 joerg /// {maximum value that can be subtracted from this pointer, 355 1.1 joerg /// maximum value that can be added to this pointer} 356 1.1 joerg std::pair<uint64_t, uint64_t> validIndexAdjustments() { 357 1.1 joerg if (Invalid || isMostDerivedAnUnsizedArray()) 358 1.1 joerg return {0, 0}; 359 1.1 joerg 360 1.1 joerg // [expr.add]p4: For the purposes of these operators, a pointer to a 361 1.1 joerg // nonarray object behaves the same as a pointer to the first element of 362 1.1 joerg // an array of length one with the type of the object as its element type. 363 1.1 joerg bool IsArray = MostDerivedPathLength == Entries.size() && 364 1.1 joerg MostDerivedIsArrayElement; 365 1.1 joerg uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex() 366 1.1 joerg : (uint64_t)IsOnePastTheEnd; 367 1.1 joerg uint64_t ArraySize = 368 1.1 joerg IsArray ? getMostDerivedArraySize() : (uint64_t)1; 369 1.1 joerg return {ArrayIndex, ArraySize - ArrayIndex}; 370 1.1 joerg } 371 1.1 joerg 372 1.1 joerg /// Check that this refers to a valid subobject. 373 1.1 joerg bool isValidSubobject() const { 374 1.1 joerg if (Invalid) 375 1.1 joerg return false; 376 1.1 joerg return !isOnePastTheEnd(); 377 1.1 joerg } 378 1.1 joerg /// Check that this refers to a valid subobject, and if not, produce a 379 1.1 joerg /// relevant diagnostic and set the designator as invalid. 380 1.1 joerg bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK); 381 1.1 joerg 382 1.1 joerg /// Get the type of the designated object. 383 1.1 joerg QualType getType(ASTContext &Ctx) const { 384 1.1 joerg assert(!Invalid && "invalid designator has no subobject type"); 385 1.1 joerg return MostDerivedPathLength == Entries.size() 386 1.1 joerg ? MostDerivedType 387 1.1 joerg : Ctx.getRecordType(getAsBaseClass(Entries.back())); 388 1.1 joerg } 389 1.1 joerg 390 1.1 joerg /// Update this designator to refer to the first element within this array. 391 1.1 joerg void addArrayUnchecked(const ConstantArrayType *CAT) { 392 1.1 joerg Entries.push_back(PathEntry::ArrayIndex(0)); 393 1.1 joerg 394 1.1 joerg // This is a most-derived object. 395 1.1 joerg MostDerivedType = CAT->getElementType(); 396 1.1 joerg MostDerivedIsArrayElement = true; 397 1.1 joerg MostDerivedArraySize = CAT->getSize().getZExtValue(); 398 1.1 joerg MostDerivedPathLength = Entries.size(); 399 1.1 joerg } 400 1.1 joerg /// Update this designator to refer to the first element within the array of 401 1.1 joerg /// elements of type T. This is an array of unknown size. 402 1.1 joerg void addUnsizedArrayUnchecked(QualType ElemTy) { 403 1.1 joerg Entries.push_back(PathEntry::ArrayIndex(0)); 404 1.1 joerg 405 1.1 joerg MostDerivedType = ElemTy; 406 1.1 joerg MostDerivedIsArrayElement = true; 407 1.1 joerg // The value in MostDerivedArraySize is undefined in this case. So, set it 408 1.1 joerg // to an arbitrary value that's likely to loudly break things if it's 409 1.1 joerg // used. 410 1.1 joerg MostDerivedArraySize = AssumedSizeForUnsizedArray; 411 1.1 joerg MostDerivedPathLength = Entries.size(); 412 1.1 joerg } 413 1.1 joerg /// Update this designator to refer to the given base or member of this 414 1.1 joerg /// object. 415 1.1 joerg void addDeclUnchecked(const Decl *D, bool Virtual = false) { 416 1.1 joerg Entries.push_back(APValue::BaseOrMemberType(D, Virtual)); 417 1.1 joerg 418 1.1 joerg // If this isn't a base class, it's a new most-derived object. 419 1.1 joerg if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) { 420 1.1 joerg MostDerivedType = FD->getType(); 421 1.1 joerg MostDerivedIsArrayElement = false; 422 1.1 joerg MostDerivedArraySize = 0; 423 1.1 joerg MostDerivedPathLength = Entries.size(); 424 1.1 joerg } 425 1.1 joerg } 426 1.1 joerg /// Update this designator to refer to the given complex component. 427 1.1 joerg void addComplexUnchecked(QualType EltTy, bool Imag) { 428 1.1 joerg Entries.push_back(PathEntry::ArrayIndex(Imag)); 429 1.1 joerg 430 1.1 joerg // This is technically a most-derived object, though in practice this 431 1.1 joerg // is unlikely to matter. 432 1.1 joerg MostDerivedType = EltTy; 433 1.1 joerg MostDerivedIsArrayElement = true; 434 1.1 joerg MostDerivedArraySize = 2; 435 1.1 joerg MostDerivedPathLength = Entries.size(); 436 1.1 joerg } 437 1.1 joerg void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E); 438 1.1 joerg void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, 439 1.1 joerg const APSInt &N); 440 1.1 joerg /// Add N to the address of this subobject. 441 1.1 joerg void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) { 442 1.1 joerg if (Invalid || !N) return; 443 1.1 joerg uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue(); 444 1.1 joerg if (isMostDerivedAnUnsizedArray()) { 445 1.1 joerg diagnoseUnsizedArrayPointerArithmetic(Info, E); 446 1.1 joerg // Can't verify -- trust that the user is doing the right thing (or if 447 1.1 joerg // not, trust that the caller will catch the bad behavior). 448 1.1 joerg // FIXME: Should we reject if this overflows, at least? 449 1.1 joerg Entries.back() = PathEntry::ArrayIndex( 450 1.1 joerg Entries.back().getAsArrayIndex() + TruncatedN); 451 1.1 joerg return; 452 1.1 joerg } 453 1.1 joerg 454 1.1 joerg // [expr.add]p4: For the purposes of these operators, a pointer to a 455 1.1 joerg // nonarray object behaves the same as a pointer to the first element of 456 1.1 joerg // an array of length one with the type of the object as its element type. 457 1.1 joerg bool IsArray = MostDerivedPathLength == Entries.size() && 458 1.1 joerg MostDerivedIsArrayElement; 459 1.1 joerg uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex() 460 1.1 joerg : (uint64_t)IsOnePastTheEnd; 461 1.1 joerg uint64_t ArraySize = 462 1.1 joerg IsArray ? getMostDerivedArraySize() : (uint64_t)1; 463 1.1 joerg 464 1.1 joerg if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) { 465 1.1 joerg // Calculate the actual index in a wide enough type, so we can include 466 1.1 joerg // it in the note. 467 1.1 joerg N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65)); 468 1.1 joerg (llvm::APInt&)N += ArrayIndex; 469 1.1 joerg assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index"); 470 1.1 joerg diagnosePointerArithmetic(Info, E, N); 471 1.1 joerg setInvalid(); 472 1.1 joerg return; 473 1.1 joerg } 474 1.1 joerg 475 1.1 joerg ArrayIndex += TruncatedN; 476 1.1 joerg assert(ArrayIndex <= ArraySize && 477 1.1 joerg "bounds check succeeded for out-of-bounds index"); 478 1.1 joerg 479 1.1 joerg if (IsArray) 480 1.1 joerg Entries.back() = PathEntry::ArrayIndex(ArrayIndex); 481 1.1 joerg else 482 1.1 joerg IsOnePastTheEnd = (ArrayIndex != 0); 483 1.1 joerg } 484 1.1 joerg }; 485 1.1 joerg 486 1.1.1.2 joerg /// A scope at the end of which an object can need to be destroyed. 487 1.1.1.2 joerg enum class ScopeKind { 488 1.1.1.2 joerg Block, 489 1.1.1.2 joerg FullExpression, 490 1.1.1.2 joerg Call 491 1.1.1.2 joerg }; 492 1.1.1.2 joerg 493 1.1.1.2 joerg /// A reference to a particular call and its arguments. 494 1.1.1.2 joerg struct CallRef { 495 1.1.1.2 joerg CallRef() : OrigCallee(), CallIndex(0), Version() {} 496 1.1.1.2 joerg CallRef(const FunctionDecl *Callee, unsigned CallIndex, unsigned Version) 497 1.1.1.2 joerg : OrigCallee(Callee), CallIndex(CallIndex), Version(Version) {} 498 1.1.1.2 joerg 499 1.1.1.2 joerg explicit operator bool() const { return OrigCallee; } 500 1.1.1.2 joerg 501 1.1.1.2 joerg /// Get the parameter that the caller initialized, corresponding to the 502 1.1.1.2 joerg /// given parameter in the callee. 503 1.1.1.2 joerg const ParmVarDecl *getOrigParam(const ParmVarDecl *PVD) const { 504 1.1.1.2 joerg return OrigCallee ? OrigCallee->getParamDecl(PVD->getFunctionScopeIndex()) 505 1.1.1.2 joerg : PVD; 506 1.1.1.2 joerg } 507 1.1.1.2 joerg 508 1.1.1.2 joerg /// The callee at the point where the arguments were evaluated. This might 509 1.1.1.2 joerg /// be different from the actual callee (a different redeclaration, or a 510 1.1.1.2 joerg /// virtual override), but this function's parameters are the ones that 511 1.1.1.2 joerg /// appear in the parameter map. 512 1.1.1.2 joerg const FunctionDecl *OrigCallee; 513 1.1.1.2 joerg /// The call index of the frame that holds the argument values. 514 1.1.1.2 joerg unsigned CallIndex; 515 1.1.1.2 joerg /// The version of the parameters corresponding to this call. 516 1.1.1.2 joerg unsigned Version; 517 1.1.1.2 joerg }; 518 1.1.1.2 joerg 519 1.1 joerg /// A stack frame in the constexpr call stack. 520 1.1 joerg class CallStackFrame : public interp::Frame { 521 1.1 joerg public: 522 1.1 joerg EvalInfo &Info; 523 1.1 joerg 524 1.1 joerg /// Parent - The caller of this stack frame. 525 1.1 joerg CallStackFrame *Caller; 526 1.1 joerg 527 1.1 joerg /// Callee - The function which was called. 528 1.1 joerg const FunctionDecl *Callee; 529 1.1 joerg 530 1.1 joerg /// This - The binding for the this pointer in this call, if any. 531 1.1 joerg const LValue *This; 532 1.1 joerg 533 1.1.1.2 joerg /// Information on how to find the arguments to this call. Our arguments 534 1.1.1.2 joerg /// are stored in our parent's CallStackFrame, using the ParmVarDecl* as a 535 1.1.1.2 joerg /// key and this value as the version. 536 1.1.1.2 joerg CallRef Arguments; 537 1.1 joerg 538 1.1 joerg /// Source location information about the default argument or default 539 1.1 joerg /// initializer expression we're evaluating, if any. 540 1.1 joerg CurrentSourceLocExprScope CurSourceLocExprScope; 541 1.1 joerg 542 1.1 joerg // Note that we intentionally use std::map here so that references to 543 1.1 joerg // values are stable. 544 1.1 joerg typedef std::pair<const void *, unsigned> MapKeyTy; 545 1.1 joerg typedef std::map<MapKeyTy, APValue> MapTy; 546 1.1 joerg /// Temporaries - Temporary lvalues materialized within this stack frame. 547 1.1 joerg MapTy Temporaries; 548 1.1 joerg 549 1.1 joerg /// CallLoc - The location of the call expression for this call. 550 1.1 joerg SourceLocation CallLoc; 551 1.1 joerg 552 1.1 joerg /// Index - The call index of this call. 553 1.1 joerg unsigned Index; 554 1.1 joerg 555 1.1 joerg /// The stack of integers for tracking version numbers for temporaries. 556 1.1 joerg SmallVector<unsigned, 2> TempVersionStack = {1}; 557 1.1 joerg unsigned CurTempVersion = TempVersionStack.back(); 558 1.1 joerg 559 1.1 joerg unsigned getTempVersion() const { return TempVersionStack.back(); } 560 1.1 joerg 561 1.1 joerg void pushTempVersion() { 562 1.1 joerg TempVersionStack.push_back(++CurTempVersion); 563 1.1 joerg } 564 1.1 joerg 565 1.1 joerg void popTempVersion() { 566 1.1 joerg TempVersionStack.pop_back(); 567 1.1 joerg } 568 1.1 joerg 569 1.1.1.2 joerg CallRef createCall(const FunctionDecl *Callee) { 570 1.1.1.2 joerg return {Callee, Index, ++CurTempVersion}; 571 1.1.1.2 joerg } 572 1.1.1.2 joerg 573 1.1 joerg // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact 574 1.1 joerg // on the overall stack usage of deeply-recursing constexpr evaluations. 575 1.1 joerg // (We should cache this map rather than recomputing it repeatedly.) 576 1.1 joerg // But let's try this and see how it goes; we can look into caching the map 577 1.1 joerg // as a later change. 578 1.1 joerg 579 1.1 joerg /// LambdaCaptureFields - Mapping from captured variables/this to 580 1.1 joerg /// corresponding data members in the closure class. 581 1.1 joerg llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields; 582 1.1 joerg FieldDecl *LambdaThisCaptureField; 583 1.1 joerg 584 1.1 joerg CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, 585 1.1 joerg const FunctionDecl *Callee, const LValue *This, 586 1.1.1.2 joerg CallRef Arguments); 587 1.1 joerg ~CallStackFrame(); 588 1.1 joerg 589 1.1 joerg // Return the temporary for Key whose version number is Version. 590 1.1 joerg APValue *getTemporary(const void *Key, unsigned Version) { 591 1.1 joerg MapKeyTy KV(Key, Version); 592 1.1 joerg auto LB = Temporaries.lower_bound(KV); 593 1.1 joerg if (LB != Temporaries.end() && LB->first == KV) 594 1.1 joerg return &LB->second; 595 1.1 joerg // Pair (Key,Version) wasn't found in the map. Check that no elements 596 1.1 joerg // in the map have 'Key' as their key. 597 1.1 joerg assert((LB == Temporaries.end() || LB->first.first != Key) && 598 1.1 joerg (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) && 599 1.1 joerg "Element with key 'Key' found in map"); 600 1.1 joerg return nullptr; 601 1.1 joerg } 602 1.1 joerg 603 1.1 joerg // Return the current temporary for Key in the map. 604 1.1 joerg APValue *getCurrentTemporary(const void *Key) { 605 1.1 joerg auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX)); 606 1.1 joerg if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key) 607 1.1 joerg return &std::prev(UB)->second; 608 1.1 joerg return nullptr; 609 1.1 joerg } 610 1.1 joerg 611 1.1 joerg // Return the version number of the current temporary for Key. 612 1.1 joerg unsigned getCurrentTemporaryVersion(const void *Key) const { 613 1.1 joerg auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX)); 614 1.1 joerg if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key) 615 1.1 joerg return std::prev(UB)->first.second; 616 1.1 joerg return 0; 617 1.1 joerg } 618 1.1 joerg 619 1.1 joerg /// Allocate storage for an object of type T in this stack frame. 620 1.1 joerg /// Populates LV with a handle to the created object. Key identifies 621 1.1 joerg /// the temporary within the stack frame, and must not be reused without 622 1.1 joerg /// bumping the temporary version number. 623 1.1 joerg template<typename KeyT> 624 1.1 joerg APValue &createTemporary(const KeyT *Key, QualType T, 625 1.1.1.2 joerg ScopeKind Scope, LValue &LV); 626 1.1.1.2 joerg 627 1.1.1.2 joerg /// Allocate storage for a parameter of a function call made in this frame. 628 1.1.1.2 joerg APValue &createParam(CallRef Args, const ParmVarDecl *PVD, LValue &LV); 629 1.1 joerg 630 1.1 joerg void describe(llvm::raw_ostream &OS) override; 631 1.1 joerg 632 1.1 joerg Frame *getCaller() const override { return Caller; } 633 1.1 joerg SourceLocation getCallLocation() const override { return CallLoc; } 634 1.1 joerg const FunctionDecl *getCallee() const override { return Callee; } 635 1.1 joerg 636 1.1 joerg bool isStdFunction() const { 637 1.1 joerg for (const DeclContext *DC = Callee; DC; DC = DC->getParent()) 638 1.1 joerg if (DC->isStdNamespace()) 639 1.1 joerg return true; 640 1.1 joerg return false; 641 1.1 joerg } 642 1.1.1.2 joerg 643 1.1.1.2 joerg private: 644 1.1.1.2 joerg APValue &createLocal(APValue::LValueBase Base, const void *Key, QualType T, 645 1.1.1.2 joerg ScopeKind Scope); 646 1.1 joerg }; 647 1.1 joerg 648 1.1 joerg /// Temporarily override 'this'. 649 1.1 joerg class ThisOverrideRAII { 650 1.1 joerg public: 651 1.1 joerg ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable) 652 1.1 joerg : Frame(Frame), OldThis(Frame.This) { 653 1.1 joerg if (Enable) 654 1.1 joerg Frame.This = NewThis; 655 1.1 joerg } 656 1.1 joerg ~ThisOverrideRAII() { 657 1.1 joerg Frame.This = OldThis; 658 1.1 joerg } 659 1.1 joerg private: 660 1.1 joerg CallStackFrame &Frame; 661 1.1 joerg const LValue *OldThis; 662 1.1 joerg }; 663 1.1 joerg } 664 1.1 joerg 665 1.1 joerg static bool HandleDestruction(EvalInfo &Info, const Expr *E, 666 1.1 joerg const LValue &This, QualType ThisType); 667 1.1 joerg static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc, 668 1.1 joerg APValue::LValueBase LVBase, APValue &Value, 669 1.1 joerg QualType T); 670 1.1 joerg 671 1.1 joerg namespace { 672 1.1 joerg /// A cleanup, and a flag indicating whether it is lifetime-extended. 673 1.1 joerg class Cleanup { 674 1.1.1.2 joerg llvm::PointerIntPair<APValue*, 2, ScopeKind> Value; 675 1.1 joerg APValue::LValueBase Base; 676 1.1 joerg QualType T; 677 1.1 joerg 678 1.1 joerg public: 679 1.1 joerg Cleanup(APValue *Val, APValue::LValueBase Base, QualType T, 680 1.1.1.2 joerg ScopeKind Scope) 681 1.1.1.2 joerg : Value(Val, Scope), Base(Base), T(T) {} 682 1.1 joerg 683 1.1.1.2 joerg /// Determine whether this cleanup should be performed at the end of the 684 1.1.1.2 joerg /// given kind of scope. 685 1.1.1.2 joerg bool isDestroyedAtEndOf(ScopeKind K) const { 686 1.1.1.2 joerg return (int)Value.getInt() >= (int)K; 687 1.1.1.2 joerg } 688 1.1 joerg bool endLifetime(EvalInfo &Info, bool RunDestructors) { 689 1.1 joerg if (RunDestructors) { 690 1.1 joerg SourceLocation Loc; 691 1.1 joerg if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) 692 1.1 joerg Loc = VD->getLocation(); 693 1.1 joerg else if (const Expr *E = Base.dyn_cast<const Expr*>()) 694 1.1 joerg Loc = E->getExprLoc(); 695 1.1 joerg return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T); 696 1.1 joerg } 697 1.1 joerg *Value.getPointer() = APValue(); 698 1.1 joerg return true; 699 1.1 joerg } 700 1.1 joerg 701 1.1 joerg bool hasSideEffect() { 702 1.1 joerg return T.isDestructedType(); 703 1.1 joerg } 704 1.1 joerg }; 705 1.1 joerg 706 1.1 joerg /// A reference to an object whose construction we are currently evaluating. 707 1.1 joerg struct ObjectUnderConstruction { 708 1.1 joerg APValue::LValueBase Base; 709 1.1 joerg ArrayRef<APValue::LValuePathEntry> Path; 710 1.1 joerg friend bool operator==(const ObjectUnderConstruction &LHS, 711 1.1 joerg const ObjectUnderConstruction &RHS) { 712 1.1 joerg return LHS.Base == RHS.Base && LHS.Path == RHS.Path; 713 1.1 joerg } 714 1.1 joerg friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) { 715 1.1 joerg return llvm::hash_combine(Obj.Base, Obj.Path); 716 1.1 joerg } 717 1.1 joerg }; 718 1.1 joerg enum class ConstructionPhase { 719 1.1 joerg None, 720 1.1 joerg Bases, 721 1.1 joerg AfterBases, 722 1.1.1.2 joerg AfterFields, 723 1.1 joerg Destroying, 724 1.1 joerg DestroyingBases 725 1.1 joerg }; 726 1.1 joerg } 727 1.1 joerg 728 1.1 joerg namespace llvm { 729 1.1 joerg template<> struct DenseMapInfo<ObjectUnderConstruction> { 730 1.1 joerg using Base = DenseMapInfo<APValue::LValueBase>; 731 1.1 joerg static ObjectUnderConstruction getEmptyKey() { 732 1.1 joerg return {Base::getEmptyKey(), {}}; } 733 1.1 joerg static ObjectUnderConstruction getTombstoneKey() { 734 1.1 joerg return {Base::getTombstoneKey(), {}}; 735 1.1 joerg } 736 1.1 joerg static unsigned getHashValue(const ObjectUnderConstruction &Object) { 737 1.1 joerg return hash_value(Object); 738 1.1 joerg } 739 1.1 joerg static bool isEqual(const ObjectUnderConstruction &LHS, 740 1.1 joerg const ObjectUnderConstruction &RHS) { 741 1.1 joerg return LHS == RHS; 742 1.1 joerg } 743 1.1 joerg }; 744 1.1 joerg } 745 1.1 joerg 746 1.1 joerg namespace { 747 1.1 joerg /// A dynamically-allocated heap object. 748 1.1 joerg struct DynAlloc { 749 1.1 joerg /// The value of this heap-allocated object. 750 1.1 joerg APValue Value; 751 1.1 joerg /// The allocating expression; used for diagnostics. Either a CXXNewExpr 752 1.1 joerg /// or a CallExpr (the latter is for direct calls to operator new inside 753 1.1 joerg /// std::allocator<T>::allocate). 754 1.1 joerg const Expr *AllocExpr = nullptr; 755 1.1 joerg 756 1.1 joerg enum Kind { 757 1.1 joerg New, 758 1.1 joerg ArrayNew, 759 1.1 joerg StdAllocator 760 1.1 joerg }; 761 1.1 joerg 762 1.1 joerg /// Get the kind of the allocation. This must match between allocation 763 1.1 joerg /// and deallocation. 764 1.1 joerg Kind getKind() const { 765 1.1 joerg if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr)) 766 1.1 joerg return NE->isArray() ? ArrayNew : New; 767 1.1 joerg assert(isa<CallExpr>(AllocExpr)); 768 1.1 joerg return StdAllocator; 769 1.1 joerg } 770 1.1 joerg }; 771 1.1 joerg 772 1.1 joerg struct DynAllocOrder { 773 1.1 joerg bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const { 774 1.1 joerg return L.getIndex() < R.getIndex(); 775 1.1 joerg } 776 1.1 joerg }; 777 1.1 joerg 778 1.1 joerg /// EvalInfo - This is a private struct used by the evaluator to capture 779 1.1 joerg /// information about a subexpression as it is folded. It retains information 780 1.1 joerg /// about the AST context, but also maintains information about the folded 781 1.1 joerg /// expression. 782 1.1 joerg /// 783 1.1 joerg /// If an expression could be evaluated, it is still possible it is not a C 784 1.1 joerg /// "integer constant expression" or constant expression. If not, this struct 785 1.1 joerg /// captures information about how and why not. 786 1.1 joerg /// 787 1.1 joerg /// One bit of information passed *into* the request for constant folding 788 1.1 joerg /// indicates whether the subexpression is "evaluated" or not according to C 789 1.1 joerg /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can 790 1.1 joerg /// evaluate the expression regardless of what the RHS is, but C only allows 791 1.1 joerg /// certain things in certain situations. 792 1.1 joerg class EvalInfo : public interp::State { 793 1.1 joerg public: 794 1.1 joerg ASTContext &Ctx; 795 1.1 joerg 796 1.1 joerg /// EvalStatus - Contains information about the evaluation. 797 1.1 joerg Expr::EvalStatus &EvalStatus; 798 1.1 joerg 799 1.1 joerg /// CurrentCall - The top of the constexpr call stack. 800 1.1 joerg CallStackFrame *CurrentCall; 801 1.1 joerg 802 1.1 joerg /// CallStackDepth - The number of calls in the call stack right now. 803 1.1 joerg unsigned CallStackDepth; 804 1.1 joerg 805 1.1 joerg /// NextCallIndex - The next call index to assign. 806 1.1 joerg unsigned NextCallIndex; 807 1.1 joerg 808 1.1 joerg /// StepsLeft - The remaining number of evaluation steps we're permitted 809 1.1 joerg /// to perform. This is essentially a limit for the number of statements 810 1.1 joerg /// we will evaluate. 811 1.1 joerg unsigned StepsLeft; 812 1.1 joerg 813 1.1.1.2 joerg /// Enable the experimental new constant interpreter. If an expression is 814 1.1.1.2 joerg /// not supported by the interpreter, an error is triggered. 815 1.1 joerg bool EnableNewConstInterp; 816 1.1 joerg 817 1.1 joerg /// BottomFrame - The frame in which evaluation started. This must be 818 1.1 joerg /// initialized after CurrentCall and CallStackDepth. 819 1.1 joerg CallStackFrame BottomFrame; 820 1.1 joerg 821 1.1 joerg /// A stack of values whose lifetimes end at the end of some surrounding 822 1.1 joerg /// evaluation frame. 823 1.1 joerg llvm::SmallVector<Cleanup, 16> CleanupStack; 824 1.1 joerg 825 1.1 joerg /// EvaluatingDecl - This is the declaration whose initializer is being 826 1.1 joerg /// evaluated, if any. 827 1.1 joerg APValue::LValueBase EvaluatingDecl; 828 1.1 joerg 829 1.1 joerg enum class EvaluatingDeclKind { 830 1.1 joerg None, 831 1.1 joerg /// We're evaluating the construction of EvaluatingDecl. 832 1.1 joerg Ctor, 833 1.1 joerg /// We're evaluating the destruction of EvaluatingDecl. 834 1.1 joerg Dtor, 835 1.1 joerg }; 836 1.1 joerg EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None; 837 1.1 joerg 838 1.1 joerg /// EvaluatingDeclValue - This is the value being constructed for the 839 1.1 joerg /// declaration whose initializer is being evaluated, if any. 840 1.1 joerg APValue *EvaluatingDeclValue; 841 1.1 joerg 842 1.1 joerg /// Set of objects that are currently being constructed. 843 1.1 joerg llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase> 844 1.1 joerg ObjectsUnderConstruction; 845 1.1 joerg 846 1.1 joerg /// Current heap allocations, along with the location where each was 847 1.1 joerg /// allocated. We use std::map here because we need stable addresses 848 1.1 joerg /// for the stored APValues. 849 1.1 joerg std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs; 850 1.1 joerg 851 1.1 joerg /// The number of heap allocations performed so far in this evaluation. 852 1.1 joerg unsigned NumHeapAllocs = 0; 853 1.1 joerg 854 1.1 joerg struct EvaluatingConstructorRAII { 855 1.1 joerg EvalInfo &EI; 856 1.1 joerg ObjectUnderConstruction Object; 857 1.1 joerg bool DidInsert; 858 1.1 joerg EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object, 859 1.1 joerg bool HasBases) 860 1.1 joerg : EI(EI), Object(Object) { 861 1.1 joerg DidInsert = 862 1.1 joerg EI.ObjectsUnderConstruction 863 1.1 joerg .insert({Object, HasBases ? ConstructionPhase::Bases 864 1.1 joerg : ConstructionPhase::AfterBases}) 865 1.1 joerg .second; 866 1.1 joerg } 867 1.1 joerg void finishedConstructingBases() { 868 1.1 joerg EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases; 869 1.1 joerg } 870 1.1.1.2 joerg void finishedConstructingFields() { 871 1.1.1.2 joerg EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields; 872 1.1.1.2 joerg } 873 1.1 joerg ~EvaluatingConstructorRAII() { 874 1.1 joerg if (DidInsert) EI.ObjectsUnderConstruction.erase(Object); 875 1.1 joerg } 876 1.1 joerg }; 877 1.1 joerg 878 1.1 joerg struct EvaluatingDestructorRAII { 879 1.1 joerg EvalInfo &EI; 880 1.1 joerg ObjectUnderConstruction Object; 881 1.1 joerg bool DidInsert; 882 1.1 joerg EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object) 883 1.1 joerg : EI(EI), Object(Object) { 884 1.1 joerg DidInsert = EI.ObjectsUnderConstruction 885 1.1 joerg .insert({Object, ConstructionPhase::Destroying}) 886 1.1 joerg .second; 887 1.1 joerg } 888 1.1 joerg void startedDestroyingBases() { 889 1.1 joerg EI.ObjectsUnderConstruction[Object] = 890 1.1 joerg ConstructionPhase::DestroyingBases; 891 1.1 joerg } 892 1.1 joerg ~EvaluatingDestructorRAII() { 893 1.1 joerg if (DidInsert) 894 1.1 joerg EI.ObjectsUnderConstruction.erase(Object); 895 1.1 joerg } 896 1.1 joerg }; 897 1.1 joerg 898 1.1 joerg ConstructionPhase 899 1.1 joerg isEvaluatingCtorDtor(APValue::LValueBase Base, 900 1.1 joerg ArrayRef<APValue::LValuePathEntry> Path) { 901 1.1 joerg return ObjectsUnderConstruction.lookup({Base, Path}); 902 1.1 joerg } 903 1.1 joerg 904 1.1 joerg /// If we're currently speculatively evaluating, the outermost call stack 905 1.1 joerg /// depth at which we can mutate state, otherwise 0. 906 1.1 joerg unsigned SpeculativeEvaluationDepth = 0; 907 1.1 joerg 908 1.1 joerg /// The current array initialization index, if we're performing array 909 1.1 joerg /// initialization. 910 1.1 joerg uint64_t ArrayInitIndex = -1; 911 1.1 joerg 912 1.1 joerg /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further 913 1.1 joerg /// notes attached to it will also be stored, otherwise they will not be. 914 1.1 joerg bool HasActiveDiagnostic; 915 1.1 joerg 916 1.1 joerg /// Have we emitted a diagnostic explaining why we couldn't constant 917 1.1 joerg /// fold (not just why it's not strictly a constant expression)? 918 1.1 joerg bool HasFoldFailureDiagnostic; 919 1.1 joerg 920 1.1 joerg /// Whether or not we're in a context where the front end requires a 921 1.1 joerg /// constant value. 922 1.1 joerg bool InConstantContext; 923 1.1 joerg 924 1.1 joerg /// Whether we're checking that an expression is a potential constant 925 1.1 joerg /// expression. If so, do not fail on constructs that could become constant 926 1.1 joerg /// later on (such as a use of an undefined global). 927 1.1 joerg bool CheckingPotentialConstantExpression = false; 928 1.1 joerg 929 1.1 joerg /// Whether we're checking for an expression that has undefined behavior. 930 1.1 joerg /// If so, we will produce warnings if we encounter an operation that is 931 1.1 joerg /// always undefined. 932 1.1.1.2 joerg /// 933 1.1.1.2 joerg /// Note that we still need to evaluate the expression normally when this 934 1.1.1.2 joerg /// is set; this is used when evaluating ICEs in C. 935 1.1 joerg bool CheckingForUndefinedBehavior = false; 936 1.1 joerg 937 1.1 joerg enum EvaluationMode { 938 1.1 joerg /// Evaluate as a constant expression. Stop if we find that the expression 939 1.1 joerg /// is not a constant expression. 940 1.1 joerg EM_ConstantExpression, 941 1.1 joerg 942 1.1 joerg /// Evaluate as a constant expression. Stop if we find that the expression 943 1.1 joerg /// is not a constant expression. Some expressions can be retried in the 944 1.1 joerg /// optimizer if we don't constant fold them here, but in an unevaluated 945 1.1 joerg /// context we try to fold them immediately since the optimizer never 946 1.1 joerg /// gets a chance to look at it. 947 1.1 joerg EM_ConstantExpressionUnevaluated, 948 1.1 joerg 949 1.1 joerg /// Fold the expression to a constant. Stop if we hit a side-effect that 950 1.1 joerg /// we can't model. 951 1.1 joerg EM_ConstantFold, 952 1.1 joerg 953 1.1 joerg /// Evaluate in any way we know how. Don't worry about side-effects that 954 1.1 joerg /// can't be modeled. 955 1.1 joerg EM_IgnoreSideEffects, 956 1.1 joerg } EvalMode; 957 1.1 joerg 958 1.1 joerg /// Are we checking whether the expression is a potential constant 959 1.1 joerg /// expression? 960 1.1 joerg bool checkingPotentialConstantExpression() const override { 961 1.1 joerg return CheckingPotentialConstantExpression; 962 1.1 joerg } 963 1.1 joerg 964 1.1 joerg /// Are we checking an expression for overflow? 965 1.1 joerg // FIXME: We should check for any kind of undefined or suspicious behavior 966 1.1 joerg // in such constructs, not just overflow. 967 1.1 joerg bool checkingForUndefinedBehavior() const override { 968 1.1 joerg return CheckingForUndefinedBehavior; 969 1.1 joerg } 970 1.1 joerg 971 1.1 joerg EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode) 972 1.1 joerg : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr), 973 1.1 joerg CallStackDepth(0), NextCallIndex(1), 974 1.1.1.2 joerg StepsLeft(C.getLangOpts().ConstexprStepLimit), 975 1.1.1.2 joerg EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp), 976 1.1.1.2 joerg BottomFrame(*this, SourceLocation(), nullptr, nullptr, CallRef()), 977 1.1 joerg EvaluatingDecl((const ValueDecl *)nullptr), 978 1.1 joerg EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false), 979 1.1 joerg HasFoldFailureDiagnostic(false), InConstantContext(false), 980 1.1 joerg EvalMode(Mode) {} 981 1.1 joerg 982 1.1 joerg ~EvalInfo() { 983 1.1 joerg discardCleanups(); 984 1.1 joerg } 985 1.1 joerg 986 1.1 joerg void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value, 987 1.1 joerg EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) { 988 1.1 joerg EvaluatingDecl = Base; 989 1.1 joerg IsEvaluatingDecl = EDK; 990 1.1 joerg EvaluatingDeclValue = &Value; 991 1.1 joerg } 992 1.1 joerg 993 1.1 joerg bool CheckCallLimit(SourceLocation Loc) { 994 1.1 joerg // Don't perform any constexpr calls (other than the call we're checking) 995 1.1 joerg // when checking a potential constant expression. 996 1.1 joerg if (checkingPotentialConstantExpression() && CallStackDepth > 1) 997 1.1 joerg return false; 998 1.1 joerg if (NextCallIndex == 0) { 999 1.1 joerg // NextCallIndex has wrapped around. 1000 1.1 joerg FFDiag(Loc, diag::note_constexpr_call_limit_exceeded); 1001 1.1 joerg return false; 1002 1.1 joerg } 1003 1.1 joerg if (CallStackDepth <= getLangOpts().ConstexprCallDepth) 1004 1.1 joerg return true; 1005 1.1 joerg FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded) 1006 1.1 joerg << getLangOpts().ConstexprCallDepth; 1007 1.1 joerg return false; 1008 1.1 joerg } 1009 1.1 joerg 1010 1.1 joerg std::pair<CallStackFrame *, unsigned> 1011 1.1 joerg getCallFrameAndDepth(unsigned CallIndex) { 1012 1.1 joerg assert(CallIndex && "no call index in getCallFrameAndDepth"); 1013 1.1 joerg // We will eventually hit BottomFrame, which has Index 1, so Frame can't 1014 1.1 joerg // be null in this loop. 1015 1.1 joerg unsigned Depth = CallStackDepth; 1016 1.1 joerg CallStackFrame *Frame = CurrentCall; 1017 1.1 joerg while (Frame->Index > CallIndex) { 1018 1.1 joerg Frame = Frame->Caller; 1019 1.1 joerg --Depth; 1020 1.1 joerg } 1021 1.1 joerg if (Frame->Index == CallIndex) 1022 1.1 joerg return {Frame, Depth}; 1023 1.1 joerg return {nullptr, 0}; 1024 1.1 joerg } 1025 1.1 joerg 1026 1.1 joerg bool nextStep(const Stmt *S) { 1027 1.1 joerg if (!StepsLeft) { 1028 1.1 joerg FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded); 1029 1.1 joerg return false; 1030 1.1 joerg } 1031 1.1 joerg --StepsLeft; 1032 1.1 joerg return true; 1033 1.1 joerg } 1034 1.1 joerg 1035 1.1 joerg APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV); 1036 1.1 joerg 1037 1.1 joerg Optional<DynAlloc*> lookupDynamicAlloc(DynamicAllocLValue DA) { 1038 1.1 joerg Optional<DynAlloc*> Result; 1039 1.1 joerg auto It = HeapAllocs.find(DA); 1040 1.1 joerg if (It != HeapAllocs.end()) 1041 1.1 joerg Result = &It->second; 1042 1.1 joerg return Result; 1043 1.1 joerg } 1044 1.1 joerg 1045 1.1.1.2 joerg /// Get the allocated storage for the given parameter of the given call. 1046 1.1.1.2 joerg APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) { 1047 1.1.1.2 joerg CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first; 1048 1.1.1.2 joerg return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version) 1049 1.1.1.2 joerg : nullptr; 1050 1.1.1.2 joerg } 1051 1.1.1.2 joerg 1052 1.1 joerg /// Information about a stack frame for std::allocator<T>::[de]allocate. 1053 1.1 joerg struct StdAllocatorCaller { 1054 1.1 joerg unsigned FrameIndex; 1055 1.1 joerg QualType ElemType; 1056 1.1 joerg explicit operator bool() const { return FrameIndex != 0; }; 1057 1.1 joerg }; 1058 1.1 joerg 1059 1.1 joerg StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const { 1060 1.1 joerg for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame; 1061 1.1 joerg Call = Call->Caller) { 1062 1.1 joerg const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee); 1063 1.1 joerg if (!MD) 1064 1.1 joerg continue; 1065 1.1 joerg const IdentifierInfo *FnII = MD->getIdentifier(); 1066 1.1 joerg if (!FnII || !FnII->isStr(FnName)) 1067 1.1 joerg continue; 1068 1.1 joerg 1069 1.1 joerg const auto *CTSD = 1070 1.1 joerg dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent()); 1071 1.1 joerg if (!CTSD) 1072 1.1 joerg continue; 1073 1.1 joerg 1074 1.1 joerg const IdentifierInfo *ClassII = CTSD->getIdentifier(); 1075 1.1 joerg const TemplateArgumentList &TAL = CTSD->getTemplateArgs(); 1076 1.1 joerg if (CTSD->isInStdNamespace() && ClassII && 1077 1.1 joerg ClassII->isStr("allocator") && TAL.size() >= 1 && 1078 1.1 joerg TAL[0].getKind() == TemplateArgument::Type) 1079 1.1 joerg return {Call->Index, TAL[0].getAsType()}; 1080 1.1 joerg } 1081 1.1 joerg 1082 1.1 joerg return {}; 1083 1.1 joerg } 1084 1.1 joerg 1085 1.1 joerg void performLifetimeExtension() { 1086 1.1 joerg // Disable the cleanups for lifetime-extended temporaries. 1087 1.1.1.2 joerg CleanupStack.erase(std::remove_if(CleanupStack.begin(), 1088 1.1.1.2 joerg CleanupStack.end(), 1089 1.1.1.2 joerg [](Cleanup &C) { 1090 1.1.1.2 joerg return !C.isDestroyedAtEndOf( 1091 1.1.1.2 joerg ScopeKind::FullExpression); 1092 1.1.1.2 joerg }), 1093 1.1.1.2 joerg CleanupStack.end()); 1094 1.1 joerg } 1095 1.1 joerg 1096 1.1 joerg /// Throw away any remaining cleanups at the end of evaluation. If any 1097 1.1 joerg /// cleanups would have had a side-effect, note that as an unmodeled 1098 1.1 joerg /// side-effect and return false. Otherwise, return true. 1099 1.1 joerg bool discardCleanups() { 1100 1.1.1.2 joerg for (Cleanup &C : CleanupStack) { 1101 1.1.1.2 joerg if (C.hasSideEffect() && !noteSideEffect()) { 1102 1.1.1.2 joerg CleanupStack.clear(); 1103 1.1.1.2 joerg return false; 1104 1.1.1.2 joerg } 1105 1.1.1.2 joerg } 1106 1.1.1.2 joerg CleanupStack.clear(); 1107 1.1 joerg return true; 1108 1.1 joerg } 1109 1.1 joerg 1110 1.1 joerg private: 1111 1.1 joerg interp::Frame *getCurrentFrame() override { return CurrentCall; } 1112 1.1 joerg const interp::Frame *getBottomFrame() const override { return &BottomFrame; } 1113 1.1 joerg 1114 1.1 joerg bool hasActiveDiagnostic() override { return HasActiveDiagnostic; } 1115 1.1 joerg void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; } 1116 1.1 joerg 1117 1.1 joerg void setFoldFailureDiagnostic(bool Flag) override { 1118 1.1 joerg HasFoldFailureDiagnostic = Flag; 1119 1.1 joerg } 1120 1.1 joerg 1121 1.1 joerg Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; } 1122 1.1 joerg 1123 1.1 joerg ASTContext &getCtx() const override { return Ctx; } 1124 1.1 joerg 1125 1.1 joerg // If we have a prior diagnostic, it will be noting that the expression 1126 1.1 joerg // isn't a constant expression. This diagnostic is more important, 1127 1.1 joerg // unless we require this evaluation to produce a constant expression. 1128 1.1 joerg // 1129 1.1 joerg // FIXME: We might want to show both diagnostics to the user in 1130 1.1 joerg // EM_ConstantFold mode. 1131 1.1 joerg bool hasPriorDiagnostic() override { 1132 1.1 joerg if (!EvalStatus.Diag->empty()) { 1133 1.1 joerg switch (EvalMode) { 1134 1.1 joerg case EM_ConstantFold: 1135 1.1 joerg case EM_IgnoreSideEffects: 1136 1.1 joerg if (!HasFoldFailureDiagnostic) 1137 1.1 joerg break; 1138 1.1 joerg // We've already failed to fold something. Keep that diagnostic. 1139 1.1 joerg LLVM_FALLTHROUGH; 1140 1.1 joerg case EM_ConstantExpression: 1141 1.1 joerg case EM_ConstantExpressionUnevaluated: 1142 1.1 joerg setActiveDiagnostic(false); 1143 1.1 joerg return true; 1144 1.1 joerg } 1145 1.1 joerg } 1146 1.1 joerg return false; 1147 1.1 joerg } 1148 1.1 joerg 1149 1.1 joerg unsigned getCallStackDepth() override { return CallStackDepth; } 1150 1.1 joerg 1151 1.1 joerg public: 1152 1.1 joerg /// Should we continue evaluation after encountering a side-effect that we 1153 1.1 joerg /// couldn't model? 1154 1.1 joerg bool keepEvaluatingAfterSideEffect() { 1155 1.1 joerg switch (EvalMode) { 1156 1.1 joerg case EM_IgnoreSideEffects: 1157 1.1 joerg return true; 1158 1.1 joerg 1159 1.1 joerg case EM_ConstantExpression: 1160 1.1 joerg case EM_ConstantExpressionUnevaluated: 1161 1.1 joerg case EM_ConstantFold: 1162 1.1 joerg // By default, assume any side effect might be valid in some other 1163 1.1 joerg // evaluation of this expression from a different context. 1164 1.1 joerg return checkingPotentialConstantExpression() || 1165 1.1 joerg checkingForUndefinedBehavior(); 1166 1.1 joerg } 1167 1.1 joerg llvm_unreachable("Missed EvalMode case"); 1168 1.1 joerg } 1169 1.1 joerg 1170 1.1 joerg /// Note that we have had a side-effect, and determine whether we should 1171 1.1 joerg /// keep evaluating. 1172 1.1 joerg bool noteSideEffect() { 1173 1.1 joerg EvalStatus.HasSideEffects = true; 1174 1.1 joerg return keepEvaluatingAfterSideEffect(); 1175 1.1 joerg } 1176 1.1 joerg 1177 1.1 joerg /// Should we continue evaluation after encountering undefined behavior? 1178 1.1 joerg bool keepEvaluatingAfterUndefinedBehavior() { 1179 1.1 joerg switch (EvalMode) { 1180 1.1 joerg case EM_IgnoreSideEffects: 1181 1.1 joerg case EM_ConstantFold: 1182 1.1 joerg return true; 1183 1.1 joerg 1184 1.1 joerg case EM_ConstantExpression: 1185 1.1 joerg case EM_ConstantExpressionUnevaluated: 1186 1.1 joerg return checkingForUndefinedBehavior(); 1187 1.1 joerg } 1188 1.1 joerg llvm_unreachable("Missed EvalMode case"); 1189 1.1 joerg } 1190 1.1 joerg 1191 1.1 joerg /// Note that we hit something that was technically undefined behavior, but 1192 1.1 joerg /// that we can evaluate past it (such as signed overflow or floating-point 1193 1.1 joerg /// division by zero.) 1194 1.1 joerg bool noteUndefinedBehavior() override { 1195 1.1 joerg EvalStatus.HasUndefinedBehavior = true; 1196 1.1 joerg return keepEvaluatingAfterUndefinedBehavior(); 1197 1.1 joerg } 1198 1.1 joerg 1199 1.1 joerg /// Should we continue evaluation as much as possible after encountering a 1200 1.1 joerg /// construct which can't be reduced to a value? 1201 1.1 joerg bool keepEvaluatingAfterFailure() const override { 1202 1.1 joerg if (!StepsLeft) 1203 1.1 joerg return false; 1204 1.1 joerg 1205 1.1 joerg switch (EvalMode) { 1206 1.1 joerg case EM_ConstantExpression: 1207 1.1 joerg case EM_ConstantExpressionUnevaluated: 1208 1.1 joerg case EM_ConstantFold: 1209 1.1 joerg case EM_IgnoreSideEffects: 1210 1.1 joerg return checkingPotentialConstantExpression() || 1211 1.1 joerg checkingForUndefinedBehavior(); 1212 1.1 joerg } 1213 1.1 joerg llvm_unreachable("Missed EvalMode case"); 1214 1.1 joerg } 1215 1.1 joerg 1216 1.1 joerg /// Notes that we failed to evaluate an expression that other expressions 1217 1.1 joerg /// directly depend on, and determine if we should keep evaluating. This 1218 1.1 joerg /// should only be called if we actually intend to keep evaluating. 1219 1.1 joerg /// 1220 1.1 joerg /// Call noteSideEffect() instead if we may be able to ignore the value that 1221 1.1 joerg /// we failed to evaluate, e.g. if we failed to evaluate Foo() in: 1222 1.1 joerg /// 1223 1.1 joerg /// (Foo(), 1) // use noteSideEffect 1224 1.1 joerg /// (Foo() || true) // use noteSideEffect 1225 1.1 joerg /// Foo() + 1 // use noteFailure 1226 1.1 joerg LLVM_NODISCARD bool noteFailure() { 1227 1.1 joerg // Failure when evaluating some expression often means there is some 1228 1.1 joerg // subexpression whose evaluation was skipped. Therefore, (because we 1229 1.1 joerg // don't track whether we skipped an expression when unwinding after an 1230 1.1 joerg // evaluation failure) every evaluation failure that bubbles up from a 1231 1.1 joerg // subexpression implies that a side-effect has potentially happened. We 1232 1.1 joerg // skip setting the HasSideEffects flag to true until we decide to 1233 1.1 joerg // continue evaluating after that point, which happens here. 1234 1.1 joerg bool KeepGoing = keepEvaluatingAfterFailure(); 1235 1.1 joerg EvalStatus.HasSideEffects |= KeepGoing; 1236 1.1 joerg return KeepGoing; 1237 1.1 joerg } 1238 1.1 joerg 1239 1.1 joerg class ArrayInitLoopIndex { 1240 1.1 joerg EvalInfo &Info; 1241 1.1 joerg uint64_t OuterIndex; 1242 1.1 joerg 1243 1.1 joerg public: 1244 1.1 joerg ArrayInitLoopIndex(EvalInfo &Info) 1245 1.1 joerg : Info(Info), OuterIndex(Info.ArrayInitIndex) { 1246 1.1 joerg Info.ArrayInitIndex = 0; 1247 1.1 joerg } 1248 1.1 joerg ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; } 1249 1.1 joerg 1250 1.1 joerg operator uint64_t&() { return Info.ArrayInitIndex; } 1251 1.1 joerg }; 1252 1.1 joerg }; 1253 1.1 joerg 1254 1.1 joerg /// Object used to treat all foldable expressions as constant expressions. 1255 1.1 joerg struct FoldConstant { 1256 1.1 joerg EvalInfo &Info; 1257 1.1 joerg bool Enabled; 1258 1.1 joerg bool HadNoPriorDiags; 1259 1.1 joerg EvalInfo::EvaluationMode OldMode; 1260 1.1 joerg 1261 1.1 joerg explicit FoldConstant(EvalInfo &Info, bool Enabled) 1262 1.1 joerg : Info(Info), 1263 1.1 joerg Enabled(Enabled), 1264 1.1 joerg HadNoPriorDiags(Info.EvalStatus.Diag && 1265 1.1 joerg Info.EvalStatus.Diag->empty() && 1266 1.1 joerg !Info.EvalStatus.HasSideEffects), 1267 1.1 joerg OldMode(Info.EvalMode) { 1268 1.1 joerg if (Enabled) 1269 1.1 joerg Info.EvalMode = EvalInfo::EM_ConstantFold; 1270 1.1 joerg } 1271 1.1 joerg void keepDiagnostics() { Enabled = false; } 1272 1.1 joerg ~FoldConstant() { 1273 1.1 joerg if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() && 1274 1.1 joerg !Info.EvalStatus.HasSideEffects) 1275 1.1 joerg Info.EvalStatus.Diag->clear(); 1276 1.1 joerg Info.EvalMode = OldMode; 1277 1.1 joerg } 1278 1.1 joerg }; 1279 1.1 joerg 1280 1.1 joerg /// RAII object used to set the current evaluation mode to ignore 1281 1.1 joerg /// side-effects. 1282 1.1 joerg struct IgnoreSideEffectsRAII { 1283 1.1 joerg EvalInfo &Info; 1284 1.1 joerg EvalInfo::EvaluationMode OldMode; 1285 1.1 joerg explicit IgnoreSideEffectsRAII(EvalInfo &Info) 1286 1.1 joerg : Info(Info), OldMode(Info.EvalMode) { 1287 1.1 joerg Info.EvalMode = EvalInfo::EM_IgnoreSideEffects; 1288 1.1 joerg } 1289 1.1 joerg 1290 1.1 joerg ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; } 1291 1.1 joerg }; 1292 1.1 joerg 1293 1.1 joerg /// RAII object used to optionally suppress diagnostics and side-effects from 1294 1.1 joerg /// a speculative evaluation. 1295 1.1 joerg class SpeculativeEvaluationRAII { 1296 1.1 joerg EvalInfo *Info = nullptr; 1297 1.1 joerg Expr::EvalStatus OldStatus; 1298 1.1 joerg unsigned OldSpeculativeEvaluationDepth; 1299 1.1 joerg 1300 1.1 joerg void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) { 1301 1.1 joerg Info = Other.Info; 1302 1.1 joerg OldStatus = Other.OldStatus; 1303 1.1 joerg OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth; 1304 1.1 joerg Other.Info = nullptr; 1305 1.1 joerg } 1306 1.1 joerg 1307 1.1 joerg void maybeRestoreState() { 1308 1.1 joerg if (!Info) 1309 1.1 joerg return; 1310 1.1 joerg 1311 1.1 joerg Info->EvalStatus = OldStatus; 1312 1.1 joerg Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth; 1313 1.1 joerg } 1314 1.1 joerg 1315 1.1 joerg public: 1316 1.1 joerg SpeculativeEvaluationRAII() = default; 1317 1.1 joerg 1318 1.1 joerg SpeculativeEvaluationRAII( 1319 1.1 joerg EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr) 1320 1.1 joerg : Info(&Info), OldStatus(Info.EvalStatus), 1321 1.1 joerg OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) { 1322 1.1 joerg Info.EvalStatus.Diag = NewDiag; 1323 1.1 joerg Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1; 1324 1.1 joerg } 1325 1.1 joerg 1326 1.1 joerg SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete; 1327 1.1 joerg SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) { 1328 1.1 joerg moveFromAndCancel(std::move(Other)); 1329 1.1 joerg } 1330 1.1 joerg 1331 1.1 joerg SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) { 1332 1.1 joerg maybeRestoreState(); 1333 1.1 joerg moveFromAndCancel(std::move(Other)); 1334 1.1 joerg return *this; 1335 1.1 joerg } 1336 1.1 joerg 1337 1.1 joerg ~SpeculativeEvaluationRAII() { maybeRestoreState(); } 1338 1.1 joerg }; 1339 1.1 joerg 1340 1.1 joerg /// RAII object wrapping a full-expression or block scope, and handling 1341 1.1 joerg /// the ending of the lifetime of temporaries created within it. 1342 1.1.1.2 joerg template<ScopeKind Kind> 1343 1.1 joerg class ScopeRAII { 1344 1.1 joerg EvalInfo &Info; 1345 1.1 joerg unsigned OldStackSize; 1346 1.1 joerg public: 1347 1.1 joerg ScopeRAII(EvalInfo &Info) 1348 1.1 joerg : Info(Info), OldStackSize(Info.CleanupStack.size()) { 1349 1.1 joerg // Push a new temporary version. This is needed to distinguish between 1350 1.1 joerg // temporaries created in different iterations of a loop. 1351 1.1 joerg Info.CurrentCall->pushTempVersion(); 1352 1.1 joerg } 1353 1.1 joerg bool destroy(bool RunDestructors = true) { 1354 1.1 joerg bool OK = cleanup(Info, RunDestructors, OldStackSize); 1355 1.1 joerg OldStackSize = -1U; 1356 1.1 joerg return OK; 1357 1.1 joerg } 1358 1.1 joerg ~ScopeRAII() { 1359 1.1 joerg if (OldStackSize != -1U) 1360 1.1 joerg destroy(false); 1361 1.1 joerg // Body moved to a static method to encourage the compiler to inline away 1362 1.1 joerg // instances of this class. 1363 1.1 joerg Info.CurrentCall->popTempVersion(); 1364 1.1 joerg } 1365 1.1 joerg private: 1366 1.1 joerg static bool cleanup(EvalInfo &Info, bool RunDestructors, 1367 1.1 joerg unsigned OldStackSize) { 1368 1.1 joerg assert(OldStackSize <= Info.CleanupStack.size() && 1369 1.1 joerg "running cleanups out of order?"); 1370 1.1 joerg 1371 1.1 joerg // Run all cleanups for a block scope, and non-lifetime-extended cleanups 1372 1.1 joerg // for a full-expression scope. 1373 1.1 joerg bool Success = true; 1374 1.1 joerg for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) { 1375 1.1.1.2 joerg if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) { 1376 1.1 joerg if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) { 1377 1.1 joerg Success = false; 1378 1.1 joerg break; 1379 1.1 joerg } 1380 1.1 joerg } 1381 1.1 joerg } 1382 1.1 joerg 1383 1.1.1.2 joerg // Compact any retained cleanups. 1384 1.1 joerg auto NewEnd = Info.CleanupStack.begin() + OldStackSize; 1385 1.1.1.2 joerg if (Kind != ScopeKind::Block) 1386 1.1 joerg NewEnd = 1387 1.1.1.2 joerg std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) { 1388 1.1.1.2 joerg return C.isDestroyedAtEndOf(Kind); 1389 1.1.1.2 joerg }); 1390 1.1 joerg Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end()); 1391 1.1 joerg return Success; 1392 1.1 joerg } 1393 1.1 joerg }; 1394 1.1.1.2 joerg typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII; 1395 1.1.1.2 joerg typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII; 1396 1.1.1.2 joerg typedef ScopeRAII<ScopeKind::Call> CallScopeRAII; 1397 1.1 joerg } 1398 1.1 joerg 1399 1.1 joerg bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E, 1400 1.1 joerg CheckSubobjectKind CSK) { 1401 1.1 joerg if (Invalid) 1402 1.1 joerg return false; 1403 1.1 joerg if (isOnePastTheEnd()) { 1404 1.1 joerg Info.CCEDiag(E, diag::note_constexpr_past_end_subobject) 1405 1.1 joerg << CSK; 1406 1.1 joerg setInvalid(); 1407 1.1 joerg return false; 1408 1.1 joerg } 1409 1.1 joerg // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there 1410 1.1 joerg // must actually be at least one array element; even a VLA cannot have a 1411 1.1 joerg // bound of zero. And if our index is nonzero, we already had a CCEDiag. 1412 1.1 joerg return true; 1413 1.1 joerg } 1414 1.1 joerg 1415 1.1 joerg void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, 1416 1.1 joerg const Expr *E) { 1417 1.1 joerg Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed); 1418 1.1 joerg // Do not set the designator as invalid: we can represent this situation, 1419 1.1 joerg // and correct handling of __builtin_object_size requires us to do so. 1420 1.1 joerg } 1421 1.1 joerg 1422 1.1 joerg void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info, 1423 1.1 joerg const Expr *E, 1424 1.1 joerg const APSInt &N) { 1425 1.1 joerg // If we're complaining, we must be able to statically determine the size of 1426 1.1 joerg // the most derived array. 1427 1.1 joerg if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement) 1428 1.1 joerg Info.CCEDiag(E, diag::note_constexpr_array_index) 1429 1.1 joerg << N << /*array*/ 0 1430 1.1 joerg << static_cast<unsigned>(getMostDerivedArraySize()); 1431 1.1 joerg else 1432 1.1 joerg Info.CCEDiag(E, diag::note_constexpr_array_index) 1433 1.1 joerg << N << /*non-array*/ 1; 1434 1.1 joerg setInvalid(); 1435 1.1 joerg } 1436 1.1 joerg 1437 1.1 joerg CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, 1438 1.1 joerg const FunctionDecl *Callee, const LValue *This, 1439 1.1.1.2 joerg CallRef Call) 1440 1.1 joerg : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This), 1441 1.1.1.2 joerg Arguments(Call), CallLoc(CallLoc), Index(Info.NextCallIndex++) { 1442 1.1 joerg Info.CurrentCall = this; 1443 1.1 joerg ++Info.CallStackDepth; 1444 1.1 joerg } 1445 1.1 joerg 1446 1.1 joerg CallStackFrame::~CallStackFrame() { 1447 1.1 joerg assert(Info.CurrentCall == this && "calls retired out of order"); 1448 1.1 joerg --Info.CallStackDepth; 1449 1.1 joerg Info.CurrentCall = Caller; 1450 1.1 joerg } 1451 1.1 joerg 1452 1.1 joerg static bool isRead(AccessKinds AK) { 1453 1.1 joerg return AK == AK_Read || AK == AK_ReadObjectRepresentation; 1454 1.1 joerg } 1455 1.1 joerg 1456 1.1 joerg static bool isModification(AccessKinds AK) { 1457 1.1 joerg switch (AK) { 1458 1.1 joerg case AK_Read: 1459 1.1 joerg case AK_ReadObjectRepresentation: 1460 1.1 joerg case AK_MemberCall: 1461 1.1 joerg case AK_DynamicCast: 1462 1.1 joerg case AK_TypeId: 1463 1.1 joerg return false; 1464 1.1 joerg case AK_Assign: 1465 1.1 joerg case AK_Increment: 1466 1.1 joerg case AK_Decrement: 1467 1.1 joerg case AK_Construct: 1468 1.1 joerg case AK_Destroy: 1469 1.1 joerg return true; 1470 1.1 joerg } 1471 1.1 joerg llvm_unreachable("unknown access kind"); 1472 1.1 joerg } 1473 1.1 joerg 1474 1.1 joerg static bool isAnyAccess(AccessKinds AK) { 1475 1.1 joerg return isRead(AK) || isModification(AK); 1476 1.1 joerg } 1477 1.1 joerg 1478 1.1 joerg /// Is this an access per the C++ definition? 1479 1.1 joerg static bool isFormalAccess(AccessKinds AK) { 1480 1.1 joerg return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy; 1481 1.1 joerg } 1482 1.1 joerg 1483 1.1.1.2 joerg /// Is this kind of axcess valid on an indeterminate object value? 1484 1.1.1.2 joerg static bool isValidIndeterminateAccess(AccessKinds AK) { 1485 1.1.1.2 joerg switch (AK) { 1486 1.1.1.2 joerg case AK_Read: 1487 1.1.1.2 joerg case AK_Increment: 1488 1.1.1.2 joerg case AK_Decrement: 1489 1.1.1.2 joerg // These need the object's value. 1490 1.1.1.2 joerg return false; 1491 1.1.1.2 joerg 1492 1.1.1.2 joerg case AK_ReadObjectRepresentation: 1493 1.1.1.2 joerg case AK_Assign: 1494 1.1.1.2 joerg case AK_Construct: 1495 1.1.1.2 joerg case AK_Destroy: 1496 1.1.1.2 joerg // Construction and destruction don't need the value. 1497 1.1.1.2 joerg return true; 1498 1.1.1.2 joerg 1499 1.1.1.2 joerg case AK_MemberCall: 1500 1.1.1.2 joerg case AK_DynamicCast: 1501 1.1.1.2 joerg case AK_TypeId: 1502 1.1.1.2 joerg // These aren't really meaningful on scalars. 1503 1.1.1.2 joerg return true; 1504 1.1.1.2 joerg } 1505 1.1.1.2 joerg llvm_unreachable("unknown access kind"); 1506 1.1.1.2 joerg } 1507 1.1.1.2 joerg 1508 1.1 joerg namespace { 1509 1.1 joerg struct ComplexValue { 1510 1.1 joerg private: 1511 1.1 joerg bool IsInt; 1512 1.1 joerg 1513 1.1 joerg public: 1514 1.1 joerg APSInt IntReal, IntImag; 1515 1.1 joerg APFloat FloatReal, FloatImag; 1516 1.1 joerg 1517 1.1 joerg ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {} 1518 1.1 joerg 1519 1.1 joerg void makeComplexFloat() { IsInt = false; } 1520 1.1 joerg bool isComplexFloat() const { return !IsInt; } 1521 1.1 joerg APFloat &getComplexFloatReal() { return FloatReal; } 1522 1.1 joerg APFloat &getComplexFloatImag() { return FloatImag; } 1523 1.1 joerg 1524 1.1 joerg void makeComplexInt() { IsInt = true; } 1525 1.1 joerg bool isComplexInt() const { return IsInt; } 1526 1.1 joerg APSInt &getComplexIntReal() { return IntReal; } 1527 1.1 joerg APSInt &getComplexIntImag() { return IntImag; } 1528 1.1 joerg 1529 1.1 joerg void moveInto(APValue &v) const { 1530 1.1 joerg if (isComplexFloat()) 1531 1.1 joerg v = APValue(FloatReal, FloatImag); 1532 1.1 joerg else 1533 1.1 joerg v = APValue(IntReal, IntImag); 1534 1.1 joerg } 1535 1.1 joerg void setFrom(const APValue &v) { 1536 1.1 joerg assert(v.isComplexFloat() || v.isComplexInt()); 1537 1.1 joerg if (v.isComplexFloat()) { 1538 1.1 joerg makeComplexFloat(); 1539 1.1 joerg FloatReal = v.getComplexFloatReal(); 1540 1.1 joerg FloatImag = v.getComplexFloatImag(); 1541 1.1 joerg } else { 1542 1.1 joerg makeComplexInt(); 1543 1.1 joerg IntReal = v.getComplexIntReal(); 1544 1.1 joerg IntImag = v.getComplexIntImag(); 1545 1.1 joerg } 1546 1.1 joerg } 1547 1.1 joerg }; 1548 1.1 joerg 1549 1.1 joerg struct LValue { 1550 1.1 joerg APValue::LValueBase Base; 1551 1.1 joerg CharUnits Offset; 1552 1.1 joerg SubobjectDesignator Designator; 1553 1.1 joerg bool IsNullPtr : 1; 1554 1.1 joerg bool InvalidBase : 1; 1555 1.1 joerg 1556 1.1 joerg const APValue::LValueBase getLValueBase() const { return Base; } 1557 1.1 joerg CharUnits &getLValueOffset() { return Offset; } 1558 1.1 joerg const CharUnits &getLValueOffset() const { return Offset; } 1559 1.1 joerg SubobjectDesignator &getLValueDesignator() { return Designator; } 1560 1.1 joerg const SubobjectDesignator &getLValueDesignator() const { return Designator;} 1561 1.1 joerg bool isNullPointer() const { return IsNullPtr;} 1562 1.1 joerg 1563 1.1 joerg unsigned getLValueCallIndex() const { return Base.getCallIndex(); } 1564 1.1 joerg unsigned getLValueVersion() const { return Base.getVersion(); } 1565 1.1 joerg 1566 1.1 joerg void moveInto(APValue &V) const { 1567 1.1 joerg if (Designator.Invalid) 1568 1.1 joerg V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr); 1569 1.1 joerg else { 1570 1.1 joerg assert(!InvalidBase && "APValues can't handle invalid LValue bases"); 1571 1.1 joerg V = APValue(Base, Offset, Designator.Entries, 1572 1.1 joerg Designator.IsOnePastTheEnd, IsNullPtr); 1573 1.1 joerg } 1574 1.1 joerg } 1575 1.1 joerg void setFrom(ASTContext &Ctx, const APValue &V) { 1576 1.1 joerg assert(V.isLValue() && "Setting LValue from a non-LValue?"); 1577 1.1 joerg Base = V.getLValueBase(); 1578 1.1 joerg Offset = V.getLValueOffset(); 1579 1.1 joerg InvalidBase = false; 1580 1.1 joerg Designator = SubobjectDesignator(Ctx, V); 1581 1.1 joerg IsNullPtr = V.isNullPointer(); 1582 1.1 joerg } 1583 1.1 joerg 1584 1.1 joerg void set(APValue::LValueBase B, bool BInvalid = false) { 1585 1.1 joerg #ifndef NDEBUG 1586 1.1 joerg // We only allow a few types of invalid bases. Enforce that here. 1587 1.1 joerg if (BInvalid) { 1588 1.1 joerg const auto *E = B.get<const Expr *>(); 1589 1.1 joerg assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) && 1590 1.1 joerg "Unexpected type of invalid base"); 1591 1.1 joerg } 1592 1.1 joerg #endif 1593 1.1 joerg 1594 1.1 joerg Base = B; 1595 1.1 joerg Offset = CharUnits::fromQuantity(0); 1596 1.1 joerg InvalidBase = BInvalid; 1597 1.1 joerg Designator = SubobjectDesignator(getType(B)); 1598 1.1 joerg IsNullPtr = false; 1599 1.1 joerg } 1600 1.1 joerg 1601 1.1 joerg void setNull(ASTContext &Ctx, QualType PointerTy) { 1602 1.1.1.2 joerg Base = (const ValueDecl *)nullptr; 1603 1.1 joerg Offset = 1604 1.1 joerg CharUnits::fromQuantity(Ctx.getTargetNullPointerValue(PointerTy)); 1605 1.1 joerg InvalidBase = false; 1606 1.1 joerg Designator = SubobjectDesignator(PointerTy->getPointeeType()); 1607 1.1 joerg IsNullPtr = true; 1608 1.1 joerg } 1609 1.1 joerg 1610 1.1 joerg void setInvalid(APValue::LValueBase B, unsigned I = 0) { 1611 1.1 joerg set(B, true); 1612 1.1 joerg } 1613 1.1 joerg 1614 1.1 joerg std::string toString(ASTContext &Ctx, QualType T) const { 1615 1.1 joerg APValue Printable; 1616 1.1 joerg moveInto(Printable); 1617 1.1 joerg return Printable.getAsString(Ctx, T); 1618 1.1 joerg } 1619 1.1 joerg 1620 1.1 joerg private: 1621 1.1 joerg // Check that this LValue is not based on a null pointer. If it is, produce 1622 1.1 joerg // a diagnostic and mark the designator as invalid. 1623 1.1 joerg template <typename GenDiagType> 1624 1.1 joerg bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) { 1625 1.1 joerg if (Designator.Invalid) 1626 1.1 joerg return false; 1627 1.1 joerg if (IsNullPtr) { 1628 1.1 joerg GenDiag(); 1629 1.1 joerg Designator.setInvalid(); 1630 1.1 joerg return false; 1631 1.1 joerg } 1632 1.1 joerg return true; 1633 1.1 joerg } 1634 1.1 joerg 1635 1.1 joerg public: 1636 1.1 joerg bool checkNullPointer(EvalInfo &Info, const Expr *E, 1637 1.1 joerg CheckSubobjectKind CSK) { 1638 1.1 joerg return checkNullPointerDiagnosingWith([&Info, E, CSK] { 1639 1.1 joerg Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK; 1640 1.1 joerg }); 1641 1.1 joerg } 1642 1.1 joerg 1643 1.1 joerg bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E, 1644 1.1 joerg AccessKinds AK) { 1645 1.1 joerg return checkNullPointerDiagnosingWith([&Info, E, AK] { 1646 1.1 joerg Info.FFDiag(E, diag::note_constexpr_access_null) << AK; 1647 1.1 joerg }); 1648 1.1 joerg } 1649 1.1 joerg 1650 1.1 joerg // Check this LValue refers to an object. If not, set the designator to be 1651 1.1 joerg // invalid and emit a diagnostic. 1652 1.1 joerg bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) { 1653 1.1 joerg return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) && 1654 1.1 joerg Designator.checkSubobject(Info, E, CSK); 1655 1.1 joerg } 1656 1.1 joerg 1657 1.1 joerg void addDecl(EvalInfo &Info, const Expr *E, 1658 1.1 joerg const Decl *D, bool Virtual = false) { 1659 1.1 joerg if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base)) 1660 1.1 joerg Designator.addDeclUnchecked(D, Virtual); 1661 1.1 joerg } 1662 1.1 joerg void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) { 1663 1.1 joerg if (!Designator.Entries.empty()) { 1664 1.1 joerg Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array); 1665 1.1 joerg Designator.setInvalid(); 1666 1.1 joerg return; 1667 1.1 joerg } 1668 1.1 joerg if (checkSubobject(Info, E, CSK_ArrayToPointer)) { 1669 1.1 joerg assert(getType(Base)->isPointerType() || getType(Base)->isArrayType()); 1670 1.1 joerg Designator.FirstEntryIsAnUnsizedArray = true; 1671 1.1 joerg Designator.addUnsizedArrayUnchecked(ElemTy); 1672 1.1 joerg } 1673 1.1 joerg } 1674 1.1 joerg void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) { 1675 1.1 joerg if (checkSubobject(Info, E, CSK_ArrayToPointer)) 1676 1.1 joerg Designator.addArrayUnchecked(CAT); 1677 1.1 joerg } 1678 1.1 joerg void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) { 1679 1.1 joerg if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real)) 1680 1.1 joerg Designator.addComplexUnchecked(EltTy, Imag); 1681 1.1 joerg } 1682 1.1 joerg void clearIsNullPointer() { 1683 1.1 joerg IsNullPtr = false; 1684 1.1 joerg } 1685 1.1 joerg void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E, 1686 1.1 joerg const APSInt &Index, CharUnits ElementSize) { 1687 1.1 joerg // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB, 1688 1.1 joerg // but we're not required to diagnose it and it's valid in C++.) 1689 1.1 joerg if (!Index) 1690 1.1 joerg return; 1691 1.1 joerg 1692 1.1 joerg // Compute the new offset in the appropriate width, wrapping at 64 bits. 1693 1.1 joerg // FIXME: When compiling for a 32-bit target, we should use 32-bit 1694 1.1 joerg // offsets. 1695 1.1 joerg uint64_t Offset64 = Offset.getQuantity(); 1696 1.1 joerg uint64_t ElemSize64 = ElementSize.getQuantity(); 1697 1.1 joerg uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); 1698 1.1 joerg Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64); 1699 1.1 joerg 1700 1.1 joerg if (checkNullPointer(Info, E, CSK_ArrayIndex)) 1701 1.1 joerg Designator.adjustIndex(Info, E, Index); 1702 1.1 joerg clearIsNullPointer(); 1703 1.1 joerg } 1704 1.1 joerg void adjustOffset(CharUnits N) { 1705 1.1 joerg Offset += N; 1706 1.1 joerg if (N.getQuantity()) 1707 1.1 joerg clearIsNullPointer(); 1708 1.1 joerg } 1709 1.1 joerg }; 1710 1.1 joerg 1711 1.1 joerg struct MemberPtr { 1712 1.1 joerg MemberPtr() {} 1713 1.1 joerg explicit MemberPtr(const ValueDecl *Decl) : 1714 1.1 joerg DeclAndIsDerivedMember(Decl, false), Path() {} 1715 1.1 joerg 1716 1.1 joerg /// The member or (direct or indirect) field referred to by this member 1717 1.1 joerg /// pointer, or 0 if this is a null member pointer. 1718 1.1 joerg const ValueDecl *getDecl() const { 1719 1.1 joerg return DeclAndIsDerivedMember.getPointer(); 1720 1.1 joerg } 1721 1.1 joerg /// Is this actually a member of some type derived from the relevant class? 1722 1.1 joerg bool isDerivedMember() const { 1723 1.1 joerg return DeclAndIsDerivedMember.getInt(); 1724 1.1 joerg } 1725 1.1 joerg /// Get the class which the declaration actually lives in. 1726 1.1 joerg const CXXRecordDecl *getContainingRecord() const { 1727 1.1 joerg return cast<CXXRecordDecl>( 1728 1.1 joerg DeclAndIsDerivedMember.getPointer()->getDeclContext()); 1729 1.1 joerg } 1730 1.1 joerg 1731 1.1 joerg void moveInto(APValue &V) const { 1732 1.1 joerg V = APValue(getDecl(), isDerivedMember(), Path); 1733 1.1 joerg } 1734 1.1 joerg void setFrom(const APValue &V) { 1735 1.1 joerg assert(V.isMemberPointer()); 1736 1.1 joerg DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl()); 1737 1.1 joerg DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember()); 1738 1.1 joerg Path.clear(); 1739 1.1 joerg ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath(); 1740 1.1 joerg Path.insert(Path.end(), P.begin(), P.end()); 1741 1.1 joerg } 1742 1.1 joerg 1743 1.1 joerg /// DeclAndIsDerivedMember - The member declaration, and a flag indicating 1744 1.1 joerg /// whether the member is a member of some class derived from the class type 1745 1.1 joerg /// of the member pointer. 1746 1.1 joerg llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember; 1747 1.1 joerg /// Path - The path of base/derived classes from the member declaration's 1748 1.1 joerg /// class (exclusive) to the class type of the member pointer (inclusive). 1749 1.1 joerg SmallVector<const CXXRecordDecl*, 4> Path; 1750 1.1 joerg 1751 1.1 joerg /// Perform a cast towards the class of the Decl (either up or down the 1752 1.1 joerg /// hierarchy). 1753 1.1 joerg bool castBack(const CXXRecordDecl *Class) { 1754 1.1 joerg assert(!Path.empty()); 1755 1.1 joerg const CXXRecordDecl *Expected; 1756 1.1 joerg if (Path.size() >= 2) 1757 1.1 joerg Expected = Path[Path.size() - 2]; 1758 1.1 joerg else 1759 1.1 joerg Expected = getContainingRecord(); 1760 1.1 joerg if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) { 1761 1.1 joerg // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*), 1762 1.1 joerg // if B does not contain the original member and is not a base or 1763 1.1 joerg // derived class of the class containing the original member, the result 1764 1.1 joerg // of the cast is undefined. 1765 1.1 joerg // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to 1766 1.1 joerg // (D::*). We consider that to be a language defect. 1767 1.1 joerg return false; 1768 1.1 joerg } 1769 1.1 joerg Path.pop_back(); 1770 1.1 joerg return true; 1771 1.1 joerg } 1772 1.1 joerg /// Perform a base-to-derived member pointer cast. 1773 1.1 joerg bool castToDerived(const CXXRecordDecl *Derived) { 1774 1.1 joerg if (!getDecl()) 1775 1.1 joerg return true; 1776 1.1 joerg if (!isDerivedMember()) { 1777 1.1 joerg Path.push_back(Derived); 1778 1.1 joerg return true; 1779 1.1 joerg } 1780 1.1 joerg if (!castBack(Derived)) 1781 1.1 joerg return false; 1782 1.1 joerg if (Path.empty()) 1783 1.1 joerg DeclAndIsDerivedMember.setInt(false); 1784 1.1 joerg return true; 1785 1.1 joerg } 1786 1.1 joerg /// Perform a derived-to-base member pointer cast. 1787 1.1 joerg bool castToBase(const CXXRecordDecl *Base) { 1788 1.1 joerg if (!getDecl()) 1789 1.1 joerg return true; 1790 1.1 joerg if (Path.empty()) 1791 1.1 joerg DeclAndIsDerivedMember.setInt(true); 1792 1.1 joerg if (isDerivedMember()) { 1793 1.1 joerg Path.push_back(Base); 1794 1.1 joerg return true; 1795 1.1 joerg } 1796 1.1 joerg return castBack(Base); 1797 1.1 joerg } 1798 1.1 joerg }; 1799 1.1 joerg 1800 1.1 joerg /// Compare two member pointers, which are assumed to be of the same type. 1801 1.1 joerg static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) { 1802 1.1 joerg if (!LHS.getDecl() || !RHS.getDecl()) 1803 1.1 joerg return !LHS.getDecl() && !RHS.getDecl(); 1804 1.1 joerg if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl()) 1805 1.1 joerg return false; 1806 1.1 joerg return LHS.Path == RHS.Path; 1807 1.1 joerg } 1808 1.1 joerg } 1809 1.1 joerg 1810 1.1 joerg static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E); 1811 1.1 joerg static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, 1812 1.1 joerg const LValue &This, const Expr *E, 1813 1.1 joerg bool AllowNonLiteralTypes = false); 1814 1.1 joerg static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, 1815 1.1 joerg bool InvalidBaseOK = false); 1816 1.1 joerg static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info, 1817 1.1 joerg bool InvalidBaseOK = false); 1818 1.1 joerg static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, 1819 1.1 joerg EvalInfo &Info); 1820 1.1 joerg static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info); 1821 1.1 joerg static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info); 1822 1.1 joerg static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, 1823 1.1 joerg EvalInfo &Info); 1824 1.1 joerg static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info); 1825 1.1 joerg static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info); 1826 1.1 joerg static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, 1827 1.1 joerg EvalInfo &Info); 1828 1.1 joerg static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result); 1829 1.1 joerg 1830 1.1 joerg /// Evaluate an integer or fixed point expression into an APResult. 1831 1.1 joerg static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, 1832 1.1 joerg EvalInfo &Info); 1833 1.1 joerg 1834 1.1 joerg /// Evaluate only a fixed point expression into an APResult. 1835 1.1 joerg static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, 1836 1.1 joerg EvalInfo &Info); 1837 1.1 joerg 1838 1.1 joerg //===----------------------------------------------------------------------===// 1839 1.1 joerg // Misc utilities 1840 1.1 joerg //===----------------------------------------------------------------------===// 1841 1.1 joerg 1842 1.1 joerg /// Negate an APSInt in place, converting it to a signed form if necessary, and 1843 1.1 joerg /// preserving its value (by extending by up to one bit as needed). 1844 1.1 joerg static void negateAsSigned(APSInt &Int) { 1845 1.1 joerg if (Int.isUnsigned() || Int.isMinSignedValue()) { 1846 1.1 joerg Int = Int.extend(Int.getBitWidth() + 1); 1847 1.1 joerg Int.setIsSigned(true); 1848 1.1 joerg } 1849 1.1 joerg Int = -Int; 1850 1.1 joerg } 1851 1.1 joerg 1852 1.1 joerg template<typename KeyT> 1853 1.1 joerg APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T, 1854 1.1.1.2 joerg ScopeKind Scope, LValue &LV) { 1855 1.1 joerg unsigned Version = getTempVersion(); 1856 1.1 joerg APValue::LValueBase Base(Key, Index, Version); 1857 1.1 joerg LV.set(Base); 1858 1.1.1.2 joerg return createLocal(Base, Key, T, Scope); 1859 1.1.1.2 joerg } 1860 1.1.1.2 joerg 1861 1.1.1.2 joerg /// Allocate storage for a parameter of a function call made in this frame. 1862 1.1.1.2 joerg APValue &CallStackFrame::createParam(CallRef Args, const ParmVarDecl *PVD, 1863 1.1.1.2 joerg LValue &LV) { 1864 1.1.1.2 joerg assert(Args.CallIndex == Index && "creating parameter in wrong frame"); 1865 1.1.1.2 joerg APValue::LValueBase Base(PVD, Index, Args.Version); 1866 1.1.1.2 joerg LV.set(Base); 1867 1.1.1.2 joerg // We always destroy parameters at the end of the call, even if we'd allow 1868 1.1.1.2 joerg // them to live to the end of the full-expression at runtime, in order to 1869 1.1.1.2 joerg // give portable results and match other compilers. 1870 1.1.1.2 joerg return createLocal(Base, PVD, PVD->getType(), ScopeKind::Call); 1871 1.1.1.2 joerg } 1872 1.1.1.2 joerg 1873 1.1.1.2 joerg APValue &CallStackFrame::createLocal(APValue::LValueBase Base, const void *Key, 1874 1.1.1.2 joerg QualType T, ScopeKind Scope) { 1875 1.1.1.2 joerg assert(Base.getCallIndex() == Index && "lvalue for wrong frame"); 1876 1.1.1.2 joerg unsigned Version = Base.getVersion(); 1877 1.1 joerg APValue &Result = Temporaries[MapKeyTy(Key, Version)]; 1878 1.1.1.2 joerg assert(Result.isAbsent() && "local created multiple times"); 1879 1.1 joerg 1880 1.1.1.2 joerg // If we're creating a local immediately in the operand of a speculative 1881 1.1 joerg // evaluation, don't register a cleanup to be run outside the speculative 1882 1.1 joerg // evaluation context, since we won't actually be able to initialize this 1883 1.1 joerg // object. 1884 1.1 joerg if (Index <= Info.SpeculativeEvaluationDepth) { 1885 1.1 joerg if (T.isDestructedType()) 1886 1.1 joerg Info.noteSideEffect(); 1887 1.1 joerg } else { 1888 1.1.1.2 joerg Info.CleanupStack.push_back(Cleanup(&Result, Base, T, Scope)); 1889 1.1 joerg } 1890 1.1 joerg return Result; 1891 1.1 joerg } 1892 1.1 joerg 1893 1.1 joerg APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) { 1894 1.1 joerg if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) { 1895 1.1 joerg FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded); 1896 1.1 joerg return nullptr; 1897 1.1 joerg } 1898 1.1 joerg 1899 1.1 joerg DynamicAllocLValue DA(NumHeapAllocs++); 1900 1.1 joerg LV.set(APValue::LValueBase::getDynamicAlloc(DA, T)); 1901 1.1 joerg auto Result = HeapAllocs.emplace(std::piecewise_construct, 1902 1.1 joerg std::forward_as_tuple(DA), std::tuple<>()); 1903 1.1 joerg assert(Result.second && "reused a heap alloc index?"); 1904 1.1 joerg Result.first->second.AllocExpr = E; 1905 1.1 joerg return &Result.first->second.Value; 1906 1.1 joerg } 1907 1.1 joerg 1908 1.1 joerg /// Produce a string describing the given constexpr call. 1909 1.1 joerg void CallStackFrame::describe(raw_ostream &Out) { 1910 1.1 joerg unsigned ArgIndex = 0; 1911 1.1 joerg bool IsMemberCall = isa<CXXMethodDecl>(Callee) && 1912 1.1 joerg !isa<CXXConstructorDecl>(Callee) && 1913 1.1 joerg cast<CXXMethodDecl>(Callee)->isInstance(); 1914 1.1 joerg 1915 1.1 joerg if (!IsMemberCall) 1916 1.1 joerg Out << *Callee << '('; 1917 1.1 joerg 1918 1.1 joerg if (This && IsMemberCall) { 1919 1.1 joerg APValue Val; 1920 1.1 joerg This->moveInto(Val); 1921 1.1 joerg Val.printPretty(Out, Info.Ctx, 1922 1.1 joerg This->Designator.MostDerivedType); 1923 1.1 joerg // FIXME: Add parens around Val if needed. 1924 1.1 joerg Out << "->" << *Callee << '('; 1925 1.1 joerg IsMemberCall = false; 1926 1.1 joerg } 1927 1.1 joerg 1928 1.1 joerg for (FunctionDecl::param_const_iterator I = Callee->param_begin(), 1929 1.1 joerg E = Callee->param_end(); I != E; ++I, ++ArgIndex) { 1930 1.1 joerg if (ArgIndex > (unsigned)IsMemberCall) 1931 1.1 joerg Out << ", "; 1932 1.1 joerg 1933 1.1 joerg const ParmVarDecl *Param = *I; 1934 1.1.1.2 joerg APValue *V = Info.getParamSlot(Arguments, Param); 1935 1.1.1.2 joerg if (V) 1936 1.1.1.2 joerg V->printPretty(Out, Info.Ctx, Param->getType()); 1937 1.1.1.2 joerg else 1938 1.1.1.2 joerg Out << "<...>"; 1939 1.1 joerg 1940 1.1 joerg if (ArgIndex == 0 && IsMemberCall) 1941 1.1 joerg Out << "->" << *Callee << '('; 1942 1.1 joerg } 1943 1.1 joerg 1944 1.1 joerg Out << ')'; 1945 1.1 joerg } 1946 1.1 joerg 1947 1.1 joerg /// Evaluate an expression to see if it had side-effects, and discard its 1948 1.1 joerg /// result. 1949 1.1 joerg /// \return \c true if the caller should keep evaluating. 1950 1.1 joerg static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) { 1951 1.1.1.2 joerg assert(!E->isValueDependent()); 1952 1.1 joerg APValue Scratch; 1953 1.1 joerg if (!Evaluate(Scratch, Info, E)) 1954 1.1 joerg // We don't need the value, but we might have skipped a side effect here. 1955 1.1 joerg return Info.noteSideEffect(); 1956 1.1 joerg return true; 1957 1.1 joerg } 1958 1.1 joerg 1959 1.1 joerg /// Should this call expression be treated as a string literal? 1960 1.1 joerg static bool IsStringLiteralCall(const CallExpr *E) { 1961 1.1 joerg unsigned Builtin = E->getBuiltinCallee(); 1962 1.1 joerg return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString || 1963 1.1 joerg Builtin == Builtin::BI__builtin___NSStringMakeConstantString); 1964 1.1 joerg } 1965 1.1 joerg 1966 1.1 joerg static bool IsGlobalLValue(APValue::LValueBase B) { 1967 1.1 joerg // C++11 [expr.const]p3 An address constant expression is a prvalue core 1968 1.1 joerg // constant expression of pointer type that evaluates to... 1969 1.1 joerg 1970 1.1 joerg // ... a null pointer value, or a prvalue core constant expression of type 1971 1.1 joerg // std::nullptr_t. 1972 1.1 joerg if (!B) return true; 1973 1.1 joerg 1974 1.1 joerg if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 1975 1.1 joerg // ... the address of an object with static storage duration, 1976 1.1 joerg if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 1977 1.1 joerg return VD->hasGlobalStorage(); 1978 1.1.1.2 joerg if (isa<TemplateParamObjectDecl>(D)) 1979 1.1.1.2 joerg return true; 1980 1.1 joerg // ... the address of a function, 1981 1.1.1.2 joerg // ... the address of a GUID [MS extension], 1982 1.1.1.2 joerg return isa<FunctionDecl>(D) || isa<MSGuidDecl>(D); 1983 1.1 joerg } 1984 1.1 joerg 1985 1.1 joerg if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>()) 1986 1.1 joerg return true; 1987 1.1 joerg 1988 1.1 joerg const Expr *E = B.get<const Expr*>(); 1989 1.1 joerg switch (E->getStmtClass()) { 1990 1.1 joerg default: 1991 1.1 joerg return false; 1992 1.1 joerg case Expr::CompoundLiteralExprClass: { 1993 1.1 joerg const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E); 1994 1.1 joerg return CLE->isFileScope() && CLE->isLValue(); 1995 1.1 joerg } 1996 1.1 joerg case Expr::MaterializeTemporaryExprClass: 1997 1.1 joerg // A materialized temporary might have been lifetime-extended to static 1998 1.1 joerg // storage duration. 1999 1.1 joerg return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static; 2000 1.1 joerg // A string literal has static storage duration. 2001 1.1 joerg case Expr::StringLiteralClass: 2002 1.1 joerg case Expr::PredefinedExprClass: 2003 1.1 joerg case Expr::ObjCStringLiteralClass: 2004 1.1 joerg case Expr::ObjCEncodeExprClass: 2005 1.1 joerg return true; 2006 1.1 joerg case Expr::ObjCBoxedExprClass: 2007 1.1 joerg return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer(); 2008 1.1 joerg case Expr::CallExprClass: 2009 1.1 joerg return IsStringLiteralCall(cast<CallExpr>(E)); 2010 1.1 joerg // For GCC compatibility, &&label has static storage duration. 2011 1.1 joerg case Expr::AddrLabelExprClass: 2012 1.1 joerg return true; 2013 1.1 joerg // A Block literal expression may be used as the initialization value for 2014 1.1 joerg // Block variables at global or local static scope. 2015 1.1 joerg case Expr::BlockExprClass: 2016 1.1 joerg return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures(); 2017 1.1 joerg case Expr::ImplicitValueInitExprClass: 2018 1.1 joerg // FIXME: 2019 1.1 joerg // We can never form an lvalue with an implicit value initialization as its 2020 1.1 joerg // base through expression evaluation, so these only appear in one case: the 2021 1.1 joerg // implicit variable declaration we invent when checking whether a constexpr 2022 1.1 joerg // constructor can produce a constant expression. We must assume that such 2023 1.1 joerg // an expression might be a global lvalue. 2024 1.1 joerg return true; 2025 1.1 joerg } 2026 1.1 joerg } 2027 1.1 joerg 2028 1.1 joerg static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) { 2029 1.1 joerg return LVal.Base.dyn_cast<const ValueDecl*>(); 2030 1.1 joerg } 2031 1.1 joerg 2032 1.1 joerg static bool IsLiteralLValue(const LValue &Value) { 2033 1.1 joerg if (Value.getLValueCallIndex()) 2034 1.1 joerg return false; 2035 1.1 joerg const Expr *E = Value.Base.dyn_cast<const Expr*>(); 2036 1.1 joerg return E && !isa<MaterializeTemporaryExpr>(E); 2037 1.1 joerg } 2038 1.1 joerg 2039 1.1 joerg static bool IsWeakLValue(const LValue &Value) { 2040 1.1 joerg const ValueDecl *Decl = GetLValueBaseDecl(Value); 2041 1.1 joerg return Decl && Decl->isWeak(); 2042 1.1 joerg } 2043 1.1 joerg 2044 1.1 joerg static bool isZeroSized(const LValue &Value) { 2045 1.1 joerg const ValueDecl *Decl = GetLValueBaseDecl(Value); 2046 1.1 joerg if (Decl && isa<VarDecl>(Decl)) { 2047 1.1 joerg QualType Ty = Decl->getType(); 2048 1.1 joerg if (Ty->isArrayType()) 2049 1.1 joerg return Ty->isIncompleteType() || 2050 1.1 joerg Decl->getASTContext().getTypeSize(Ty) == 0; 2051 1.1 joerg } 2052 1.1 joerg return false; 2053 1.1 joerg } 2054 1.1 joerg 2055 1.1 joerg static bool HasSameBase(const LValue &A, const LValue &B) { 2056 1.1 joerg if (!A.getLValueBase()) 2057 1.1 joerg return !B.getLValueBase(); 2058 1.1 joerg if (!B.getLValueBase()) 2059 1.1 joerg return false; 2060 1.1 joerg 2061 1.1 joerg if (A.getLValueBase().getOpaqueValue() != 2062 1.1.1.2 joerg B.getLValueBase().getOpaqueValue()) 2063 1.1.1.2 joerg return false; 2064 1.1 joerg 2065 1.1.1.2 joerg return A.getLValueCallIndex() == B.getLValueCallIndex() && 2066 1.1.1.2 joerg A.getLValueVersion() == B.getLValueVersion(); 2067 1.1 joerg } 2068 1.1 joerg 2069 1.1 joerg static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) { 2070 1.1 joerg assert(Base && "no location for a null lvalue"); 2071 1.1 joerg const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 2072 1.1.1.2 joerg 2073 1.1.1.2 joerg // For a parameter, find the corresponding call stack frame (if it still 2074 1.1.1.2 joerg // exists), and point at the parameter of the function definition we actually 2075 1.1.1.2 joerg // invoked. 2076 1.1.1.2 joerg if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) { 2077 1.1.1.2 joerg unsigned Idx = PVD->getFunctionScopeIndex(); 2078 1.1.1.2 joerg for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) { 2079 1.1.1.2 joerg if (F->Arguments.CallIndex == Base.getCallIndex() && 2080 1.1.1.2 joerg F->Arguments.Version == Base.getVersion() && F->Callee && 2081 1.1.1.2 joerg Idx < F->Callee->getNumParams()) { 2082 1.1.1.2 joerg VD = F->Callee->getParamDecl(Idx); 2083 1.1.1.2 joerg break; 2084 1.1.1.2 joerg } 2085 1.1.1.2 joerg } 2086 1.1.1.2 joerg } 2087 1.1.1.2 joerg 2088 1.1 joerg if (VD) 2089 1.1 joerg Info.Note(VD->getLocation(), diag::note_declared_at); 2090 1.1 joerg else if (const Expr *E = Base.dyn_cast<const Expr*>()) 2091 1.1 joerg Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here); 2092 1.1 joerg else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) { 2093 1.1 joerg // FIXME: Produce a note for dangling pointers too. 2094 1.1 joerg if (Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA)) 2095 1.1 joerg Info.Note((*Alloc)->AllocExpr->getExprLoc(), 2096 1.1 joerg diag::note_constexpr_dynamic_alloc_here); 2097 1.1 joerg } 2098 1.1 joerg // We have no information to show for a typeid(T) object. 2099 1.1 joerg } 2100 1.1 joerg 2101 1.1 joerg enum class CheckEvaluationResultKind { 2102 1.1 joerg ConstantExpression, 2103 1.1 joerg FullyInitialized, 2104 1.1 joerg }; 2105 1.1 joerg 2106 1.1 joerg /// Materialized temporaries that we've already checked to determine if they're 2107 1.1 joerg /// initializsed by a constant expression. 2108 1.1 joerg using CheckedTemporaries = 2109 1.1 joerg llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>; 2110 1.1 joerg 2111 1.1 joerg static bool CheckEvaluationResult(CheckEvaluationResultKind CERK, 2112 1.1 joerg EvalInfo &Info, SourceLocation DiagLoc, 2113 1.1 joerg QualType Type, const APValue &Value, 2114 1.1.1.2 joerg ConstantExprKind Kind, 2115 1.1 joerg SourceLocation SubobjectLoc, 2116 1.1 joerg CheckedTemporaries &CheckedTemps); 2117 1.1 joerg 2118 1.1 joerg /// Check that this reference or pointer core constant expression is a valid 2119 1.1 joerg /// value for an address or reference constant expression. Return true if we 2120 1.1 joerg /// can fold this expression, whether or not it's a constant expression. 2121 1.1 joerg static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc, 2122 1.1 joerg QualType Type, const LValue &LVal, 2123 1.1.1.2 joerg ConstantExprKind Kind, 2124 1.1 joerg CheckedTemporaries &CheckedTemps) { 2125 1.1 joerg bool IsReferenceType = Type->isReferenceType(); 2126 1.1 joerg 2127 1.1 joerg APValue::LValueBase Base = LVal.getLValueBase(); 2128 1.1 joerg const SubobjectDesignator &Designator = LVal.getLValueDesignator(); 2129 1.1 joerg 2130 1.1.1.2 joerg const Expr *BaseE = Base.dyn_cast<const Expr *>(); 2131 1.1.1.2 joerg const ValueDecl *BaseVD = Base.dyn_cast<const ValueDecl*>(); 2132 1.1.1.2 joerg 2133 1.1.1.2 joerg // Additional restrictions apply in a template argument. We only enforce the 2134 1.1.1.2 joerg // C++20 restrictions here; additional syntactic and semantic restrictions 2135 1.1.1.2 joerg // are applied elsewhere. 2136 1.1.1.2 joerg if (isTemplateArgument(Kind)) { 2137 1.1.1.2 joerg int InvalidBaseKind = -1; 2138 1.1.1.2 joerg StringRef Ident; 2139 1.1.1.2 joerg if (Base.is<TypeInfoLValue>()) 2140 1.1.1.2 joerg InvalidBaseKind = 0; 2141 1.1.1.2 joerg else if (isa_and_nonnull<StringLiteral>(BaseE)) 2142 1.1.1.2 joerg InvalidBaseKind = 1; 2143 1.1.1.2 joerg else if (isa_and_nonnull<MaterializeTemporaryExpr>(BaseE) || 2144 1.1.1.2 joerg isa_and_nonnull<LifetimeExtendedTemporaryDecl>(BaseVD)) 2145 1.1.1.2 joerg InvalidBaseKind = 2; 2146 1.1.1.2 joerg else if (auto *PE = dyn_cast_or_null<PredefinedExpr>(BaseE)) { 2147 1.1.1.2 joerg InvalidBaseKind = 3; 2148 1.1.1.2 joerg Ident = PE->getIdentKindName(); 2149 1.1.1.2 joerg } 2150 1.1.1.2 joerg 2151 1.1.1.2 joerg if (InvalidBaseKind != -1) { 2152 1.1.1.2 joerg Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg) 2153 1.1.1.2 joerg << IsReferenceType << !Designator.Entries.empty() << InvalidBaseKind 2154 1.1.1.2 joerg << Ident; 2155 1.1.1.2 joerg return false; 2156 1.1.1.2 joerg } 2157 1.1.1.2 joerg } 2158 1.1.1.2 joerg 2159 1.1.1.2 joerg if (auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD)) { 2160 1.1.1.2 joerg if (FD->isConsteval()) { 2161 1.1.1.2 joerg Info.FFDiag(Loc, diag::note_consteval_address_accessible) 2162 1.1.1.2 joerg << !Type->isAnyPointerType(); 2163 1.1.1.2 joerg Info.Note(FD->getLocation(), diag::note_declared_at); 2164 1.1.1.2 joerg return false; 2165 1.1.1.2 joerg } 2166 1.1.1.2 joerg } 2167 1.1.1.2 joerg 2168 1.1 joerg // Check that the object is a global. Note that the fake 'this' object we 2169 1.1 joerg // manufacture when checking potential constant expressions is conservatively 2170 1.1 joerg // assumed to be global here. 2171 1.1 joerg if (!IsGlobalLValue(Base)) { 2172 1.1 joerg if (Info.getLangOpts().CPlusPlus11) { 2173 1.1 joerg const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 2174 1.1 joerg Info.FFDiag(Loc, diag::note_constexpr_non_global, 1) 2175 1.1 joerg << IsReferenceType << !Designator.Entries.empty() 2176 1.1 joerg << !!VD << VD; 2177 1.1.1.2 joerg 2178 1.1.1.2 joerg auto *VarD = dyn_cast_or_null<VarDecl>(VD); 2179 1.1.1.2 joerg if (VarD && VarD->isConstexpr()) { 2180 1.1.1.2 joerg // Non-static local constexpr variables have unintuitive semantics: 2181 1.1.1.2 joerg // constexpr int a = 1; 2182 1.1.1.2 joerg // constexpr const int *p = &a; 2183 1.1.1.2 joerg // ... is invalid because the address of 'a' is not constant. Suggest 2184 1.1.1.2 joerg // adding a 'static' in this case. 2185 1.1.1.2 joerg Info.Note(VarD->getLocation(), diag::note_constexpr_not_static) 2186 1.1.1.2 joerg << VarD 2187 1.1.1.2 joerg << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static "); 2188 1.1.1.2 joerg } else { 2189 1.1.1.2 joerg NoteLValueLocation(Info, Base); 2190 1.1.1.2 joerg } 2191 1.1 joerg } else { 2192 1.1 joerg Info.FFDiag(Loc); 2193 1.1 joerg } 2194 1.1 joerg // Don't allow references to temporaries to escape. 2195 1.1 joerg return false; 2196 1.1 joerg } 2197 1.1 joerg assert((Info.checkingPotentialConstantExpression() || 2198 1.1 joerg LVal.getLValueCallIndex() == 0) && 2199 1.1 joerg "have call index for global lvalue"); 2200 1.1 joerg 2201 1.1 joerg if (Base.is<DynamicAllocLValue>()) { 2202 1.1 joerg Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc) 2203 1.1 joerg << IsReferenceType << !Designator.Entries.empty(); 2204 1.1 joerg NoteLValueLocation(Info, Base); 2205 1.1 joerg return false; 2206 1.1 joerg } 2207 1.1 joerg 2208 1.1.1.2 joerg if (BaseVD) { 2209 1.1.1.2 joerg if (const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) { 2210 1.1 joerg // Check if this is a thread-local variable. 2211 1.1 joerg if (Var->getTLSKind()) 2212 1.1 joerg // FIXME: Diagnostic! 2213 1.1 joerg return false; 2214 1.1 joerg 2215 1.1.1.2 joerg // A dllimport variable never acts like a constant, unless we're 2216 1.1.1.2 joerg // evaluating a value for use only in name mangling. 2217 1.1.1.2 joerg if (!isForManglingOnly(Kind) && Var->hasAttr<DLLImportAttr>()) 2218 1.1 joerg // FIXME: Diagnostic! 2219 1.1 joerg return false; 2220 1.1 joerg } 2221 1.1.1.2 joerg if (const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) { 2222 1.1 joerg // __declspec(dllimport) must be handled very carefully: 2223 1.1 joerg // We must never initialize an expression with the thunk in C++. 2224 1.1 joerg // Doing otherwise would allow the same id-expression to yield 2225 1.1 joerg // different addresses for the same function in different translation 2226 1.1 joerg // units. However, this means that we must dynamically initialize the 2227 1.1 joerg // expression with the contents of the import address table at runtime. 2228 1.1 joerg // 2229 1.1 joerg // The C language has no notion of ODR; furthermore, it has no notion of 2230 1.1 joerg // dynamic initialization. This means that we are permitted to 2231 1.1 joerg // perform initialization with the address of the thunk. 2232 1.1.1.2 joerg if (Info.getLangOpts().CPlusPlus && !isForManglingOnly(Kind) && 2233 1.1 joerg FD->hasAttr<DLLImportAttr>()) 2234 1.1 joerg // FIXME: Diagnostic! 2235 1.1 joerg return false; 2236 1.1 joerg } 2237 1.1.1.2 joerg } else if (const auto *MTE = 2238 1.1.1.2 joerg dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) { 2239 1.1 joerg if (CheckedTemps.insert(MTE).second) { 2240 1.1 joerg QualType TempType = getType(Base); 2241 1.1 joerg if (TempType.isDestructedType()) { 2242 1.1 joerg Info.FFDiag(MTE->getExprLoc(), 2243 1.1.1.2 joerg diag::note_constexpr_unsupported_temporary_nontrivial_dtor) 2244 1.1 joerg << TempType; 2245 1.1 joerg return false; 2246 1.1 joerg } 2247 1.1 joerg 2248 1.1.1.2 joerg APValue *V = MTE->getOrCreateValue(false); 2249 1.1 joerg assert(V && "evasluation result refers to uninitialised temporary"); 2250 1.1 joerg if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression, 2251 1.1 joerg Info, MTE->getExprLoc(), TempType, *V, 2252 1.1.1.2 joerg Kind, SourceLocation(), CheckedTemps)) 2253 1.1 joerg return false; 2254 1.1 joerg } 2255 1.1 joerg } 2256 1.1 joerg 2257 1.1 joerg // Allow address constant expressions to be past-the-end pointers. This is 2258 1.1 joerg // an extension: the standard requires them to point to an object. 2259 1.1 joerg if (!IsReferenceType) 2260 1.1 joerg return true; 2261 1.1 joerg 2262 1.1 joerg // A reference constant expression must refer to an object. 2263 1.1 joerg if (!Base) { 2264 1.1 joerg // FIXME: diagnostic 2265 1.1 joerg Info.CCEDiag(Loc); 2266 1.1 joerg return true; 2267 1.1 joerg } 2268 1.1 joerg 2269 1.1 joerg // Does this refer one past the end of some object? 2270 1.1 joerg if (!Designator.Invalid && Designator.isOnePastTheEnd()) { 2271 1.1 joerg Info.FFDiag(Loc, diag::note_constexpr_past_end, 1) 2272 1.1.1.2 joerg << !Designator.Entries.empty() << !!BaseVD << BaseVD; 2273 1.1 joerg NoteLValueLocation(Info, Base); 2274 1.1 joerg } 2275 1.1 joerg 2276 1.1 joerg return true; 2277 1.1 joerg } 2278 1.1 joerg 2279 1.1 joerg /// Member pointers are constant expressions unless they point to a 2280 1.1 joerg /// non-virtual dllimport member function. 2281 1.1 joerg static bool CheckMemberPointerConstantExpression(EvalInfo &Info, 2282 1.1 joerg SourceLocation Loc, 2283 1.1 joerg QualType Type, 2284 1.1 joerg const APValue &Value, 2285 1.1.1.2 joerg ConstantExprKind Kind) { 2286 1.1 joerg const ValueDecl *Member = Value.getMemberPointerDecl(); 2287 1.1 joerg const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member); 2288 1.1 joerg if (!FD) 2289 1.1 joerg return true; 2290 1.1.1.2 joerg if (FD->isConsteval()) { 2291 1.1.1.2 joerg Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0; 2292 1.1.1.2 joerg Info.Note(FD->getLocation(), diag::note_declared_at); 2293 1.1.1.2 joerg return false; 2294 1.1.1.2 joerg } 2295 1.1.1.2 joerg return isForManglingOnly(Kind) || FD->isVirtual() || 2296 1.1 joerg !FD->hasAttr<DLLImportAttr>(); 2297 1.1 joerg } 2298 1.1 joerg 2299 1.1 joerg /// Check that this core constant expression is of literal type, and if not, 2300 1.1 joerg /// produce an appropriate diagnostic. 2301 1.1 joerg static bool CheckLiteralType(EvalInfo &Info, const Expr *E, 2302 1.1 joerg const LValue *This = nullptr) { 2303 1.1 joerg if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx)) 2304 1.1 joerg return true; 2305 1.1 joerg 2306 1.1 joerg // C++1y: A constant initializer for an object o [...] may also invoke 2307 1.1 joerg // constexpr constructors for o and its subobjects even if those objects 2308 1.1 joerg // are of non-literal class types. 2309 1.1 joerg // 2310 1.1 joerg // C++11 missed this detail for aggregates, so classes like this: 2311 1.1 joerg // struct foo_t { union { int i; volatile int j; } u; }; 2312 1.1 joerg // are not (obviously) initializable like so: 2313 1.1 joerg // __attribute__((__require_constant_initialization__)) 2314 1.1 joerg // static const foo_t x = {{0}}; 2315 1.1 joerg // because "i" is a subobject with non-literal initialization (due to the 2316 1.1 joerg // volatile member of the union). See: 2317 1.1 joerg // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677 2318 1.1 joerg // Therefore, we use the C++1y behavior. 2319 1.1 joerg if (This && Info.EvaluatingDecl == This->getLValueBase()) 2320 1.1 joerg return true; 2321 1.1 joerg 2322 1.1 joerg // Prvalue constant expressions must be of literal types. 2323 1.1 joerg if (Info.getLangOpts().CPlusPlus11) 2324 1.1 joerg Info.FFDiag(E, diag::note_constexpr_nonliteral) 2325 1.1 joerg << E->getType(); 2326 1.1 joerg else 2327 1.1 joerg Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2328 1.1 joerg return false; 2329 1.1 joerg } 2330 1.1 joerg 2331 1.1 joerg static bool CheckEvaluationResult(CheckEvaluationResultKind CERK, 2332 1.1 joerg EvalInfo &Info, SourceLocation DiagLoc, 2333 1.1 joerg QualType Type, const APValue &Value, 2334 1.1.1.2 joerg ConstantExprKind Kind, 2335 1.1 joerg SourceLocation SubobjectLoc, 2336 1.1 joerg CheckedTemporaries &CheckedTemps) { 2337 1.1 joerg if (!Value.hasValue()) { 2338 1.1 joerg Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized) 2339 1.1 joerg << true << Type; 2340 1.1 joerg if (SubobjectLoc.isValid()) 2341 1.1 joerg Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here); 2342 1.1 joerg return false; 2343 1.1 joerg } 2344 1.1 joerg 2345 1.1 joerg // We allow _Atomic(T) to be initialized from anything that T can be 2346 1.1 joerg // initialized from. 2347 1.1 joerg if (const AtomicType *AT = Type->getAs<AtomicType>()) 2348 1.1 joerg Type = AT->getValueType(); 2349 1.1 joerg 2350 1.1 joerg // Core issue 1454: For a literal constant expression of array or class type, 2351 1.1 joerg // each subobject of its value shall have been initialized by a constant 2352 1.1 joerg // expression. 2353 1.1 joerg if (Value.isArray()) { 2354 1.1 joerg QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType(); 2355 1.1 joerg for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) { 2356 1.1 joerg if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy, 2357 1.1.1.2 joerg Value.getArrayInitializedElt(I), Kind, 2358 1.1 joerg SubobjectLoc, CheckedTemps)) 2359 1.1 joerg return false; 2360 1.1 joerg } 2361 1.1 joerg if (!Value.hasArrayFiller()) 2362 1.1 joerg return true; 2363 1.1 joerg return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy, 2364 1.1.1.2 joerg Value.getArrayFiller(), Kind, SubobjectLoc, 2365 1.1 joerg CheckedTemps); 2366 1.1 joerg } 2367 1.1 joerg if (Value.isUnion() && Value.getUnionField()) { 2368 1.1 joerg return CheckEvaluationResult( 2369 1.1 joerg CERK, Info, DiagLoc, Value.getUnionField()->getType(), 2370 1.1.1.2 joerg Value.getUnionValue(), Kind, Value.getUnionField()->getLocation(), 2371 1.1 joerg CheckedTemps); 2372 1.1 joerg } 2373 1.1 joerg if (Value.isStruct()) { 2374 1.1 joerg RecordDecl *RD = Type->castAs<RecordType>()->getDecl(); 2375 1.1 joerg if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) { 2376 1.1 joerg unsigned BaseIndex = 0; 2377 1.1 joerg for (const CXXBaseSpecifier &BS : CD->bases()) { 2378 1.1 joerg if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(), 2379 1.1.1.2 joerg Value.getStructBase(BaseIndex), Kind, 2380 1.1 joerg BS.getBeginLoc(), CheckedTemps)) 2381 1.1 joerg return false; 2382 1.1 joerg ++BaseIndex; 2383 1.1 joerg } 2384 1.1 joerg } 2385 1.1 joerg for (const auto *I : RD->fields()) { 2386 1.1 joerg if (I->isUnnamedBitfield()) 2387 1.1 joerg continue; 2388 1.1 joerg 2389 1.1 joerg if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(), 2390 1.1 joerg Value.getStructField(I->getFieldIndex()), 2391 1.1.1.2 joerg Kind, I->getLocation(), CheckedTemps)) 2392 1.1 joerg return false; 2393 1.1 joerg } 2394 1.1 joerg } 2395 1.1 joerg 2396 1.1 joerg if (Value.isLValue() && 2397 1.1 joerg CERK == CheckEvaluationResultKind::ConstantExpression) { 2398 1.1 joerg LValue LVal; 2399 1.1 joerg LVal.setFrom(Info.Ctx, Value); 2400 1.1.1.2 joerg return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Kind, 2401 1.1 joerg CheckedTemps); 2402 1.1 joerg } 2403 1.1 joerg 2404 1.1 joerg if (Value.isMemberPointer() && 2405 1.1 joerg CERK == CheckEvaluationResultKind::ConstantExpression) 2406 1.1.1.2 joerg return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Kind); 2407 1.1 joerg 2408 1.1 joerg // Everything else is fine. 2409 1.1 joerg return true; 2410 1.1 joerg } 2411 1.1 joerg 2412 1.1 joerg /// Check that this core constant expression value is a valid value for a 2413 1.1 joerg /// constant expression. If not, report an appropriate diagnostic. Does not 2414 1.1 joerg /// check that the expression is of literal type. 2415 1.1.1.2 joerg static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, 2416 1.1.1.2 joerg QualType Type, const APValue &Value, 2417 1.1.1.2 joerg ConstantExprKind Kind) { 2418 1.1.1.2 joerg // Nothing to check for a constant expression of type 'cv void'. 2419 1.1.1.2 joerg if (Type->isVoidType()) 2420 1.1.1.2 joerg return true; 2421 1.1.1.2 joerg 2422 1.1 joerg CheckedTemporaries CheckedTemps; 2423 1.1 joerg return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression, 2424 1.1.1.2 joerg Info, DiagLoc, Type, Value, Kind, 2425 1.1 joerg SourceLocation(), CheckedTemps); 2426 1.1 joerg } 2427 1.1 joerg 2428 1.1 joerg /// Check that this evaluated value is fully-initialized and can be loaded by 2429 1.1 joerg /// an lvalue-to-rvalue conversion. 2430 1.1 joerg static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc, 2431 1.1 joerg QualType Type, const APValue &Value) { 2432 1.1 joerg CheckedTemporaries CheckedTemps; 2433 1.1 joerg return CheckEvaluationResult( 2434 1.1 joerg CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value, 2435 1.1.1.2 joerg ConstantExprKind::Normal, SourceLocation(), CheckedTemps); 2436 1.1 joerg } 2437 1.1 joerg 2438 1.1 joerg /// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless 2439 1.1 joerg /// "the allocated storage is deallocated within the evaluation". 2440 1.1 joerg static bool CheckMemoryLeaks(EvalInfo &Info) { 2441 1.1 joerg if (!Info.HeapAllocs.empty()) { 2442 1.1 joerg // We can still fold to a constant despite a compile-time memory leak, 2443 1.1 joerg // so long as the heap allocation isn't referenced in the result (we check 2444 1.1 joerg // that in CheckConstantExpression). 2445 1.1 joerg Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr, 2446 1.1 joerg diag::note_constexpr_memory_leak) 2447 1.1 joerg << unsigned(Info.HeapAllocs.size() - 1); 2448 1.1 joerg } 2449 1.1 joerg return true; 2450 1.1 joerg } 2451 1.1 joerg 2452 1.1 joerg static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) { 2453 1.1 joerg // A null base expression indicates a null pointer. These are always 2454 1.1 joerg // evaluatable, and they are false unless the offset is zero. 2455 1.1 joerg if (!Value.getLValueBase()) { 2456 1.1 joerg Result = !Value.getLValueOffset().isZero(); 2457 1.1 joerg return true; 2458 1.1 joerg } 2459 1.1 joerg 2460 1.1 joerg // We have a non-null base. These are generally known to be true, but if it's 2461 1.1 joerg // a weak declaration it can be null at runtime. 2462 1.1 joerg Result = true; 2463 1.1 joerg const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>(); 2464 1.1 joerg return !Decl || !Decl->isWeak(); 2465 1.1 joerg } 2466 1.1 joerg 2467 1.1 joerg static bool HandleConversionToBool(const APValue &Val, bool &Result) { 2468 1.1 joerg switch (Val.getKind()) { 2469 1.1 joerg case APValue::None: 2470 1.1 joerg case APValue::Indeterminate: 2471 1.1 joerg return false; 2472 1.1 joerg case APValue::Int: 2473 1.1 joerg Result = Val.getInt().getBoolValue(); 2474 1.1 joerg return true; 2475 1.1 joerg case APValue::FixedPoint: 2476 1.1 joerg Result = Val.getFixedPoint().getBoolValue(); 2477 1.1 joerg return true; 2478 1.1 joerg case APValue::Float: 2479 1.1 joerg Result = !Val.getFloat().isZero(); 2480 1.1 joerg return true; 2481 1.1 joerg case APValue::ComplexInt: 2482 1.1 joerg Result = Val.getComplexIntReal().getBoolValue() || 2483 1.1 joerg Val.getComplexIntImag().getBoolValue(); 2484 1.1 joerg return true; 2485 1.1 joerg case APValue::ComplexFloat: 2486 1.1 joerg Result = !Val.getComplexFloatReal().isZero() || 2487 1.1 joerg !Val.getComplexFloatImag().isZero(); 2488 1.1 joerg return true; 2489 1.1 joerg case APValue::LValue: 2490 1.1 joerg return EvalPointerValueAsBool(Val, Result); 2491 1.1 joerg case APValue::MemberPointer: 2492 1.1 joerg Result = Val.getMemberPointerDecl(); 2493 1.1 joerg return true; 2494 1.1 joerg case APValue::Vector: 2495 1.1 joerg case APValue::Array: 2496 1.1 joerg case APValue::Struct: 2497 1.1 joerg case APValue::Union: 2498 1.1 joerg case APValue::AddrLabelDiff: 2499 1.1 joerg return false; 2500 1.1 joerg } 2501 1.1 joerg 2502 1.1 joerg llvm_unreachable("unknown APValue kind"); 2503 1.1 joerg } 2504 1.1 joerg 2505 1.1 joerg static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result, 2506 1.1 joerg EvalInfo &Info) { 2507 1.1.1.2 joerg assert(!E->isValueDependent()); 2508 1.1 joerg assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition"); 2509 1.1 joerg APValue Val; 2510 1.1 joerg if (!Evaluate(Val, Info, E)) 2511 1.1 joerg return false; 2512 1.1 joerg return HandleConversionToBool(Val, Result); 2513 1.1 joerg } 2514 1.1 joerg 2515 1.1 joerg template<typename T> 2516 1.1 joerg static bool HandleOverflow(EvalInfo &Info, const Expr *E, 2517 1.1 joerg const T &SrcValue, QualType DestType) { 2518 1.1 joerg Info.CCEDiag(E, diag::note_constexpr_overflow) 2519 1.1 joerg << SrcValue << DestType; 2520 1.1 joerg return Info.noteUndefinedBehavior(); 2521 1.1 joerg } 2522 1.1 joerg 2523 1.1 joerg static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E, 2524 1.1 joerg QualType SrcType, const APFloat &Value, 2525 1.1 joerg QualType DestType, APSInt &Result) { 2526 1.1 joerg unsigned DestWidth = Info.Ctx.getIntWidth(DestType); 2527 1.1 joerg // Determine whether we are converting to unsigned or signed. 2528 1.1 joerg bool DestSigned = DestType->isSignedIntegerOrEnumerationType(); 2529 1.1 joerg 2530 1.1 joerg Result = APSInt(DestWidth, !DestSigned); 2531 1.1 joerg bool ignored; 2532 1.1 joerg if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored) 2533 1.1 joerg & APFloat::opInvalidOp) 2534 1.1 joerg return HandleOverflow(Info, E, Value, DestType); 2535 1.1 joerg return true; 2536 1.1 joerg } 2537 1.1 joerg 2538 1.1.1.2 joerg /// Get rounding mode used for evaluation of the specified expression. 2539 1.1.1.2 joerg /// \param[out] DynamicRM Is set to true is the requested rounding mode is 2540 1.1.1.2 joerg /// dynamic. 2541 1.1.1.2 joerg /// If rounding mode is unknown at compile time, still try to evaluate the 2542 1.1.1.2 joerg /// expression. If the result is exact, it does not depend on rounding mode. 2543 1.1.1.2 joerg /// So return "tonearest" mode instead of "dynamic". 2544 1.1.1.2 joerg static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E, 2545 1.1.1.2 joerg bool &DynamicRM) { 2546 1.1.1.2 joerg llvm::RoundingMode RM = 2547 1.1.1.2 joerg E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).getRoundingMode(); 2548 1.1.1.2 joerg DynamicRM = (RM == llvm::RoundingMode::Dynamic); 2549 1.1.1.2 joerg if (DynamicRM) 2550 1.1.1.2 joerg RM = llvm::RoundingMode::NearestTiesToEven; 2551 1.1.1.2 joerg return RM; 2552 1.1.1.2 joerg } 2553 1.1.1.2 joerg 2554 1.1.1.2 joerg /// Check if the given evaluation result is allowed for constant evaluation. 2555 1.1.1.2 joerg static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E, 2556 1.1.1.2 joerg APFloat::opStatus St) { 2557 1.1.1.2 joerg // In a constant context, assume that any dynamic rounding mode or FP 2558 1.1.1.2 joerg // exception state matches the default floating-point environment. 2559 1.1.1.2 joerg if (Info.InConstantContext) 2560 1.1.1.2 joerg return true; 2561 1.1.1.2 joerg 2562 1.1.1.2 joerg FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()); 2563 1.1.1.2 joerg if ((St & APFloat::opInexact) && 2564 1.1.1.2 joerg FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) { 2565 1.1.1.2 joerg // Inexact result means that it depends on rounding mode. If the requested 2566 1.1.1.2 joerg // mode is dynamic, the evaluation cannot be made in compile time. 2567 1.1.1.2 joerg Info.FFDiag(E, diag::note_constexpr_dynamic_rounding); 2568 1.1.1.2 joerg return false; 2569 1.1.1.2 joerg } 2570 1.1.1.2 joerg 2571 1.1.1.2 joerg if ((St != APFloat::opOK) && 2572 1.1.1.2 joerg (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic || 2573 1.1.1.2 joerg FPO.getFPExceptionMode() != LangOptions::FPE_Ignore || 2574 1.1.1.2 joerg FPO.getAllowFEnvAccess())) { 2575 1.1.1.2 joerg Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict); 2576 1.1.1.2 joerg return false; 2577 1.1.1.2 joerg } 2578 1.1.1.2 joerg 2579 1.1.1.2 joerg if ((St & APFloat::opStatus::opInvalidOp) && 2580 1.1.1.2 joerg FPO.getFPExceptionMode() != LangOptions::FPE_Ignore) { 2581 1.1.1.2 joerg // There is no usefully definable result. 2582 1.1.1.2 joerg Info.FFDiag(E); 2583 1.1.1.2 joerg return false; 2584 1.1.1.2 joerg } 2585 1.1.1.2 joerg 2586 1.1.1.2 joerg // FIXME: if: 2587 1.1.1.2 joerg // - evaluation triggered other FP exception, and 2588 1.1.1.2 joerg // - exception mode is not "ignore", and 2589 1.1.1.2 joerg // - the expression being evaluated is not a part of global variable 2590 1.1.1.2 joerg // initializer, 2591 1.1.1.2 joerg // the evaluation probably need to be rejected. 2592 1.1.1.2 joerg return true; 2593 1.1.1.2 joerg } 2594 1.1.1.2 joerg 2595 1.1 joerg static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E, 2596 1.1 joerg QualType SrcType, QualType DestType, 2597 1.1 joerg APFloat &Result) { 2598 1.1.1.2 joerg assert(isa<CastExpr>(E) || isa<CompoundAssignOperator>(E)); 2599 1.1.1.2 joerg bool DynamicRM; 2600 1.1.1.2 joerg llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM); 2601 1.1.1.2 joerg APFloat::opStatus St; 2602 1.1 joerg APFloat Value = Result; 2603 1.1 joerg bool ignored; 2604 1.1.1.2 joerg St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored); 2605 1.1.1.2 joerg return checkFloatingPointResult(Info, E, St); 2606 1.1 joerg } 2607 1.1 joerg 2608 1.1 joerg static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E, 2609 1.1 joerg QualType DestType, QualType SrcType, 2610 1.1 joerg const APSInt &Value) { 2611 1.1 joerg unsigned DestWidth = Info.Ctx.getIntWidth(DestType); 2612 1.1 joerg // Figure out if this is a truncate, extend or noop cast. 2613 1.1 joerg // If the input is signed, do a sign extend, noop, or truncate. 2614 1.1 joerg APSInt Result = Value.extOrTrunc(DestWidth); 2615 1.1 joerg Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType()); 2616 1.1 joerg if (DestType->isBooleanType()) 2617 1.1 joerg Result = Value.getBoolValue(); 2618 1.1 joerg return Result; 2619 1.1 joerg } 2620 1.1 joerg 2621 1.1 joerg static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E, 2622 1.1.1.2 joerg const FPOptions FPO, 2623 1.1 joerg QualType SrcType, const APSInt &Value, 2624 1.1 joerg QualType DestType, APFloat &Result) { 2625 1.1 joerg Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1); 2626 1.1.1.2 joerg APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(), 2627 1.1.1.2 joerg APFloat::rmNearestTiesToEven); 2628 1.1.1.2 joerg if (!Info.InConstantContext && St != llvm::APFloatBase::opOK && 2629 1.1.1.2 joerg FPO.isFPConstrained()) { 2630 1.1.1.2 joerg Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict); 2631 1.1.1.2 joerg return false; 2632 1.1.1.2 joerg } 2633 1.1 joerg return true; 2634 1.1 joerg } 2635 1.1 joerg 2636 1.1 joerg static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E, 2637 1.1 joerg APValue &Value, const FieldDecl *FD) { 2638 1.1 joerg assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield"); 2639 1.1 joerg 2640 1.1 joerg if (!Value.isInt()) { 2641 1.1 joerg // Trying to store a pointer-cast-to-integer into a bitfield. 2642 1.1 joerg // FIXME: In this case, we should provide the diagnostic for casting 2643 1.1 joerg // a pointer to an integer. 2644 1.1 joerg assert(Value.isLValue() && "integral value neither int nor lvalue?"); 2645 1.1 joerg Info.FFDiag(E); 2646 1.1 joerg return false; 2647 1.1 joerg } 2648 1.1 joerg 2649 1.1 joerg APSInt &Int = Value.getInt(); 2650 1.1 joerg unsigned OldBitWidth = Int.getBitWidth(); 2651 1.1 joerg unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx); 2652 1.1 joerg if (NewBitWidth < OldBitWidth) 2653 1.1 joerg Int = Int.trunc(NewBitWidth).extend(OldBitWidth); 2654 1.1 joerg return true; 2655 1.1 joerg } 2656 1.1 joerg 2657 1.1 joerg static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E, 2658 1.1 joerg llvm::APInt &Res) { 2659 1.1 joerg APValue SVal; 2660 1.1 joerg if (!Evaluate(SVal, Info, E)) 2661 1.1 joerg return false; 2662 1.1 joerg if (SVal.isInt()) { 2663 1.1 joerg Res = SVal.getInt(); 2664 1.1 joerg return true; 2665 1.1 joerg } 2666 1.1 joerg if (SVal.isFloat()) { 2667 1.1 joerg Res = SVal.getFloat().bitcastToAPInt(); 2668 1.1 joerg return true; 2669 1.1 joerg } 2670 1.1 joerg if (SVal.isVector()) { 2671 1.1 joerg QualType VecTy = E->getType(); 2672 1.1 joerg unsigned VecSize = Info.Ctx.getTypeSize(VecTy); 2673 1.1 joerg QualType EltTy = VecTy->castAs<VectorType>()->getElementType(); 2674 1.1 joerg unsigned EltSize = Info.Ctx.getTypeSize(EltTy); 2675 1.1 joerg bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 2676 1.1 joerg Res = llvm::APInt::getNullValue(VecSize); 2677 1.1 joerg for (unsigned i = 0; i < SVal.getVectorLength(); i++) { 2678 1.1 joerg APValue &Elt = SVal.getVectorElt(i); 2679 1.1 joerg llvm::APInt EltAsInt; 2680 1.1 joerg if (Elt.isInt()) { 2681 1.1 joerg EltAsInt = Elt.getInt(); 2682 1.1 joerg } else if (Elt.isFloat()) { 2683 1.1 joerg EltAsInt = Elt.getFloat().bitcastToAPInt(); 2684 1.1 joerg } else { 2685 1.1 joerg // Don't try to handle vectors of anything other than int or float 2686 1.1 joerg // (not sure if it's possible to hit this case). 2687 1.1 joerg Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2688 1.1 joerg return false; 2689 1.1 joerg } 2690 1.1 joerg unsigned BaseEltSize = EltAsInt.getBitWidth(); 2691 1.1 joerg if (BigEndian) 2692 1.1 joerg Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize); 2693 1.1 joerg else 2694 1.1 joerg Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize); 2695 1.1 joerg } 2696 1.1 joerg return true; 2697 1.1 joerg } 2698 1.1 joerg // Give up if the input isn't an int, float, or vector. For example, we 2699 1.1 joerg // reject "(v4i16)(intptr_t)&a". 2700 1.1 joerg Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2701 1.1 joerg return false; 2702 1.1 joerg } 2703 1.1 joerg 2704 1.1 joerg /// Perform the given integer operation, which is known to need at most BitWidth 2705 1.1 joerg /// bits, and check for overflow in the original type (if that type was not an 2706 1.1 joerg /// unsigned type). 2707 1.1 joerg template<typename Operation> 2708 1.1 joerg static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E, 2709 1.1 joerg const APSInt &LHS, const APSInt &RHS, 2710 1.1 joerg unsigned BitWidth, Operation Op, 2711 1.1 joerg APSInt &Result) { 2712 1.1 joerg if (LHS.isUnsigned()) { 2713 1.1 joerg Result = Op(LHS, RHS); 2714 1.1 joerg return true; 2715 1.1 joerg } 2716 1.1 joerg 2717 1.1 joerg APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false); 2718 1.1 joerg Result = Value.trunc(LHS.getBitWidth()); 2719 1.1 joerg if (Result.extend(BitWidth) != Value) { 2720 1.1 joerg if (Info.checkingForUndefinedBehavior()) 2721 1.1 joerg Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 2722 1.1 joerg diag::warn_integer_constant_overflow) 2723 1.1 joerg << Result.toString(10) << E->getType(); 2724 1.1.1.2 joerg return HandleOverflow(Info, E, Value, E->getType()); 2725 1.1 joerg } 2726 1.1 joerg return true; 2727 1.1 joerg } 2728 1.1 joerg 2729 1.1 joerg /// Perform the given binary integer operation. 2730 1.1 joerg static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS, 2731 1.1 joerg BinaryOperatorKind Opcode, APSInt RHS, 2732 1.1 joerg APSInt &Result) { 2733 1.1 joerg switch (Opcode) { 2734 1.1 joerg default: 2735 1.1 joerg Info.FFDiag(E); 2736 1.1 joerg return false; 2737 1.1 joerg case BO_Mul: 2738 1.1 joerg return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2, 2739 1.1 joerg std::multiplies<APSInt>(), Result); 2740 1.1 joerg case BO_Add: 2741 1.1 joerg return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, 2742 1.1 joerg std::plus<APSInt>(), Result); 2743 1.1 joerg case BO_Sub: 2744 1.1 joerg return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, 2745 1.1 joerg std::minus<APSInt>(), Result); 2746 1.1 joerg case BO_And: Result = LHS & RHS; return true; 2747 1.1 joerg case BO_Xor: Result = LHS ^ RHS; return true; 2748 1.1 joerg case BO_Or: Result = LHS | RHS; return true; 2749 1.1 joerg case BO_Div: 2750 1.1 joerg case BO_Rem: 2751 1.1 joerg if (RHS == 0) { 2752 1.1 joerg Info.FFDiag(E, diag::note_expr_divide_by_zero); 2753 1.1 joerg return false; 2754 1.1 joerg } 2755 1.1 joerg Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS); 2756 1.1 joerg // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports 2757 1.1 joerg // this operation and gives the two's complement result. 2758 1.1 joerg if (RHS.isNegative() && RHS.isAllOnesValue() && 2759 1.1 joerg LHS.isSigned() && LHS.isMinSignedValue()) 2760 1.1 joerg return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), 2761 1.1 joerg E->getType()); 2762 1.1 joerg return true; 2763 1.1 joerg case BO_Shl: { 2764 1.1 joerg if (Info.getLangOpts().OpenCL) 2765 1.1 joerg // OpenCL 6.3j: shift values are effectively % word size of LHS. 2766 1.1 joerg RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), 2767 1.1 joerg static_cast<uint64_t>(LHS.getBitWidth() - 1)), 2768 1.1 joerg RHS.isUnsigned()); 2769 1.1 joerg else if (RHS.isSigned() && RHS.isNegative()) { 2770 1.1 joerg // During constant-folding, a negative shift is an opposite shift. Such 2771 1.1 joerg // a shift is not a constant expression. 2772 1.1 joerg Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; 2773 1.1 joerg RHS = -RHS; 2774 1.1 joerg goto shift_right; 2775 1.1 joerg } 2776 1.1 joerg shift_left: 2777 1.1 joerg // C++11 [expr.shift]p1: Shift width must be less than the bit width of 2778 1.1 joerg // the shifted type. 2779 1.1 joerg unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 2780 1.1 joerg if (SA != RHS) { 2781 1.1 joerg Info.CCEDiag(E, diag::note_constexpr_large_shift) 2782 1.1 joerg << RHS << E->getType() << LHS.getBitWidth(); 2783 1.1.1.2 joerg } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) { 2784 1.1 joerg // C++11 [expr.shift]p2: A signed left shift must have a non-negative 2785 1.1 joerg // operand, and must not overflow the corresponding unsigned type. 2786 1.1 joerg // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to 2787 1.1 joerg // E1 x 2^E2 module 2^N. 2788 1.1 joerg if (LHS.isNegative()) 2789 1.1 joerg Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS; 2790 1.1 joerg else if (LHS.countLeadingZeros() < SA) 2791 1.1 joerg Info.CCEDiag(E, diag::note_constexpr_lshift_discards); 2792 1.1 joerg } 2793 1.1 joerg Result = LHS << SA; 2794 1.1 joerg return true; 2795 1.1 joerg } 2796 1.1 joerg case BO_Shr: { 2797 1.1 joerg if (Info.getLangOpts().OpenCL) 2798 1.1 joerg // OpenCL 6.3j: shift values are effectively % word size of LHS. 2799 1.1 joerg RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), 2800 1.1 joerg static_cast<uint64_t>(LHS.getBitWidth() - 1)), 2801 1.1 joerg RHS.isUnsigned()); 2802 1.1 joerg else if (RHS.isSigned() && RHS.isNegative()) { 2803 1.1 joerg // During constant-folding, a negative shift is an opposite shift. Such a 2804 1.1 joerg // shift is not a constant expression. 2805 1.1 joerg Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; 2806 1.1 joerg RHS = -RHS; 2807 1.1 joerg goto shift_left; 2808 1.1 joerg } 2809 1.1 joerg shift_right: 2810 1.1 joerg // C++11 [expr.shift]p1: Shift width must be less than the bit width of the 2811 1.1 joerg // shifted type. 2812 1.1 joerg unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 2813 1.1 joerg if (SA != RHS) 2814 1.1 joerg Info.CCEDiag(E, diag::note_constexpr_large_shift) 2815 1.1 joerg << RHS << E->getType() << LHS.getBitWidth(); 2816 1.1 joerg Result = LHS >> SA; 2817 1.1 joerg return true; 2818 1.1 joerg } 2819 1.1 joerg 2820 1.1 joerg case BO_LT: Result = LHS < RHS; return true; 2821 1.1 joerg case BO_GT: Result = LHS > RHS; return true; 2822 1.1 joerg case BO_LE: Result = LHS <= RHS; return true; 2823 1.1 joerg case BO_GE: Result = LHS >= RHS; return true; 2824 1.1 joerg case BO_EQ: Result = LHS == RHS; return true; 2825 1.1 joerg case BO_NE: Result = LHS != RHS; return true; 2826 1.1 joerg case BO_Cmp: 2827 1.1 joerg llvm_unreachable("BO_Cmp should be handled elsewhere"); 2828 1.1 joerg } 2829 1.1 joerg } 2830 1.1 joerg 2831 1.1 joerg /// Perform the given binary floating-point operation, in-place, on LHS. 2832 1.1.1.2 joerg static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E, 2833 1.1 joerg APFloat &LHS, BinaryOperatorKind Opcode, 2834 1.1 joerg const APFloat &RHS) { 2835 1.1.1.2 joerg bool DynamicRM; 2836 1.1.1.2 joerg llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM); 2837 1.1.1.2 joerg APFloat::opStatus St; 2838 1.1 joerg switch (Opcode) { 2839 1.1 joerg default: 2840 1.1 joerg Info.FFDiag(E); 2841 1.1 joerg return false; 2842 1.1 joerg case BO_Mul: 2843 1.1.1.2 joerg St = LHS.multiply(RHS, RM); 2844 1.1 joerg break; 2845 1.1 joerg case BO_Add: 2846 1.1.1.2 joerg St = LHS.add(RHS, RM); 2847 1.1 joerg break; 2848 1.1 joerg case BO_Sub: 2849 1.1.1.2 joerg St = LHS.subtract(RHS, RM); 2850 1.1 joerg break; 2851 1.1 joerg case BO_Div: 2852 1.1 joerg // [expr.mul]p4: 2853 1.1 joerg // If the second operand of / or % is zero the behavior is undefined. 2854 1.1 joerg if (RHS.isZero()) 2855 1.1 joerg Info.CCEDiag(E, diag::note_expr_divide_by_zero); 2856 1.1.1.2 joerg St = LHS.divide(RHS, RM); 2857 1.1 joerg break; 2858 1.1 joerg } 2859 1.1 joerg 2860 1.1 joerg // [expr.pre]p4: 2861 1.1 joerg // If during the evaluation of an expression, the result is not 2862 1.1 joerg // mathematically defined [...], the behavior is undefined. 2863 1.1 joerg // FIXME: C++ rules require us to not conform to IEEE 754 here. 2864 1.1 joerg if (LHS.isNaN()) { 2865 1.1 joerg Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN(); 2866 1.1 joerg return Info.noteUndefinedBehavior(); 2867 1.1 joerg } 2868 1.1.1.2 joerg 2869 1.1.1.2 joerg return checkFloatingPointResult(Info, E, St); 2870 1.1.1.2 joerg } 2871 1.1.1.2 joerg 2872 1.1.1.2 joerg static bool handleLogicalOpForVector(const APInt &LHSValue, 2873 1.1.1.2 joerg BinaryOperatorKind Opcode, 2874 1.1.1.2 joerg const APInt &RHSValue, APInt &Result) { 2875 1.1.1.2 joerg bool LHS = (LHSValue != 0); 2876 1.1.1.2 joerg bool RHS = (RHSValue != 0); 2877 1.1.1.2 joerg 2878 1.1.1.2 joerg if (Opcode == BO_LAnd) 2879 1.1.1.2 joerg Result = LHS && RHS; 2880 1.1.1.2 joerg else 2881 1.1.1.2 joerg Result = LHS || RHS; 2882 1.1.1.2 joerg return true; 2883 1.1.1.2 joerg } 2884 1.1.1.2 joerg static bool handleLogicalOpForVector(const APFloat &LHSValue, 2885 1.1.1.2 joerg BinaryOperatorKind Opcode, 2886 1.1.1.2 joerg const APFloat &RHSValue, APInt &Result) { 2887 1.1.1.2 joerg bool LHS = !LHSValue.isZero(); 2888 1.1.1.2 joerg bool RHS = !RHSValue.isZero(); 2889 1.1.1.2 joerg 2890 1.1.1.2 joerg if (Opcode == BO_LAnd) 2891 1.1.1.2 joerg Result = LHS && RHS; 2892 1.1.1.2 joerg else 2893 1.1.1.2 joerg Result = LHS || RHS; 2894 1.1.1.2 joerg return true; 2895 1.1.1.2 joerg } 2896 1.1.1.2 joerg 2897 1.1.1.2 joerg static bool handleLogicalOpForVector(const APValue &LHSValue, 2898 1.1.1.2 joerg BinaryOperatorKind Opcode, 2899 1.1.1.2 joerg const APValue &RHSValue, APInt &Result) { 2900 1.1.1.2 joerg // The result is always an int type, however operands match the first. 2901 1.1.1.2 joerg if (LHSValue.getKind() == APValue::Int) 2902 1.1.1.2 joerg return handleLogicalOpForVector(LHSValue.getInt(), Opcode, 2903 1.1.1.2 joerg RHSValue.getInt(), Result); 2904 1.1.1.2 joerg assert(LHSValue.getKind() == APValue::Float && "Should be no other options"); 2905 1.1.1.2 joerg return handleLogicalOpForVector(LHSValue.getFloat(), Opcode, 2906 1.1.1.2 joerg RHSValue.getFloat(), Result); 2907 1.1.1.2 joerg } 2908 1.1.1.2 joerg 2909 1.1.1.2 joerg template <typename APTy> 2910 1.1.1.2 joerg static bool 2911 1.1.1.2 joerg handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode, 2912 1.1.1.2 joerg const APTy &RHSValue, APInt &Result) { 2913 1.1.1.2 joerg switch (Opcode) { 2914 1.1.1.2 joerg default: 2915 1.1.1.2 joerg llvm_unreachable("unsupported binary operator"); 2916 1.1.1.2 joerg case BO_EQ: 2917 1.1.1.2 joerg Result = (LHSValue == RHSValue); 2918 1.1.1.2 joerg break; 2919 1.1.1.2 joerg case BO_NE: 2920 1.1.1.2 joerg Result = (LHSValue != RHSValue); 2921 1.1.1.2 joerg break; 2922 1.1.1.2 joerg case BO_LT: 2923 1.1.1.2 joerg Result = (LHSValue < RHSValue); 2924 1.1.1.2 joerg break; 2925 1.1.1.2 joerg case BO_GT: 2926 1.1.1.2 joerg Result = (LHSValue > RHSValue); 2927 1.1.1.2 joerg break; 2928 1.1.1.2 joerg case BO_LE: 2929 1.1.1.2 joerg Result = (LHSValue <= RHSValue); 2930 1.1.1.2 joerg break; 2931 1.1.1.2 joerg case BO_GE: 2932 1.1.1.2 joerg Result = (LHSValue >= RHSValue); 2933 1.1.1.2 joerg break; 2934 1.1.1.2 joerg } 2935 1.1.1.2 joerg 2936 1.1.1.2 joerg return true; 2937 1.1.1.2 joerg } 2938 1.1.1.2 joerg 2939 1.1.1.2 joerg static bool handleCompareOpForVector(const APValue &LHSValue, 2940 1.1.1.2 joerg BinaryOperatorKind Opcode, 2941 1.1.1.2 joerg const APValue &RHSValue, APInt &Result) { 2942 1.1.1.2 joerg // The result is always an int type, however operands match the first. 2943 1.1.1.2 joerg if (LHSValue.getKind() == APValue::Int) 2944 1.1.1.2 joerg return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode, 2945 1.1.1.2 joerg RHSValue.getInt(), Result); 2946 1.1.1.2 joerg assert(LHSValue.getKind() == APValue::Float && "Should be no other options"); 2947 1.1.1.2 joerg return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode, 2948 1.1.1.2 joerg RHSValue.getFloat(), Result); 2949 1.1.1.2 joerg } 2950 1.1.1.2 joerg 2951 1.1.1.2 joerg // Perform binary operations for vector types, in place on the LHS. 2952 1.1.1.2 joerg static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E, 2953 1.1.1.2 joerg BinaryOperatorKind Opcode, 2954 1.1.1.2 joerg APValue &LHSValue, 2955 1.1.1.2 joerg const APValue &RHSValue) { 2956 1.1.1.2 joerg assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI && 2957 1.1.1.2 joerg "Operation not supported on vector types"); 2958 1.1.1.2 joerg 2959 1.1.1.2 joerg const auto *VT = E->getType()->castAs<VectorType>(); 2960 1.1.1.2 joerg unsigned NumElements = VT->getNumElements(); 2961 1.1.1.2 joerg QualType EltTy = VT->getElementType(); 2962 1.1.1.2 joerg 2963 1.1.1.2 joerg // In the cases (typically C as I've observed) where we aren't evaluating 2964 1.1.1.2 joerg // constexpr but are checking for cases where the LHS isn't yet evaluatable, 2965 1.1.1.2 joerg // just give up. 2966 1.1.1.2 joerg if (!LHSValue.isVector()) { 2967 1.1.1.2 joerg assert(LHSValue.isLValue() && 2968 1.1.1.2 joerg "A vector result that isn't a vector OR uncalculated LValue"); 2969 1.1.1.2 joerg Info.FFDiag(E); 2970 1.1.1.2 joerg return false; 2971 1.1.1.2 joerg } 2972 1.1.1.2 joerg 2973 1.1.1.2 joerg assert(LHSValue.getVectorLength() == NumElements && 2974 1.1.1.2 joerg RHSValue.getVectorLength() == NumElements && "Different vector sizes"); 2975 1.1.1.2 joerg 2976 1.1.1.2 joerg SmallVector<APValue, 4> ResultElements; 2977 1.1.1.2 joerg 2978 1.1.1.2 joerg for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) { 2979 1.1.1.2 joerg APValue LHSElt = LHSValue.getVectorElt(EltNum); 2980 1.1.1.2 joerg APValue RHSElt = RHSValue.getVectorElt(EltNum); 2981 1.1.1.2 joerg 2982 1.1.1.2 joerg if (EltTy->isIntegerType()) { 2983 1.1.1.2 joerg APSInt EltResult{Info.Ctx.getIntWidth(EltTy), 2984 1.1.1.2 joerg EltTy->isUnsignedIntegerType()}; 2985 1.1.1.2 joerg bool Success = true; 2986 1.1.1.2 joerg 2987 1.1.1.2 joerg if (BinaryOperator::isLogicalOp(Opcode)) 2988 1.1.1.2 joerg Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult); 2989 1.1.1.2 joerg else if (BinaryOperator::isComparisonOp(Opcode)) 2990 1.1.1.2 joerg Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult); 2991 1.1.1.2 joerg else 2992 1.1.1.2 joerg Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode, 2993 1.1.1.2 joerg RHSElt.getInt(), EltResult); 2994 1.1.1.2 joerg 2995 1.1.1.2 joerg if (!Success) { 2996 1.1.1.2 joerg Info.FFDiag(E); 2997 1.1.1.2 joerg return false; 2998 1.1.1.2 joerg } 2999 1.1.1.2 joerg ResultElements.emplace_back(EltResult); 3000 1.1.1.2 joerg 3001 1.1.1.2 joerg } else if (EltTy->isFloatingType()) { 3002 1.1.1.2 joerg assert(LHSElt.getKind() == APValue::Float && 3003 1.1.1.2 joerg RHSElt.getKind() == APValue::Float && 3004 1.1.1.2 joerg "Mismatched LHS/RHS/Result Type"); 3005 1.1.1.2 joerg APFloat LHSFloat = LHSElt.getFloat(); 3006 1.1.1.2 joerg 3007 1.1.1.2 joerg if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode, 3008 1.1.1.2 joerg RHSElt.getFloat())) { 3009 1.1.1.2 joerg Info.FFDiag(E); 3010 1.1.1.2 joerg return false; 3011 1.1.1.2 joerg } 3012 1.1.1.2 joerg 3013 1.1.1.2 joerg ResultElements.emplace_back(LHSFloat); 3014 1.1.1.2 joerg } 3015 1.1.1.2 joerg } 3016 1.1.1.2 joerg 3017 1.1.1.2 joerg LHSValue = APValue(ResultElements.data(), ResultElements.size()); 3018 1.1 joerg return true; 3019 1.1 joerg } 3020 1.1 joerg 3021 1.1 joerg /// Cast an lvalue referring to a base subobject to a derived class, by 3022 1.1 joerg /// truncating the lvalue's path to the given length. 3023 1.1 joerg static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result, 3024 1.1 joerg const RecordDecl *TruncatedType, 3025 1.1 joerg unsigned TruncatedElements) { 3026 1.1 joerg SubobjectDesignator &D = Result.Designator; 3027 1.1 joerg 3028 1.1 joerg // Check we actually point to a derived class object. 3029 1.1 joerg if (TruncatedElements == D.Entries.size()) 3030 1.1 joerg return true; 3031 1.1 joerg assert(TruncatedElements >= D.MostDerivedPathLength && 3032 1.1 joerg "not casting to a derived class"); 3033 1.1 joerg if (!Result.checkSubobject(Info, E, CSK_Derived)) 3034 1.1 joerg return false; 3035 1.1 joerg 3036 1.1 joerg // Truncate the path to the subobject, and remove any derived-to-base offsets. 3037 1.1 joerg const RecordDecl *RD = TruncatedType; 3038 1.1 joerg for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) { 3039 1.1 joerg if (RD->isInvalidDecl()) return false; 3040 1.1 joerg const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 3041 1.1 joerg const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]); 3042 1.1 joerg if (isVirtualBaseClass(D.Entries[I])) 3043 1.1 joerg Result.Offset -= Layout.getVBaseClassOffset(Base); 3044 1.1 joerg else 3045 1.1 joerg Result.Offset -= Layout.getBaseClassOffset(Base); 3046 1.1 joerg RD = Base; 3047 1.1 joerg } 3048 1.1 joerg D.Entries.resize(TruncatedElements); 3049 1.1 joerg return true; 3050 1.1 joerg } 3051 1.1 joerg 3052 1.1 joerg static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj, 3053 1.1 joerg const CXXRecordDecl *Derived, 3054 1.1 joerg const CXXRecordDecl *Base, 3055 1.1 joerg const ASTRecordLayout *RL = nullptr) { 3056 1.1 joerg if (!RL) { 3057 1.1 joerg if (Derived->isInvalidDecl()) return false; 3058 1.1 joerg RL = &Info.Ctx.getASTRecordLayout(Derived); 3059 1.1 joerg } 3060 1.1 joerg 3061 1.1 joerg Obj.getLValueOffset() += RL->getBaseClassOffset(Base); 3062 1.1 joerg Obj.addDecl(Info, E, Base, /*Virtual*/ false); 3063 1.1 joerg return true; 3064 1.1 joerg } 3065 1.1 joerg 3066 1.1 joerg static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj, 3067 1.1 joerg const CXXRecordDecl *DerivedDecl, 3068 1.1 joerg const CXXBaseSpecifier *Base) { 3069 1.1 joerg const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 3070 1.1 joerg 3071 1.1 joerg if (!Base->isVirtual()) 3072 1.1 joerg return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl); 3073 1.1 joerg 3074 1.1 joerg SubobjectDesignator &D = Obj.Designator; 3075 1.1 joerg if (D.Invalid) 3076 1.1 joerg return false; 3077 1.1 joerg 3078 1.1 joerg // Extract most-derived object and corresponding type. 3079 1.1 joerg DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl(); 3080 1.1 joerg if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength)) 3081 1.1 joerg return false; 3082 1.1 joerg 3083 1.1 joerg // Find the virtual base class. 3084 1.1 joerg if (DerivedDecl->isInvalidDecl()) return false; 3085 1.1 joerg const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl); 3086 1.1 joerg Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl); 3087 1.1 joerg Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true); 3088 1.1 joerg return true; 3089 1.1 joerg } 3090 1.1 joerg 3091 1.1 joerg static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E, 3092 1.1 joerg QualType Type, LValue &Result) { 3093 1.1 joerg for (CastExpr::path_const_iterator PathI = E->path_begin(), 3094 1.1 joerg PathE = E->path_end(); 3095 1.1 joerg PathI != PathE; ++PathI) { 3096 1.1 joerg if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(), 3097 1.1 joerg *PathI)) 3098 1.1 joerg return false; 3099 1.1 joerg Type = (*PathI)->getType(); 3100 1.1 joerg } 3101 1.1 joerg return true; 3102 1.1 joerg } 3103 1.1 joerg 3104 1.1 joerg /// Cast an lvalue referring to a derived class to a known base subobject. 3105 1.1 joerg static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result, 3106 1.1 joerg const CXXRecordDecl *DerivedRD, 3107 1.1 joerg const CXXRecordDecl *BaseRD) { 3108 1.1 joerg CXXBasePaths Paths(/*FindAmbiguities=*/false, 3109 1.1 joerg /*RecordPaths=*/true, /*DetectVirtual=*/false); 3110 1.1 joerg if (!DerivedRD->isDerivedFrom(BaseRD, Paths)) 3111 1.1 joerg llvm_unreachable("Class must be derived from the passed in base class!"); 3112 1.1 joerg 3113 1.1 joerg for (CXXBasePathElement &Elem : Paths.front()) 3114 1.1 joerg if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base)) 3115 1.1 joerg return false; 3116 1.1 joerg return true; 3117 1.1 joerg } 3118 1.1 joerg 3119 1.1 joerg /// Update LVal to refer to the given field, which must be a member of the type 3120 1.1 joerg /// currently described by LVal. 3121 1.1 joerg static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal, 3122 1.1 joerg const FieldDecl *FD, 3123 1.1 joerg const ASTRecordLayout *RL = nullptr) { 3124 1.1 joerg if (!RL) { 3125 1.1 joerg if (FD->getParent()->isInvalidDecl()) return false; 3126 1.1 joerg RL = &Info.Ctx.getASTRecordLayout(FD->getParent()); 3127 1.1 joerg } 3128 1.1 joerg 3129 1.1 joerg unsigned I = FD->getFieldIndex(); 3130 1.1 joerg LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I))); 3131 1.1 joerg LVal.addDecl(Info, E, FD); 3132 1.1 joerg return true; 3133 1.1 joerg } 3134 1.1 joerg 3135 1.1 joerg /// Update LVal to refer to the given indirect field. 3136 1.1 joerg static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E, 3137 1.1 joerg LValue &LVal, 3138 1.1 joerg const IndirectFieldDecl *IFD) { 3139 1.1 joerg for (const auto *C : IFD->chain()) 3140 1.1 joerg if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C))) 3141 1.1 joerg return false; 3142 1.1 joerg return true; 3143 1.1 joerg } 3144 1.1 joerg 3145 1.1 joerg /// Get the size of the given type in char units. 3146 1.1 joerg static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, 3147 1.1 joerg QualType Type, CharUnits &Size) { 3148 1.1 joerg // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc 3149 1.1 joerg // extension. 3150 1.1 joerg if (Type->isVoidType() || Type->isFunctionType()) { 3151 1.1 joerg Size = CharUnits::One(); 3152 1.1 joerg return true; 3153 1.1 joerg } 3154 1.1 joerg 3155 1.1 joerg if (Type->isDependentType()) { 3156 1.1 joerg Info.FFDiag(Loc); 3157 1.1 joerg return false; 3158 1.1 joerg } 3159 1.1 joerg 3160 1.1 joerg if (!Type->isConstantSizeType()) { 3161 1.1 joerg // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2. 3162 1.1 joerg // FIXME: Better diagnostic. 3163 1.1 joerg Info.FFDiag(Loc); 3164 1.1 joerg return false; 3165 1.1 joerg } 3166 1.1 joerg 3167 1.1 joerg Size = Info.Ctx.getTypeSizeInChars(Type); 3168 1.1 joerg return true; 3169 1.1 joerg } 3170 1.1 joerg 3171 1.1 joerg /// Update a pointer value to model pointer arithmetic. 3172 1.1 joerg /// \param Info - Information about the ongoing evaluation. 3173 1.1 joerg /// \param E - The expression being evaluated, for diagnostic purposes. 3174 1.1 joerg /// \param LVal - The pointer value to be updated. 3175 1.1 joerg /// \param EltTy - The pointee type represented by LVal. 3176 1.1 joerg /// \param Adjustment - The adjustment, in objects of type EltTy, to add. 3177 1.1 joerg static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, 3178 1.1 joerg LValue &LVal, QualType EltTy, 3179 1.1 joerg APSInt Adjustment) { 3180 1.1 joerg CharUnits SizeOfPointee; 3181 1.1 joerg if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee)) 3182 1.1 joerg return false; 3183 1.1 joerg 3184 1.1 joerg LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee); 3185 1.1 joerg return true; 3186 1.1 joerg } 3187 1.1 joerg 3188 1.1 joerg static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, 3189 1.1 joerg LValue &LVal, QualType EltTy, 3190 1.1 joerg int64_t Adjustment) { 3191 1.1 joerg return HandleLValueArrayAdjustment(Info, E, LVal, EltTy, 3192 1.1 joerg APSInt::get(Adjustment)); 3193 1.1 joerg } 3194 1.1 joerg 3195 1.1 joerg /// Update an lvalue to refer to a component of a complex number. 3196 1.1 joerg /// \param Info - Information about the ongoing evaluation. 3197 1.1 joerg /// \param LVal - The lvalue to be updated. 3198 1.1 joerg /// \param EltTy - The complex number's component type. 3199 1.1 joerg /// \param Imag - False for the real component, true for the imaginary. 3200 1.1 joerg static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E, 3201 1.1 joerg LValue &LVal, QualType EltTy, 3202 1.1 joerg bool Imag) { 3203 1.1 joerg if (Imag) { 3204 1.1 joerg CharUnits SizeOfComponent; 3205 1.1 joerg if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent)) 3206 1.1 joerg return false; 3207 1.1 joerg LVal.Offset += SizeOfComponent; 3208 1.1 joerg } 3209 1.1 joerg LVal.addComplex(Info, E, EltTy, Imag); 3210 1.1 joerg return true; 3211 1.1 joerg } 3212 1.1 joerg 3213 1.1 joerg /// Try to evaluate the initializer for a variable declaration. 3214 1.1 joerg /// 3215 1.1 joerg /// \param Info Information about the ongoing evaluation. 3216 1.1 joerg /// \param E An expression to be used when printing diagnostics. 3217 1.1 joerg /// \param VD The variable whose initializer should be obtained. 3218 1.1.1.2 joerg /// \param Version The version of the variable within the frame. 3219 1.1 joerg /// \param Frame The frame in which the variable was created. Must be null 3220 1.1 joerg /// if this variable is not local to the evaluation. 3221 1.1 joerg /// \param Result Filled in with a pointer to the value of the variable. 3222 1.1 joerg static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E, 3223 1.1 joerg const VarDecl *VD, CallStackFrame *Frame, 3224 1.1.1.2 joerg unsigned Version, APValue *&Result) { 3225 1.1.1.2 joerg APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version); 3226 1.1 joerg 3227 1.1 joerg // If this is a local variable, dig out its value. 3228 1.1 joerg if (Frame) { 3229 1.1.1.2 joerg Result = Frame->getTemporary(VD, Version); 3230 1.1.1.2 joerg if (Result) 3231 1.1.1.2 joerg return true; 3232 1.1.1.2 joerg 3233 1.1.1.2 joerg if (!isa<ParmVarDecl>(VD)) { 3234 1.1 joerg // Assume variables referenced within a lambda's call operator that were 3235 1.1 joerg // not declared within the call operator are captures and during checking 3236 1.1 joerg // of a potential constant expression, assume they are unknown constant 3237 1.1 joerg // expressions. 3238 1.1 joerg assert(isLambdaCallOperator(Frame->Callee) && 3239 1.1 joerg (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) && 3240 1.1 joerg "missing value for local variable"); 3241 1.1 joerg if (Info.checkingPotentialConstantExpression()) 3242 1.1 joerg return false; 3243 1.1.1.2 joerg // FIXME: This diagnostic is bogus; we do support captures. Is this code 3244 1.1.1.2 joerg // still reachable at all? 3245 1.1 joerg Info.FFDiag(E->getBeginLoc(), 3246 1.1 joerg diag::note_unimplemented_constexpr_lambda_feature_ast) 3247 1.1 joerg << "captures not currently allowed"; 3248 1.1 joerg return false; 3249 1.1 joerg } 3250 1.1 joerg } 3251 1.1 joerg 3252 1.1 joerg // If we're currently evaluating the initializer of this declaration, use that 3253 1.1 joerg // in-flight value. 3254 1.1.1.2 joerg if (Info.EvaluatingDecl == Base) { 3255 1.1 joerg Result = Info.EvaluatingDeclValue; 3256 1.1 joerg return true; 3257 1.1 joerg } 3258 1.1 joerg 3259 1.1.1.2 joerg if (isa<ParmVarDecl>(VD)) { 3260 1.1.1.2 joerg // Assume parameters of a potential constant expression are usable in 3261 1.1.1.2 joerg // constant expressions. 3262 1.1.1.2 joerg if (!Info.checkingPotentialConstantExpression() || 3263 1.1.1.2 joerg !Info.CurrentCall->Callee || 3264 1.1.1.2 joerg !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) { 3265 1.1.1.2 joerg if (Info.getLangOpts().CPlusPlus11) { 3266 1.1.1.2 joerg Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown) 3267 1.1.1.2 joerg << VD; 3268 1.1.1.2 joerg NoteLValueLocation(Info, Base); 3269 1.1.1.2 joerg } else { 3270 1.1.1.2 joerg Info.FFDiag(E); 3271 1.1.1.2 joerg } 3272 1.1.1.2 joerg } 3273 1.1.1.2 joerg return false; 3274 1.1.1.2 joerg } 3275 1.1.1.2 joerg 3276 1.1.1.2 joerg // Dig out the initializer, and use the declaration which it's attached to. 3277 1.1.1.2 joerg // FIXME: We should eventually check whether the variable has a reachable 3278 1.1.1.2 joerg // initializing declaration. 3279 1.1.1.2 joerg const Expr *Init = VD->getAnyInitializer(VD); 3280 1.1.1.2 joerg if (!Init) { 3281 1.1.1.2 joerg // Don't diagnose during potential constant expression checking; an 3282 1.1.1.2 joerg // initializer might be added later. 3283 1.1.1.2 joerg if (!Info.checkingPotentialConstantExpression()) { 3284 1.1.1.2 joerg Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1) 3285 1.1.1.2 joerg << VD; 3286 1.1.1.2 joerg NoteLValueLocation(Info, Base); 3287 1.1.1.2 joerg } 3288 1.1.1.2 joerg return false; 3289 1.1.1.2 joerg } 3290 1.1.1.2 joerg 3291 1.1.1.2 joerg if (Init->isValueDependent()) { 3292 1.1.1.2 joerg // The DeclRefExpr is not value-dependent, but the variable it refers to 3293 1.1.1.2 joerg // has a value-dependent initializer. This should only happen in 3294 1.1.1.2 joerg // constant-folding cases, where the variable is not actually of a suitable 3295 1.1.1.2 joerg // type for use in a constant expression (otherwise the DeclRefExpr would 3296 1.1.1.2 joerg // have been value-dependent too), so diagnose that. 3297 1.1.1.2 joerg assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx)); 3298 1.1.1.2 joerg if (!Info.checkingPotentialConstantExpression()) { 3299 1.1.1.2 joerg Info.FFDiag(E, Info.getLangOpts().CPlusPlus11 3300 1.1.1.2 joerg ? diag::note_constexpr_ltor_non_constexpr 3301 1.1.1.2 joerg : diag::note_constexpr_ltor_non_integral, 1) 3302 1.1.1.2 joerg << VD << VD->getType(); 3303 1.1.1.2 joerg NoteLValueLocation(Info, Base); 3304 1.1.1.2 joerg } 3305 1.1 joerg return false; 3306 1.1 joerg } 3307 1.1 joerg 3308 1.1 joerg // Check that we can fold the initializer. In C++, we will have already done 3309 1.1 joerg // this in the cases where it matters for conformance. 3310 1.1.1.2 joerg if (!VD->evaluateValue()) { 3311 1.1.1.2 joerg Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD; 3312 1.1.1.2 joerg NoteLValueLocation(Info, Base); 3313 1.1.1.2 joerg return false; 3314 1.1.1.2 joerg } 3315 1.1.1.2 joerg 3316 1.1.1.2 joerg // Check that the variable is actually usable in constant expressions. For a 3317 1.1.1.2 joerg // const integral variable or a reference, we might have a non-constant 3318 1.1.1.2 joerg // initializer that we can nonetheless evaluate the initializer for. Such 3319 1.1.1.2 joerg // variables are not usable in constant expressions. In C++98, the 3320 1.1.1.2 joerg // initializer also syntactically needs to be an ICE. 3321 1.1.1.2 joerg // 3322 1.1.1.2 joerg // FIXME: We don't diagnose cases that aren't potentially usable in constant 3323 1.1.1.2 joerg // expressions here; doing so would regress diagnostics for things like 3324 1.1.1.2 joerg // reading from a volatile constexpr variable. 3325 1.1.1.2 joerg if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() && 3326 1.1.1.2 joerg VD->mightBeUsableInConstantExpressions(Info.Ctx)) || 3327 1.1.1.2 joerg ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) && 3328 1.1.1.2 joerg !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) { 3329 1.1.1.2 joerg Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD; 3330 1.1.1.2 joerg NoteLValueLocation(Info, Base); 3331 1.1.1.2 joerg } 3332 1.1.1.2 joerg 3333 1.1.1.2 joerg // Never use the initializer of a weak variable, not even for constant 3334 1.1.1.2 joerg // folding. We can't be sure that this is the definition that will be used. 3335 1.1.1.2 joerg if (VD->isWeak()) { 3336 1.1.1.2 joerg Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD; 3337 1.1.1.2 joerg NoteLValueLocation(Info, Base); 3338 1.1 joerg return false; 3339 1.1 joerg } 3340 1.1 joerg 3341 1.1 joerg Result = VD->getEvaluatedValue(); 3342 1.1 joerg return true; 3343 1.1 joerg } 3344 1.1 joerg 3345 1.1 joerg /// Get the base index of the given base class within an APValue representing 3346 1.1 joerg /// the given derived class. 3347 1.1 joerg static unsigned getBaseIndex(const CXXRecordDecl *Derived, 3348 1.1 joerg const CXXRecordDecl *Base) { 3349 1.1 joerg Base = Base->getCanonicalDecl(); 3350 1.1 joerg unsigned Index = 0; 3351 1.1 joerg for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(), 3352 1.1 joerg E = Derived->bases_end(); I != E; ++I, ++Index) { 3353 1.1 joerg if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base) 3354 1.1 joerg return Index; 3355 1.1 joerg } 3356 1.1 joerg 3357 1.1 joerg llvm_unreachable("base class missing from derived class's bases list"); 3358 1.1 joerg } 3359 1.1 joerg 3360 1.1 joerg /// Extract the value of a character from a string literal. 3361 1.1 joerg static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit, 3362 1.1 joerg uint64_t Index) { 3363 1.1 joerg assert(!isa<SourceLocExpr>(Lit) && 3364 1.1 joerg "SourceLocExpr should have already been converted to a StringLiteral"); 3365 1.1 joerg 3366 1.1 joerg // FIXME: Support MakeStringConstant 3367 1.1 joerg if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) { 3368 1.1 joerg std::string Str; 3369 1.1 joerg Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str); 3370 1.1 joerg assert(Index <= Str.size() && "Index too large"); 3371 1.1 joerg return APSInt::getUnsigned(Str.c_str()[Index]); 3372 1.1 joerg } 3373 1.1 joerg 3374 1.1 joerg if (auto PE = dyn_cast<PredefinedExpr>(Lit)) 3375 1.1 joerg Lit = PE->getFunctionName(); 3376 1.1 joerg const StringLiteral *S = cast<StringLiteral>(Lit); 3377 1.1 joerg const ConstantArrayType *CAT = 3378 1.1 joerg Info.Ctx.getAsConstantArrayType(S->getType()); 3379 1.1 joerg assert(CAT && "string literal isn't an array"); 3380 1.1 joerg QualType CharType = CAT->getElementType(); 3381 1.1 joerg assert(CharType->isIntegerType() && "unexpected character type"); 3382 1.1 joerg 3383 1.1 joerg APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), 3384 1.1 joerg CharType->isUnsignedIntegerType()); 3385 1.1 joerg if (Index < S->getLength()) 3386 1.1 joerg Value = S->getCodeUnit(Index); 3387 1.1 joerg return Value; 3388 1.1 joerg } 3389 1.1 joerg 3390 1.1 joerg // Expand a string literal into an array of characters. 3391 1.1 joerg // 3392 1.1 joerg // FIXME: This is inefficient; we should probably introduce something similar 3393 1.1 joerg // to the LLVM ConstantDataArray to make this cheaper. 3394 1.1 joerg static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S, 3395 1.1 joerg APValue &Result, 3396 1.1 joerg QualType AllocType = QualType()) { 3397 1.1 joerg const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType( 3398 1.1 joerg AllocType.isNull() ? S->getType() : AllocType); 3399 1.1 joerg assert(CAT && "string literal isn't an array"); 3400 1.1 joerg QualType CharType = CAT->getElementType(); 3401 1.1 joerg assert(CharType->isIntegerType() && "unexpected character type"); 3402 1.1 joerg 3403 1.1 joerg unsigned Elts = CAT->getSize().getZExtValue(); 3404 1.1 joerg Result = APValue(APValue::UninitArray(), 3405 1.1 joerg std::min(S->getLength(), Elts), Elts); 3406 1.1 joerg APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), 3407 1.1 joerg CharType->isUnsignedIntegerType()); 3408 1.1 joerg if (Result.hasArrayFiller()) 3409 1.1 joerg Result.getArrayFiller() = APValue(Value); 3410 1.1 joerg for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) { 3411 1.1 joerg Value = S->getCodeUnit(I); 3412 1.1 joerg Result.getArrayInitializedElt(I) = APValue(Value); 3413 1.1 joerg } 3414 1.1 joerg } 3415 1.1 joerg 3416 1.1 joerg // Expand an array so that it has more than Index filled elements. 3417 1.1 joerg static void expandArray(APValue &Array, unsigned Index) { 3418 1.1 joerg unsigned Size = Array.getArraySize(); 3419 1.1 joerg assert(Index < Size); 3420 1.1 joerg 3421 1.1 joerg // Always at least double the number of elements for which we store a value. 3422 1.1 joerg unsigned OldElts = Array.getArrayInitializedElts(); 3423 1.1 joerg unsigned NewElts = std::max(Index+1, OldElts * 2); 3424 1.1 joerg NewElts = std::min(Size, std::max(NewElts, 8u)); 3425 1.1 joerg 3426 1.1 joerg // Copy the data across. 3427 1.1 joerg APValue NewValue(APValue::UninitArray(), NewElts, Size); 3428 1.1 joerg for (unsigned I = 0; I != OldElts; ++I) 3429 1.1 joerg NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I)); 3430 1.1 joerg for (unsigned I = OldElts; I != NewElts; ++I) 3431 1.1 joerg NewValue.getArrayInitializedElt(I) = Array.getArrayFiller(); 3432 1.1 joerg if (NewValue.hasArrayFiller()) 3433 1.1 joerg NewValue.getArrayFiller() = Array.getArrayFiller(); 3434 1.1 joerg Array.swap(NewValue); 3435 1.1 joerg } 3436 1.1 joerg 3437 1.1 joerg /// Determine whether a type would actually be read by an lvalue-to-rvalue 3438 1.1 joerg /// conversion. If it's of class type, we may assume that the copy operation 3439 1.1 joerg /// is trivial. Note that this is never true for a union type with fields 3440 1.1 joerg /// (because the copy always "reads" the active member) and always true for 3441 1.1 joerg /// a non-class type. 3442 1.1.1.2 joerg static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD); 3443 1.1 joerg static bool isReadByLvalueToRvalueConversion(QualType T) { 3444 1.1 joerg CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 3445 1.1.1.2 joerg return !RD || isReadByLvalueToRvalueConversion(RD); 3446 1.1.1.2 joerg } 3447 1.1.1.2 joerg static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) { 3448 1.1.1.2 joerg // FIXME: A trivial copy of a union copies the object representation, even if 3449 1.1.1.2 joerg // the union is empty. 3450 1.1.1.2 joerg if (RD->isUnion()) 3451 1.1.1.2 joerg return !RD->field_empty(); 3452 1.1 joerg if (RD->isEmpty()) 3453 1.1 joerg return false; 3454 1.1 joerg 3455 1.1 joerg for (auto *Field : RD->fields()) 3456 1.1.1.2 joerg if (!Field->isUnnamedBitfield() && 3457 1.1.1.2 joerg isReadByLvalueToRvalueConversion(Field->getType())) 3458 1.1 joerg return true; 3459 1.1 joerg 3460 1.1 joerg for (auto &BaseSpec : RD->bases()) 3461 1.1 joerg if (isReadByLvalueToRvalueConversion(BaseSpec.getType())) 3462 1.1 joerg return true; 3463 1.1 joerg 3464 1.1 joerg return false; 3465 1.1 joerg } 3466 1.1 joerg 3467 1.1 joerg /// Diagnose an attempt to read from any unreadable field within the specified 3468 1.1 joerg /// type, which might be a class type. 3469 1.1 joerg static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK, 3470 1.1 joerg QualType T) { 3471 1.1 joerg CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 3472 1.1 joerg if (!RD) 3473 1.1 joerg return false; 3474 1.1 joerg 3475 1.1 joerg if (!RD->hasMutableFields()) 3476 1.1 joerg return false; 3477 1.1 joerg 3478 1.1 joerg for (auto *Field : RD->fields()) { 3479 1.1 joerg // If we're actually going to read this field in some way, then it can't 3480 1.1 joerg // be mutable. If we're in a union, then assigning to a mutable field 3481 1.1 joerg // (even an empty one) can change the active member, so that's not OK. 3482 1.1 joerg // FIXME: Add core issue number for the union case. 3483 1.1 joerg if (Field->isMutable() && 3484 1.1 joerg (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) { 3485 1.1 joerg Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field; 3486 1.1 joerg Info.Note(Field->getLocation(), diag::note_declared_at); 3487 1.1 joerg return true; 3488 1.1 joerg } 3489 1.1 joerg 3490 1.1 joerg if (diagnoseMutableFields(Info, E, AK, Field->getType())) 3491 1.1 joerg return true; 3492 1.1 joerg } 3493 1.1 joerg 3494 1.1 joerg for (auto &BaseSpec : RD->bases()) 3495 1.1 joerg if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType())) 3496 1.1 joerg return true; 3497 1.1 joerg 3498 1.1 joerg // All mutable fields were empty, and thus not actually read. 3499 1.1 joerg return false; 3500 1.1 joerg } 3501 1.1 joerg 3502 1.1 joerg static bool lifetimeStartedInEvaluation(EvalInfo &Info, 3503 1.1 joerg APValue::LValueBase Base, 3504 1.1 joerg bool MutableSubobject = false) { 3505 1.1.1.2 joerg // A temporary or transient heap allocation we created. 3506 1.1.1.2 joerg if (Base.getCallIndex() || Base.is<DynamicAllocLValue>()) 3507 1.1 joerg return true; 3508 1.1 joerg 3509 1.1 joerg switch (Info.IsEvaluatingDecl) { 3510 1.1 joerg case EvalInfo::EvaluatingDeclKind::None: 3511 1.1 joerg return false; 3512 1.1 joerg 3513 1.1 joerg case EvalInfo::EvaluatingDeclKind::Ctor: 3514 1.1 joerg // The variable whose initializer we're evaluating. 3515 1.1.1.2 joerg if (Info.EvaluatingDecl == Base) 3516 1.1.1.2 joerg return true; 3517 1.1 joerg 3518 1.1 joerg // A temporary lifetime-extended by the variable whose initializer we're 3519 1.1 joerg // evaluating. 3520 1.1 joerg if (auto *BaseE = Base.dyn_cast<const Expr *>()) 3521 1.1 joerg if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE)) 3522 1.1.1.2 joerg return Info.EvaluatingDecl == BaseMTE->getExtendingDecl(); 3523 1.1 joerg return false; 3524 1.1 joerg 3525 1.1 joerg case EvalInfo::EvaluatingDeclKind::Dtor: 3526 1.1 joerg // C++2a [expr.const]p6: 3527 1.1 joerg // [during constant destruction] the lifetime of a and its non-mutable 3528 1.1 joerg // subobjects (but not its mutable subobjects) [are] considered to start 3529 1.1 joerg // within e. 3530 1.1.1.2 joerg if (MutableSubobject || Base != Info.EvaluatingDecl) 3531 1.1.1.2 joerg return false; 3532 1.1 joerg // FIXME: We can meaningfully extend this to cover non-const objects, but 3533 1.1 joerg // we will need special handling: we should be able to access only 3534 1.1 joerg // subobjects of such objects that are themselves declared const. 3535 1.1.1.2 joerg QualType T = getType(Base); 3536 1.1.1.2 joerg return T.isConstQualified() || T->isReferenceType(); 3537 1.1 joerg } 3538 1.1 joerg 3539 1.1 joerg llvm_unreachable("unknown evaluating decl kind"); 3540 1.1 joerg } 3541 1.1 joerg 3542 1.1 joerg namespace { 3543 1.1 joerg /// A handle to a complete object (an object that is not a subobject of 3544 1.1 joerg /// another object). 3545 1.1 joerg struct CompleteObject { 3546 1.1 joerg /// The identity of the object. 3547 1.1 joerg APValue::LValueBase Base; 3548 1.1 joerg /// The value of the complete object. 3549 1.1 joerg APValue *Value; 3550 1.1 joerg /// The type of the complete object. 3551 1.1 joerg QualType Type; 3552 1.1 joerg 3553 1.1 joerg CompleteObject() : Value(nullptr) {} 3554 1.1 joerg CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type) 3555 1.1 joerg : Base(Base), Value(Value), Type(Type) {} 3556 1.1 joerg 3557 1.1 joerg bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const { 3558 1.1.1.2 joerg // If this isn't a "real" access (eg, if it's just accessing the type 3559 1.1.1.2 joerg // info), allow it. We assume the type doesn't change dynamically for 3560 1.1.1.2 joerg // subobjects of constexpr objects (even though we'd hit UB here if it 3561 1.1.1.2 joerg // did). FIXME: Is this right? 3562 1.1.1.2 joerg if (!isAnyAccess(AK)) 3563 1.1.1.2 joerg return true; 3564 1.1.1.2 joerg 3565 1.1 joerg // In C++14 onwards, it is permitted to read a mutable member whose 3566 1.1 joerg // lifetime began within the evaluation. 3567 1.1 joerg // FIXME: Should we also allow this in C++11? 3568 1.1 joerg if (!Info.getLangOpts().CPlusPlus14) 3569 1.1 joerg return false; 3570 1.1 joerg return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true); 3571 1.1 joerg } 3572 1.1 joerg 3573 1.1 joerg explicit operator bool() const { return !Type.isNull(); } 3574 1.1 joerg }; 3575 1.1 joerg } // end anonymous namespace 3576 1.1 joerg 3577 1.1 joerg static QualType getSubobjectType(QualType ObjType, QualType SubobjType, 3578 1.1 joerg bool IsMutable = false) { 3579 1.1 joerg // C++ [basic.type.qualifier]p1: 3580 1.1 joerg // - A const object is an object of type const T or a non-mutable subobject 3581 1.1 joerg // of a const object. 3582 1.1 joerg if (ObjType.isConstQualified() && !IsMutable) 3583 1.1 joerg SubobjType.addConst(); 3584 1.1 joerg // - A volatile object is an object of type const T or a subobject of a 3585 1.1 joerg // volatile object. 3586 1.1 joerg if (ObjType.isVolatileQualified()) 3587 1.1 joerg SubobjType.addVolatile(); 3588 1.1 joerg return SubobjType; 3589 1.1 joerg } 3590 1.1 joerg 3591 1.1 joerg /// Find the designated sub-object of an rvalue. 3592 1.1 joerg template<typename SubobjectHandler> 3593 1.1 joerg typename SubobjectHandler::result_type 3594 1.1 joerg findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, 3595 1.1 joerg const SubobjectDesignator &Sub, SubobjectHandler &handler) { 3596 1.1 joerg if (Sub.Invalid) 3597 1.1 joerg // A diagnostic will have already been produced. 3598 1.1 joerg return handler.failed(); 3599 1.1 joerg if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) { 3600 1.1 joerg if (Info.getLangOpts().CPlusPlus11) 3601 1.1 joerg Info.FFDiag(E, Sub.isOnePastTheEnd() 3602 1.1 joerg ? diag::note_constexpr_access_past_end 3603 1.1 joerg : diag::note_constexpr_access_unsized_array) 3604 1.1 joerg << handler.AccessKind; 3605 1.1 joerg else 3606 1.1 joerg Info.FFDiag(E); 3607 1.1 joerg return handler.failed(); 3608 1.1 joerg } 3609 1.1 joerg 3610 1.1 joerg APValue *O = Obj.Value; 3611 1.1 joerg QualType ObjType = Obj.Type; 3612 1.1 joerg const FieldDecl *LastField = nullptr; 3613 1.1 joerg const FieldDecl *VolatileField = nullptr; 3614 1.1 joerg 3615 1.1 joerg // Walk the designator's path to find the subobject. 3616 1.1 joerg for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) { 3617 1.1 joerg // Reading an indeterminate value is undefined, but assigning over one is OK. 3618 1.1 joerg if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) || 3619 1.1.1.2 joerg (O->isIndeterminate() && 3620 1.1.1.2 joerg !isValidIndeterminateAccess(handler.AccessKind))) { 3621 1.1 joerg if (!Info.checkingPotentialConstantExpression()) 3622 1.1 joerg Info.FFDiag(E, diag::note_constexpr_access_uninit) 3623 1.1 joerg << handler.AccessKind << O->isIndeterminate(); 3624 1.1 joerg return handler.failed(); 3625 1.1 joerg } 3626 1.1 joerg 3627 1.1 joerg // C++ [class.ctor]p5, C++ [class.dtor]p5: 3628 1.1 joerg // const and volatile semantics are not applied on an object under 3629 1.1 joerg // {con,de}struction. 3630 1.1 joerg if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) && 3631 1.1 joerg ObjType->isRecordType() && 3632 1.1 joerg Info.isEvaluatingCtorDtor( 3633 1.1 joerg Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(), 3634 1.1 joerg Sub.Entries.begin() + I)) != 3635 1.1 joerg ConstructionPhase::None) { 3636 1.1 joerg ObjType = Info.Ctx.getCanonicalType(ObjType); 3637 1.1 joerg ObjType.removeLocalConst(); 3638 1.1 joerg ObjType.removeLocalVolatile(); 3639 1.1 joerg } 3640 1.1 joerg 3641 1.1 joerg // If this is our last pass, check that the final object type is OK. 3642 1.1 joerg if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) { 3643 1.1 joerg // Accesses to volatile objects are prohibited. 3644 1.1 joerg if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) { 3645 1.1 joerg if (Info.getLangOpts().CPlusPlus) { 3646 1.1 joerg int DiagKind; 3647 1.1 joerg SourceLocation Loc; 3648 1.1 joerg const NamedDecl *Decl = nullptr; 3649 1.1 joerg if (VolatileField) { 3650 1.1 joerg DiagKind = 2; 3651 1.1 joerg Loc = VolatileField->getLocation(); 3652 1.1 joerg Decl = VolatileField; 3653 1.1 joerg } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) { 3654 1.1 joerg DiagKind = 1; 3655 1.1 joerg Loc = VD->getLocation(); 3656 1.1 joerg Decl = VD; 3657 1.1 joerg } else { 3658 1.1 joerg DiagKind = 0; 3659 1.1 joerg if (auto *E = Obj.Base.dyn_cast<const Expr *>()) 3660 1.1 joerg Loc = E->getExprLoc(); 3661 1.1 joerg } 3662 1.1 joerg Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1) 3663 1.1 joerg << handler.AccessKind << DiagKind << Decl; 3664 1.1 joerg Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind; 3665 1.1 joerg } else { 3666 1.1 joerg Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 3667 1.1 joerg } 3668 1.1 joerg return handler.failed(); 3669 1.1 joerg } 3670 1.1 joerg 3671 1.1 joerg // If we are reading an object of class type, there may still be more 3672 1.1 joerg // things we need to check: if there are any mutable subobjects, we 3673 1.1 joerg // cannot perform this read. (This only happens when performing a trivial 3674 1.1 joerg // copy or assignment.) 3675 1.1 joerg if (ObjType->isRecordType() && 3676 1.1 joerg !Obj.mayAccessMutableMembers(Info, handler.AccessKind) && 3677 1.1 joerg diagnoseMutableFields(Info, E, handler.AccessKind, ObjType)) 3678 1.1 joerg return handler.failed(); 3679 1.1 joerg } 3680 1.1 joerg 3681 1.1 joerg if (I == N) { 3682 1.1 joerg if (!handler.found(*O, ObjType)) 3683 1.1 joerg return false; 3684 1.1 joerg 3685 1.1 joerg // If we modified a bit-field, truncate it to the right width. 3686 1.1 joerg if (isModification(handler.AccessKind) && 3687 1.1 joerg LastField && LastField->isBitField() && 3688 1.1 joerg !truncateBitfieldValue(Info, E, *O, LastField)) 3689 1.1 joerg return false; 3690 1.1 joerg 3691 1.1 joerg return true; 3692 1.1 joerg } 3693 1.1 joerg 3694 1.1 joerg LastField = nullptr; 3695 1.1 joerg if (ObjType->isArrayType()) { 3696 1.1 joerg // Next subobject is an array element. 3697 1.1 joerg const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType); 3698 1.1 joerg assert(CAT && "vla in literal type?"); 3699 1.1 joerg uint64_t Index = Sub.Entries[I].getAsArrayIndex(); 3700 1.1 joerg if (CAT->getSize().ule(Index)) { 3701 1.1 joerg // Note, it should not be possible to form a pointer with a valid 3702 1.1 joerg // designator which points more than one past the end of the array. 3703 1.1 joerg if (Info.getLangOpts().CPlusPlus11) 3704 1.1 joerg Info.FFDiag(E, diag::note_constexpr_access_past_end) 3705 1.1 joerg << handler.AccessKind; 3706 1.1 joerg else 3707 1.1 joerg Info.FFDiag(E); 3708 1.1 joerg return handler.failed(); 3709 1.1 joerg } 3710 1.1 joerg 3711 1.1 joerg ObjType = CAT->getElementType(); 3712 1.1 joerg 3713 1.1 joerg if (O->getArrayInitializedElts() > Index) 3714 1.1 joerg O = &O->getArrayInitializedElt(Index); 3715 1.1 joerg else if (!isRead(handler.AccessKind)) { 3716 1.1 joerg expandArray(*O, Index); 3717 1.1 joerg O = &O->getArrayInitializedElt(Index); 3718 1.1 joerg } else 3719 1.1 joerg O = &O->getArrayFiller(); 3720 1.1 joerg } else if (ObjType->isAnyComplexType()) { 3721 1.1 joerg // Next subobject is a complex number. 3722 1.1 joerg uint64_t Index = Sub.Entries[I].getAsArrayIndex(); 3723 1.1 joerg if (Index > 1) { 3724 1.1 joerg if (Info.getLangOpts().CPlusPlus11) 3725 1.1 joerg Info.FFDiag(E, diag::note_constexpr_access_past_end) 3726 1.1 joerg << handler.AccessKind; 3727 1.1 joerg else 3728 1.1 joerg Info.FFDiag(E); 3729 1.1 joerg return handler.failed(); 3730 1.1 joerg } 3731 1.1 joerg 3732 1.1 joerg ObjType = getSubobjectType( 3733 1.1 joerg ObjType, ObjType->castAs<ComplexType>()->getElementType()); 3734 1.1 joerg 3735 1.1 joerg assert(I == N - 1 && "extracting subobject of scalar?"); 3736 1.1 joerg if (O->isComplexInt()) { 3737 1.1 joerg return handler.found(Index ? O->getComplexIntImag() 3738 1.1 joerg : O->getComplexIntReal(), ObjType); 3739 1.1 joerg } else { 3740 1.1 joerg assert(O->isComplexFloat()); 3741 1.1 joerg return handler.found(Index ? O->getComplexFloatImag() 3742 1.1 joerg : O->getComplexFloatReal(), ObjType); 3743 1.1 joerg } 3744 1.1 joerg } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) { 3745 1.1 joerg if (Field->isMutable() && 3746 1.1 joerg !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) { 3747 1.1 joerg Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) 3748 1.1 joerg << handler.AccessKind << Field; 3749 1.1 joerg Info.Note(Field->getLocation(), diag::note_declared_at); 3750 1.1 joerg return handler.failed(); 3751 1.1 joerg } 3752 1.1 joerg 3753 1.1 joerg // Next subobject is a class, struct or union field. 3754 1.1 joerg RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl(); 3755 1.1 joerg if (RD->isUnion()) { 3756 1.1 joerg const FieldDecl *UnionField = O->getUnionField(); 3757 1.1 joerg if (!UnionField || 3758 1.1 joerg UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) { 3759 1.1 joerg if (I == N - 1 && handler.AccessKind == AK_Construct) { 3760 1.1 joerg // Placement new onto an inactive union member makes it active. 3761 1.1 joerg O->setUnion(Field, APValue()); 3762 1.1 joerg } else { 3763 1.1 joerg // FIXME: If O->getUnionValue() is absent, report that there's no 3764 1.1 joerg // active union member rather than reporting the prior active union 3765 1.1 joerg // member. We'll need to fix nullptr_t to not use APValue() as its 3766 1.1 joerg // representation first. 3767 1.1 joerg Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member) 3768 1.1 joerg << handler.AccessKind << Field << !UnionField << UnionField; 3769 1.1 joerg return handler.failed(); 3770 1.1 joerg } 3771 1.1 joerg } 3772 1.1 joerg O = &O->getUnionValue(); 3773 1.1 joerg } else 3774 1.1 joerg O = &O->getStructField(Field->getFieldIndex()); 3775 1.1 joerg 3776 1.1 joerg ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable()); 3777 1.1 joerg LastField = Field; 3778 1.1 joerg if (Field->getType().isVolatileQualified()) 3779 1.1 joerg VolatileField = Field; 3780 1.1 joerg } else { 3781 1.1 joerg // Next subobject is a base class. 3782 1.1 joerg const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl(); 3783 1.1 joerg const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]); 3784 1.1 joerg O = &O->getStructBase(getBaseIndex(Derived, Base)); 3785 1.1 joerg 3786 1.1 joerg ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base)); 3787 1.1 joerg } 3788 1.1 joerg } 3789 1.1 joerg } 3790 1.1 joerg 3791 1.1 joerg namespace { 3792 1.1 joerg struct ExtractSubobjectHandler { 3793 1.1 joerg EvalInfo &Info; 3794 1.1 joerg const Expr *E; 3795 1.1 joerg APValue &Result; 3796 1.1 joerg const AccessKinds AccessKind; 3797 1.1 joerg 3798 1.1 joerg typedef bool result_type; 3799 1.1 joerg bool failed() { return false; } 3800 1.1 joerg bool found(APValue &Subobj, QualType SubobjType) { 3801 1.1 joerg Result = Subobj; 3802 1.1 joerg if (AccessKind == AK_ReadObjectRepresentation) 3803 1.1 joerg return true; 3804 1.1 joerg return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result); 3805 1.1 joerg } 3806 1.1 joerg bool found(APSInt &Value, QualType SubobjType) { 3807 1.1 joerg Result = APValue(Value); 3808 1.1 joerg return true; 3809 1.1 joerg } 3810 1.1 joerg bool found(APFloat &Value, QualType SubobjType) { 3811 1.1 joerg Result = APValue(Value); 3812 1.1 joerg return true; 3813 1.1 joerg } 3814 1.1 joerg }; 3815 1.1 joerg } // end anonymous namespace 3816 1.1 joerg 3817 1.1 joerg /// Extract the designated sub-object of an rvalue. 3818 1.1 joerg static bool extractSubobject(EvalInfo &Info, const Expr *E, 3819 1.1 joerg const CompleteObject &Obj, 3820 1.1 joerg const SubobjectDesignator &Sub, APValue &Result, 3821 1.1 joerg AccessKinds AK = AK_Read) { 3822 1.1 joerg assert(AK == AK_Read || AK == AK_ReadObjectRepresentation); 3823 1.1 joerg ExtractSubobjectHandler Handler = {Info, E, Result, AK}; 3824 1.1 joerg return findSubobject(Info, E, Obj, Sub, Handler); 3825 1.1 joerg } 3826 1.1 joerg 3827 1.1 joerg namespace { 3828 1.1 joerg struct ModifySubobjectHandler { 3829 1.1 joerg EvalInfo &Info; 3830 1.1 joerg APValue &NewVal; 3831 1.1 joerg const Expr *E; 3832 1.1 joerg 3833 1.1 joerg typedef bool result_type; 3834 1.1 joerg static const AccessKinds AccessKind = AK_Assign; 3835 1.1 joerg 3836 1.1 joerg bool checkConst(QualType QT) { 3837 1.1 joerg // Assigning to a const object has undefined behavior. 3838 1.1 joerg if (QT.isConstQualified()) { 3839 1.1 joerg Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 3840 1.1 joerg return false; 3841 1.1 joerg } 3842 1.1 joerg return true; 3843 1.1 joerg } 3844 1.1 joerg 3845 1.1 joerg bool failed() { return false; } 3846 1.1 joerg bool found(APValue &Subobj, QualType SubobjType) { 3847 1.1 joerg if (!checkConst(SubobjType)) 3848 1.1 joerg return false; 3849 1.1 joerg // We've been given ownership of NewVal, so just swap it in. 3850 1.1 joerg Subobj.swap(NewVal); 3851 1.1 joerg return true; 3852 1.1 joerg } 3853 1.1 joerg bool found(APSInt &Value, QualType SubobjType) { 3854 1.1 joerg if (!checkConst(SubobjType)) 3855 1.1 joerg return false; 3856 1.1 joerg if (!NewVal.isInt()) { 3857 1.1 joerg // Maybe trying to write a cast pointer value into a complex? 3858 1.1 joerg Info.FFDiag(E); 3859 1.1 joerg return false; 3860 1.1 joerg } 3861 1.1 joerg Value = NewVal.getInt(); 3862 1.1 joerg return true; 3863 1.1 joerg } 3864 1.1 joerg bool found(APFloat &Value, QualType SubobjType) { 3865 1.1 joerg if (!checkConst(SubobjType)) 3866 1.1 joerg return false; 3867 1.1 joerg Value = NewVal.getFloat(); 3868 1.1 joerg return true; 3869 1.1 joerg } 3870 1.1 joerg }; 3871 1.1 joerg } // end anonymous namespace 3872 1.1 joerg 3873 1.1 joerg const AccessKinds ModifySubobjectHandler::AccessKind; 3874 1.1 joerg 3875 1.1 joerg /// Update the designated sub-object of an rvalue to the given value. 3876 1.1 joerg static bool modifySubobject(EvalInfo &Info, const Expr *E, 3877 1.1 joerg const CompleteObject &Obj, 3878 1.1 joerg const SubobjectDesignator &Sub, 3879 1.1 joerg APValue &NewVal) { 3880 1.1 joerg ModifySubobjectHandler Handler = { Info, NewVal, E }; 3881 1.1 joerg return findSubobject(Info, E, Obj, Sub, Handler); 3882 1.1 joerg } 3883 1.1 joerg 3884 1.1 joerg /// Find the position where two subobject designators diverge, or equivalently 3885 1.1 joerg /// the length of the common initial subsequence. 3886 1.1 joerg static unsigned FindDesignatorMismatch(QualType ObjType, 3887 1.1 joerg const SubobjectDesignator &A, 3888 1.1 joerg const SubobjectDesignator &B, 3889 1.1 joerg bool &WasArrayIndex) { 3890 1.1 joerg unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size()); 3891 1.1 joerg for (/**/; I != N; ++I) { 3892 1.1 joerg if (!ObjType.isNull() && 3893 1.1 joerg (ObjType->isArrayType() || ObjType->isAnyComplexType())) { 3894 1.1 joerg // Next subobject is an array element. 3895 1.1 joerg if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) { 3896 1.1 joerg WasArrayIndex = true; 3897 1.1 joerg return I; 3898 1.1 joerg } 3899 1.1 joerg if (ObjType->isAnyComplexType()) 3900 1.1 joerg ObjType = ObjType->castAs<ComplexType>()->getElementType(); 3901 1.1 joerg else 3902 1.1 joerg ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType(); 3903 1.1 joerg } else { 3904 1.1 joerg if (A.Entries[I].getAsBaseOrMember() != 3905 1.1 joerg B.Entries[I].getAsBaseOrMember()) { 3906 1.1 joerg WasArrayIndex = false; 3907 1.1 joerg return I; 3908 1.1 joerg } 3909 1.1 joerg if (const FieldDecl *FD = getAsField(A.Entries[I])) 3910 1.1 joerg // Next subobject is a field. 3911 1.1 joerg ObjType = FD->getType(); 3912 1.1 joerg else 3913 1.1 joerg // Next subobject is a base class. 3914 1.1 joerg ObjType = QualType(); 3915 1.1 joerg } 3916 1.1 joerg } 3917 1.1 joerg WasArrayIndex = false; 3918 1.1 joerg return I; 3919 1.1 joerg } 3920 1.1 joerg 3921 1.1 joerg /// Determine whether the given subobject designators refer to elements of the 3922 1.1 joerg /// same array object. 3923 1.1 joerg static bool AreElementsOfSameArray(QualType ObjType, 3924 1.1 joerg const SubobjectDesignator &A, 3925 1.1 joerg const SubobjectDesignator &B) { 3926 1.1 joerg if (A.Entries.size() != B.Entries.size()) 3927 1.1 joerg return false; 3928 1.1 joerg 3929 1.1 joerg bool IsArray = A.MostDerivedIsArrayElement; 3930 1.1 joerg if (IsArray && A.MostDerivedPathLength != A.Entries.size()) 3931 1.1 joerg // A is a subobject of the array element. 3932 1.1 joerg return false; 3933 1.1 joerg 3934 1.1 joerg // If A (and B) designates an array element, the last entry will be the array 3935 1.1 joerg // index. That doesn't have to match. Otherwise, we're in the 'implicit array 3936 1.1 joerg // of length 1' case, and the entire path must match. 3937 1.1 joerg bool WasArrayIndex; 3938 1.1 joerg unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex); 3939 1.1 joerg return CommonLength >= A.Entries.size() - IsArray; 3940 1.1 joerg } 3941 1.1 joerg 3942 1.1 joerg /// Find the complete object to which an LValue refers. 3943 1.1 joerg static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, 3944 1.1 joerg AccessKinds AK, const LValue &LVal, 3945 1.1 joerg QualType LValType) { 3946 1.1 joerg if (LVal.InvalidBase) { 3947 1.1 joerg Info.FFDiag(E); 3948 1.1 joerg return CompleteObject(); 3949 1.1 joerg } 3950 1.1 joerg 3951 1.1 joerg if (!LVal.Base) { 3952 1.1 joerg Info.FFDiag(E, diag::note_constexpr_access_null) << AK; 3953 1.1 joerg return CompleteObject(); 3954 1.1 joerg } 3955 1.1 joerg 3956 1.1 joerg CallStackFrame *Frame = nullptr; 3957 1.1 joerg unsigned Depth = 0; 3958 1.1 joerg if (LVal.getLValueCallIndex()) { 3959 1.1 joerg std::tie(Frame, Depth) = 3960 1.1 joerg Info.getCallFrameAndDepth(LVal.getLValueCallIndex()); 3961 1.1 joerg if (!Frame) { 3962 1.1 joerg Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1) 3963 1.1 joerg << AK << LVal.Base.is<const ValueDecl*>(); 3964 1.1 joerg NoteLValueLocation(Info, LVal.Base); 3965 1.1 joerg return CompleteObject(); 3966 1.1 joerg } 3967 1.1 joerg } 3968 1.1 joerg 3969 1.1 joerg bool IsAccess = isAnyAccess(AK); 3970 1.1 joerg 3971 1.1 joerg // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type 3972 1.1 joerg // is not a constant expression (even if the object is non-volatile). We also 3973 1.1 joerg // apply this rule to C++98, in order to conform to the expected 'volatile' 3974 1.1 joerg // semantics. 3975 1.1 joerg if (isFormalAccess(AK) && LValType.isVolatileQualified()) { 3976 1.1 joerg if (Info.getLangOpts().CPlusPlus) 3977 1.1 joerg Info.FFDiag(E, diag::note_constexpr_access_volatile_type) 3978 1.1 joerg << AK << LValType; 3979 1.1 joerg else 3980 1.1 joerg Info.FFDiag(E); 3981 1.1 joerg return CompleteObject(); 3982 1.1 joerg } 3983 1.1 joerg 3984 1.1 joerg // Compute value storage location and type of base object. 3985 1.1 joerg APValue *BaseVal = nullptr; 3986 1.1 joerg QualType BaseType = getType(LVal.Base); 3987 1.1 joerg 3988 1.1.1.2 joerg if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl && 3989 1.1.1.2 joerg lifetimeStartedInEvaluation(Info, LVal.Base)) { 3990 1.1.1.2 joerg // This is the object whose initializer we're evaluating, so its lifetime 3991 1.1.1.2 joerg // started in the current evaluation. 3992 1.1.1.2 joerg BaseVal = Info.EvaluatingDeclValue; 3993 1.1.1.2 joerg } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) { 3994 1.1.1.2 joerg // Allow reading from a GUID declaration. 3995 1.1.1.2 joerg if (auto *GD = dyn_cast<MSGuidDecl>(D)) { 3996 1.1.1.2 joerg if (isModification(AK)) { 3997 1.1.1.2 joerg // All the remaining cases do not permit modification of the object. 3998 1.1.1.2 joerg Info.FFDiag(E, diag::note_constexpr_modify_global); 3999 1.1.1.2 joerg return CompleteObject(); 4000 1.1.1.2 joerg } 4001 1.1.1.2 joerg APValue &V = GD->getAsAPValue(); 4002 1.1.1.2 joerg if (V.isAbsent()) { 4003 1.1.1.2 joerg Info.FFDiag(E, diag::note_constexpr_unsupported_layout) 4004 1.1.1.2 joerg << GD->getType(); 4005 1.1.1.2 joerg return CompleteObject(); 4006 1.1.1.2 joerg } 4007 1.1.1.2 joerg return CompleteObject(LVal.Base, &V, GD->getType()); 4008 1.1.1.2 joerg } 4009 1.1.1.2 joerg 4010 1.1.1.2 joerg // Allow reading from template parameter objects. 4011 1.1.1.2 joerg if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) { 4012 1.1.1.2 joerg if (isModification(AK)) { 4013 1.1.1.2 joerg Info.FFDiag(E, diag::note_constexpr_modify_global); 4014 1.1.1.2 joerg return CompleteObject(); 4015 1.1.1.2 joerg } 4016 1.1.1.2 joerg return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()), 4017 1.1.1.2 joerg TPO->getType()); 4018 1.1.1.2 joerg } 4019 1.1.1.2 joerg 4020 1.1 joerg // In C++98, const, non-volatile integers initialized with ICEs are ICEs. 4021 1.1 joerg // In C++11, constexpr, non-volatile variables initialized with constant 4022 1.1 joerg // expressions are constant expressions too. Inside constexpr functions, 4023 1.1 joerg // parameters are constant expressions even if they're non-const. 4024 1.1 joerg // In C++1y, objects local to a constant expression (those with a Frame) are 4025 1.1 joerg // both readable and writable inside constant expressions. 4026 1.1 joerg // In C, such things can also be folded, although they are not ICEs. 4027 1.1 joerg const VarDecl *VD = dyn_cast<VarDecl>(D); 4028 1.1 joerg if (VD) { 4029 1.1 joerg if (const VarDecl *VDef = VD->getDefinition(Info.Ctx)) 4030 1.1 joerg VD = VDef; 4031 1.1 joerg } 4032 1.1 joerg if (!VD || VD->isInvalidDecl()) { 4033 1.1 joerg Info.FFDiag(E); 4034 1.1 joerg return CompleteObject(); 4035 1.1 joerg } 4036 1.1 joerg 4037 1.1.1.2 joerg bool IsConstant = BaseType.isConstant(Info.Ctx); 4038 1.1.1.2 joerg 4039 1.1 joerg // Unless we're looking at a local variable or argument in a constexpr call, 4040 1.1 joerg // the variable we're reading must be const. 4041 1.1 joerg if (!Frame) { 4042 1.1.1.2 joerg if (IsAccess && isa<ParmVarDecl>(VD)) { 4043 1.1.1.2 joerg // Access of a parameter that's not associated with a frame isn't going 4044 1.1.1.2 joerg // to work out, but we can leave it to evaluateVarDeclInit to provide a 4045 1.1.1.2 joerg // suitable diagnostic. 4046 1.1.1.2 joerg } else if (Info.getLangOpts().CPlusPlus14 && 4047 1.1.1.2 joerg lifetimeStartedInEvaluation(Info, LVal.Base)) { 4048 1.1 joerg // OK, we can read and modify an object if we're in the process of 4049 1.1 joerg // evaluating its initializer, because its lifetime began in this 4050 1.1 joerg // evaluation. 4051 1.1 joerg } else if (isModification(AK)) { 4052 1.1 joerg // All the remaining cases do not permit modification of the object. 4053 1.1 joerg Info.FFDiag(E, diag::note_constexpr_modify_global); 4054 1.1 joerg return CompleteObject(); 4055 1.1 joerg } else if (VD->isConstexpr()) { 4056 1.1 joerg // OK, we can read this variable. 4057 1.1 joerg } else if (BaseType->isIntegralOrEnumerationType()) { 4058 1.1.1.2 joerg if (!IsConstant) { 4059 1.1 joerg if (!IsAccess) 4060 1.1 joerg return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4061 1.1 joerg if (Info.getLangOpts().CPlusPlus) { 4062 1.1 joerg Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD; 4063 1.1 joerg Info.Note(VD->getLocation(), diag::note_declared_at); 4064 1.1 joerg } else { 4065 1.1 joerg Info.FFDiag(E); 4066 1.1 joerg } 4067 1.1 joerg return CompleteObject(); 4068 1.1 joerg } 4069 1.1 joerg } else if (!IsAccess) { 4070 1.1 joerg return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4071 1.1.1.2 joerg } else if (IsConstant && Info.checkingPotentialConstantExpression() && 4072 1.1.1.2 joerg BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) { 4073 1.1.1.2 joerg // This variable might end up being constexpr. Don't diagnose it yet. 4074 1.1.1.2 joerg } else if (IsConstant) { 4075 1.1.1.2 joerg // Keep evaluating to see what we can do. In particular, we support 4076 1.1.1.2 joerg // folding of const floating-point types, in order to make static const 4077 1.1.1.2 joerg // data members of such types (supported as an extension) more useful. 4078 1.1.1.2 joerg if (Info.getLangOpts().CPlusPlus) { 4079 1.1.1.2 joerg Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11 4080 1.1.1.2 joerg ? diag::note_constexpr_ltor_non_constexpr 4081 1.1.1.2 joerg : diag::note_constexpr_ltor_non_integral, 1) 4082 1.1.1.2 joerg << VD << BaseType; 4083 1.1 joerg Info.Note(VD->getLocation(), diag::note_declared_at); 4084 1.1 joerg } else { 4085 1.1 joerg Info.CCEDiag(E); 4086 1.1 joerg } 4087 1.1 joerg } else { 4088 1.1.1.2 joerg // Never allow reading a non-const value. 4089 1.1.1.2 joerg if (Info.getLangOpts().CPlusPlus) { 4090 1.1.1.2 joerg Info.FFDiag(E, Info.getLangOpts().CPlusPlus11 4091 1.1.1.2 joerg ? diag::note_constexpr_ltor_non_constexpr 4092 1.1.1.2 joerg : diag::note_constexpr_ltor_non_integral, 1) 4093 1.1.1.2 joerg << VD << BaseType; 4094 1.1 joerg Info.Note(VD->getLocation(), diag::note_declared_at); 4095 1.1 joerg } else { 4096 1.1 joerg Info.FFDiag(E); 4097 1.1 joerg } 4098 1.1 joerg return CompleteObject(); 4099 1.1 joerg } 4100 1.1 joerg } 4101 1.1 joerg 4102 1.1.1.2 joerg if (!evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(), BaseVal)) 4103 1.1 joerg return CompleteObject(); 4104 1.1 joerg } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) { 4105 1.1 joerg Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA); 4106 1.1 joerg if (!Alloc) { 4107 1.1 joerg Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK; 4108 1.1 joerg return CompleteObject(); 4109 1.1 joerg } 4110 1.1 joerg return CompleteObject(LVal.Base, &(*Alloc)->Value, 4111 1.1 joerg LVal.Base.getDynamicAllocType()); 4112 1.1 joerg } else { 4113 1.1 joerg const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 4114 1.1 joerg 4115 1.1 joerg if (!Frame) { 4116 1.1 joerg if (const MaterializeTemporaryExpr *MTE = 4117 1.1 joerg dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) { 4118 1.1 joerg assert(MTE->getStorageDuration() == SD_Static && 4119 1.1 joerg "should have a frame for a non-global materialized temporary"); 4120 1.1 joerg 4121 1.1.1.2 joerg // C++20 [expr.const]p4: [DR2126] 4122 1.1.1.2 joerg // An object or reference is usable in constant expressions if it is 4123 1.1.1.2 joerg // - a temporary object of non-volatile const-qualified literal type 4124 1.1.1.2 joerg // whose lifetime is extended to that of a variable that is usable 4125 1.1.1.2 joerg // in constant expressions 4126 1.1.1.2 joerg // 4127 1.1.1.2 joerg // C++20 [expr.const]p5: 4128 1.1 joerg // an lvalue-to-rvalue conversion [is not allowed unless it applies to] 4129 1.1.1.2 joerg // - a non-volatile glvalue that refers to an object that is usable 4130 1.1.1.2 joerg // in constant expressions, or 4131 1.1.1.2 joerg // - a non-volatile glvalue of literal type that refers to a 4132 1.1.1.2 joerg // non-volatile object whose lifetime began within the evaluation 4133 1.1.1.2 joerg // of E; 4134 1.1 joerg // 4135 1.1 joerg // C++11 misses the 'began within the evaluation of e' check and 4136 1.1 joerg // instead allows all temporaries, including things like: 4137 1.1 joerg // int &&r = 1; 4138 1.1 joerg // int x = ++r; 4139 1.1 joerg // constexpr int k = r; 4140 1.1.1.2 joerg // Therefore we use the C++14-onwards rules in C++11 too. 4141 1.1 joerg // 4142 1.1 joerg // Note that temporaries whose lifetimes began while evaluating a 4143 1.1 joerg // variable's constructor are not usable while evaluating the 4144 1.1 joerg // corresponding destructor, not even if they're of const-qualified 4145 1.1 joerg // types. 4146 1.1.1.2 joerg if (!MTE->isUsableInConstantExpressions(Info.Ctx) && 4147 1.1 joerg !lifetimeStartedInEvaluation(Info, LVal.Base)) { 4148 1.1 joerg if (!IsAccess) 4149 1.1 joerg return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4150 1.1 joerg Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK; 4151 1.1 joerg Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here); 4152 1.1 joerg return CompleteObject(); 4153 1.1 joerg } 4154 1.1 joerg 4155 1.1.1.2 joerg BaseVal = MTE->getOrCreateValue(false); 4156 1.1 joerg assert(BaseVal && "got reference to unevaluated temporary"); 4157 1.1 joerg } else { 4158 1.1 joerg if (!IsAccess) 4159 1.1 joerg return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 4160 1.1 joerg APValue Val; 4161 1.1 joerg LVal.moveInto(Val); 4162 1.1 joerg Info.FFDiag(E, diag::note_constexpr_access_unreadable_object) 4163 1.1 joerg << AK 4164 1.1 joerg << Val.getAsString(Info.Ctx, 4165 1.1 joerg Info.Ctx.getLValueReferenceType(LValType)); 4166 1.1 joerg NoteLValueLocation(Info, LVal.Base); 4167 1.1 joerg return CompleteObject(); 4168 1.1 joerg } 4169 1.1 joerg } else { 4170 1.1 joerg BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion()); 4171 1.1 joerg assert(BaseVal && "missing value for temporary"); 4172 1.1 joerg } 4173 1.1 joerg } 4174 1.1 joerg 4175 1.1 joerg // In C++14, we can't safely access any mutable state when we might be 4176 1.1.1.2 joerg // evaluating after an unmodeled side effect. Parameters are modeled as state 4177 1.1.1.2 joerg // in the caller, but aren't visible once the call returns, so they can be 4178 1.1.1.2 joerg // modified in a speculatively-evaluated call. 4179 1.1 joerg // 4180 1.1 joerg // FIXME: Not all local state is mutable. Allow local constant subobjects 4181 1.1 joerg // to be read here (but take care with 'mutable' fields). 4182 1.1.1.2 joerg unsigned VisibleDepth = Depth; 4183 1.1.1.2 joerg if (llvm::isa_and_nonnull<ParmVarDecl>( 4184 1.1.1.2 joerg LVal.Base.dyn_cast<const ValueDecl *>())) 4185 1.1.1.2 joerg ++VisibleDepth; 4186 1.1 joerg if ((Frame && Info.getLangOpts().CPlusPlus14 && 4187 1.1 joerg Info.EvalStatus.HasSideEffects) || 4188 1.1.1.2 joerg (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth)) 4189 1.1 joerg return CompleteObject(); 4190 1.1 joerg 4191 1.1 joerg return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType); 4192 1.1 joerg } 4193 1.1 joerg 4194 1.1 joerg /// Perform an lvalue-to-rvalue conversion on the given glvalue. This 4195 1.1 joerg /// can also be used for 'lvalue-to-lvalue' conversions for looking up the 4196 1.1 joerg /// glvalue referred to by an entity of reference type. 4197 1.1 joerg /// 4198 1.1 joerg /// \param Info - Information about the ongoing evaluation. 4199 1.1 joerg /// \param Conv - The expression for which we are performing the conversion. 4200 1.1 joerg /// Used for diagnostics. 4201 1.1 joerg /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the 4202 1.1 joerg /// case of a non-class type). 4203 1.1 joerg /// \param LVal - The glvalue on which we are attempting to perform this action. 4204 1.1 joerg /// \param RVal - The produced value will be placed here. 4205 1.1 joerg /// \param WantObjectRepresentation - If true, we're looking for the object 4206 1.1 joerg /// representation rather than the value, and in particular, 4207 1.1 joerg /// there is no requirement that the result be fully initialized. 4208 1.1 joerg static bool 4209 1.1 joerg handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type, 4210 1.1 joerg const LValue &LVal, APValue &RVal, 4211 1.1 joerg bool WantObjectRepresentation = false) { 4212 1.1 joerg if (LVal.Designator.Invalid) 4213 1.1 joerg return false; 4214 1.1 joerg 4215 1.1 joerg // Check for special cases where there is no existing APValue to look at. 4216 1.1 joerg const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 4217 1.1 joerg 4218 1.1 joerg AccessKinds AK = 4219 1.1 joerg WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read; 4220 1.1 joerg 4221 1.1 joerg if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) { 4222 1.1 joerg if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) { 4223 1.1 joerg // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the 4224 1.1 joerg // initializer until now for such expressions. Such an expression can't be 4225 1.1 joerg // an ICE in C, so this only matters for fold. 4226 1.1 joerg if (Type.isVolatileQualified()) { 4227 1.1 joerg Info.FFDiag(Conv); 4228 1.1 joerg return false; 4229 1.1 joerg } 4230 1.1 joerg APValue Lit; 4231 1.1 joerg if (!Evaluate(Lit, Info, CLE->getInitializer())) 4232 1.1 joerg return false; 4233 1.1 joerg CompleteObject LitObj(LVal.Base, &Lit, Base->getType()); 4234 1.1 joerg return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK); 4235 1.1 joerg } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) { 4236 1.1 joerg // Special-case character extraction so we don't have to construct an 4237 1.1 joerg // APValue for the whole string. 4238 1.1 joerg assert(LVal.Designator.Entries.size() <= 1 && 4239 1.1 joerg "Can only read characters from string literals"); 4240 1.1 joerg if (LVal.Designator.Entries.empty()) { 4241 1.1 joerg // Fail for now for LValue to RValue conversion of an array. 4242 1.1 joerg // (This shouldn't show up in C/C++, but it could be triggered by a 4243 1.1 joerg // weird EvaluateAsRValue call from a tool.) 4244 1.1 joerg Info.FFDiag(Conv); 4245 1.1 joerg return false; 4246 1.1 joerg } 4247 1.1 joerg if (LVal.Designator.isOnePastTheEnd()) { 4248 1.1 joerg if (Info.getLangOpts().CPlusPlus11) 4249 1.1 joerg Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK; 4250 1.1 joerg else 4251 1.1 joerg Info.FFDiag(Conv); 4252 1.1 joerg return false; 4253 1.1 joerg } 4254 1.1 joerg uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex(); 4255 1.1 joerg RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex)); 4256 1.1 joerg return true; 4257 1.1 joerg } 4258 1.1 joerg } 4259 1.1 joerg 4260 1.1 joerg CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type); 4261 1.1 joerg return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK); 4262 1.1 joerg } 4263 1.1 joerg 4264 1.1 joerg /// Perform an assignment of Val to LVal. Takes ownership of Val. 4265 1.1 joerg static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal, 4266 1.1 joerg QualType LValType, APValue &Val) { 4267 1.1 joerg if (LVal.Designator.Invalid) 4268 1.1 joerg return false; 4269 1.1 joerg 4270 1.1 joerg if (!Info.getLangOpts().CPlusPlus14) { 4271 1.1 joerg Info.FFDiag(E); 4272 1.1 joerg return false; 4273 1.1 joerg } 4274 1.1 joerg 4275 1.1 joerg CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); 4276 1.1 joerg return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val); 4277 1.1 joerg } 4278 1.1 joerg 4279 1.1 joerg namespace { 4280 1.1 joerg struct CompoundAssignSubobjectHandler { 4281 1.1 joerg EvalInfo &Info; 4282 1.1.1.2 joerg const CompoundAssignOperator *E; 4283 1.1 joerg QualType PromotedLHSType; 4284 1.1 joerg BinaryOperatorKind Opcode; 4285 1.1 joerg const APValue &RHS; 4286 1.1 joerg 4287 1.1 joerg static const AccessKinds AccessKind = AK_Assign; 4288 1.1 joerg 4289 1.1 joerg typedef bool result_type; 4290 1.1 joerg 4291 1.1 joerg bool checkConst(QualType QT) { 4292 1.1 joerg // Assigning to a const object has undefined behavior. 4293 1.1 joerg if (QT.isConstQualified()) { 4294 1.1 joerg Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 4295 1.1 joerg return false; 4296 1.1 joerg } 4297 1.1 joerg return true; 4298 1.1 joerg } 4299 1.1 joerg 4300 1.1 joerg bool failed() { return false; } 4301 1.1 joerg bool found(APValue &Subobj, QualType SubobjType) { 4302 1.1 joerg switch (Subobj.getKind()) { 4303 1.1 joerg case APValue::Int: 4304 1.1 joerg return found(Subobj.getInt(), SubobjType); 4305 1.1 joerg case APValue::Float: 4306 1.1 joerg return found(Subobj.getFloat(), SubobjType); 4307 1.1 joerg case APValue::ComplexInt: 4308 1.1 joerg case APValue::ComplexFloat: 4309 1.1 joerg // FIXME: Implement complex compound assignment. 4310 1.1 joerg Info.FFDiag(E); 4311 1.1 joerg return false; 4312 1.1 joerg case APValue::LValue: 4313 1.1 joerg return foundPointer(Subobj, SubobjType); 4314 1.1.1.2 joerg case APValue::Vector: 4315 1.1.1.2 joerg return foundVector(Subobj, SubobjType); 4316 1.1 joerg default: 4317 1.1 joerg // FIXME: can this happen? 4318 1.1 joerg Info.FFDiag(E); 4319 1.1 joerg return false; 4320 1.1 joerg } 4321 1.1 joerg } 4322 1.1.1.2 joerg 4323 1.1.1.2 joerg bool foundVector(APValue &Value, QualType SubobjType) { 4324 1.1.1.2 joerg if (!checkConst(SubobjType)) 4325 1.1.1.2 joerg return false; 4326 1.1.1.2 joerg 4327 1.1.1.2 joerg if (!SubobjType->isVectorType()) { 4328 1.1.1.2 joerg Info.FFDiag(E); 4329 1.1.1.2 joerg return false; 4330 1.1.1.2 joerg } 4331 1.1.1.2 joerg return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS); 4332 1.1.1.2 joerg } 4333 1.1.1.2 joerg 4334 1.1 joerg bool found(APSInt &Value, QualType SubobjType) { 4335 1.1 joerg if (!checkConst(SubobjType)) 4336 1.1 joerg return false; 4337 1.1 joerg 4338 1.1 joerg if (!SubobjType->isIntegerType()) { 4339 1.1 joerg // We don't support compound assignment on integer-cast-to-pointer 4340 1.1 joerg // values. 4341 1.1 joerg Info.FFDiag(E); 4342 1.1 joerg return false; 4343 1.1 joerg } 4344 1.1 joerg 4345 1.1 joerg if (RHS.isInt()) { 4346 1.1 joerg APSInt LHS = 4347 1.1 joerg HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value); 4348 1.1 joerg if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS)) 4349 1.1 joerg return false; 4350 1.1 joerg Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS); 4351 1.1 joerg return true; 4352 1.1 joerg } else if (RHS.isFloat()) { 4353 1.1.1.2 joerg const FPOptions FPO = E->getFPFeaturesInEffect( 4354 1.1.1.2 joerg Info.Ctx.getLangOpts()); 4355 1.1 joerg APFloat FValue(0.0); 4356 1.1.1.2 joerg return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value, 4357 1.1.1.2 joerg PromotedLHSType, FValue) && 4358 1.1 joerg handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) && 4359 1.1 joerg HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType, 4360 1.1 joerg Value); 4361 1.1 joerg } 4362 1.1 joerg 4363 1.1 joerg Info.FFDiag(E); 4364 1.1 joerg return false; 4365 1.1 joerg } 4366 1.1 joerg bool found(APFloat &Value, QualType SubobjType) { 4367 1.1 joerg return checkConst(SubobjType) && 4368 1.1 joerg HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType, 4369 1.1 joerg Value) && 4370 1.1 joerg handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) && 4371 1.1 joerg HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value); 4372 1.1 joerg } 4373 1.1 joerg bool foundPointer(APValue &Subobj, QualType SubobjType) { 4374 1.1 joerg if (!checkConst(SubobjType)) 4375 1.1 joerg return false; 4376 1.1 joerg 4377 1.1 joerg QualType PointeeType; 4378 1.1 joerg if (const PointerType *PT = SubobjType->getAs<PointerType>()) 4379 1.1 joerg PointeeType = PT->getPointeeType(); 4380 1.1 joerg 4381 1.1 joerg if (PointeeType.isNull() || !RHS.isInt() || 4382 1.1 joerg (Opcode != BO_Add && Opcode != BO_Sub)) { 4383 1.1 joerg Info.FFDiag(E); 4384 1.1 joerg return false; 4385 1.1 joerg } 4386 1.1 joerg 4387 1.1 joerg APSInt Offset = RHS.getInt(); 4388 1.1 joerg if (Opcode == BO_Sub) 4389 1.1 joerg negateAsSigned(Offset); 4390 1.1 joerg 4391 1.1 joerg LValue LVal; 4392 1.1 joerg LVal.setFrom(Info.Ctx, Subobj); 4393 1.1 joerg if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset)) 4394 1.1 joerg return false; 4395 1.1 joerg LVal.moveInto(Subobj); 4396 1.1 joerg return true; 4397 1.1 joerg } 4398 1.1 joerg }; 4399 1.1 joerg } // end anonymous namespace 4400 1.1 joerg 4401 1.1 joerg const AccessKinds CompoundAssignSubobjectHandler::AccessKind; 4402 1.1 joerg 4403 1.1 joerg /// Perform a compound assignment of LVal <op>= RVal. 4404 1.1.1.2 joerg static bool handleCompoundAssignment(EvalInfo &Info, 4405 1.1.1.2 joerg const CompoundAssignOperator *E, 4406 1.1.1.2 joerg const LValue &LVal, QualType LValType, 4407 1.1.1.2 joerg QualType PromotedLValType, 4408 1.1.1.2 joerg BinaryOperatorKind Opcode, 4409 1.1.1.2 joerg const APValue &RVal) { 4410 1.1 joerg if (LVal.Designator.Invalid) 4411 1.1 joerg return false; 4412 1.1 joerg 4413 1.1 joerg if (!Info.getLangOpts().CPlusPlus14) { 4414 1.1 joerg Info.FFDiag(E); 4415 1.1 joerg return false; 4416 1.1 joerg } 4417 1.1 joerg 4418 1.1 joerg CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); 4419 1.1 joerg CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode, 4420 1.1 joerg RVal }; 4421 1.1 joerg return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); 4422 1.1 joerg } 4423 1.1 joerg 4424 1.1 joerg namespace { 4425 1.1 joerg struct IncDecSubobjectHandler { 4426 1.1 joerg EvalInfo &Info; 4427 1.1 joerg const UnaryOperator *E; 4428 1.1 joerg AccessKinds AccessKind; 4429 1.1 joerg APValue *Old; 4430 1.1 joerg 4431 1.1 joerg typedef bool result_type; 4432 1.1 joerg 4433 1.1 joerg bool checkConst(QualType QT) { 4434 1.1 joerg // Assigning to a const object has undefined behavior. 4435 1.1 joerg if (QT.isConstQualified()) { 4436 1.1 joerg Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 4437 1.1 joerg return false; 4438 1.1 joerg } 4439 1.1 joerg return true; 4440 1.1 joerg } 4441 1.1 joerg 4442 1.1 joerg bool failed() { return false; } 4443 1.1 joerg bool found(APValue &Subobj, QualType SubobjType) { 4444 1.1 joerg // Stash the old value. Also clear Old, so we don't clobber it later 4445 1.1 joerg // if we're post-incrementing a complex. 4446 1.1 joerg if (Old) { 4447 1.1 joerg *Old = Subobj; 4448 1.1 joerg Old = nullptr; 4449 1.1 joerg } 4450 1.1 joerg 4451 1.1 joerg switch (Subobj.getKind()) { 4452 1.1 joerg case APValue::Int: 4453 1.1 joerg return found(Subobj.getInt(), SubobjType); 4454 1.1 joerg case APValue::Float: 4455 1.1 joerg return found(Subobj.getFloat(), SubobjType); 4456 1.1 joerg case APValue::ComplexInt: 4457 1.1 joerg return found(Subobj.getComplexIntReal(), 4458 1.1 joerg SubobjType->castAs<ComplexType>()->getElementType() 4459 1.1 joerg .withCVRQualifiers(SubobjType.getCVRQualifiers())); 4460 1.1 joerg case APValue::ComplexFloat: 4461 1.1 joerg return found(Subobj.getComplexFloatReal(), 4462 1.1 joerg SubobjType->castAs<ComplexType>()->getElementType() 4463 1.1 joerg .withCVRQualifiers(SubobjType.getCVRQualifiers())); 4464 1.1 joerg case APValue::LValue: 4465 1.1 joerg return foundPointer(Subobj, SubobjType); 4466 1.1 joerg default: 4467 1.1 joerg // FIXME: can this happen? 4468 1.1 joerg Info.FFDiag(E); 4469 1.1 joerg return false; 4470 1.1 joerg } 4471 1.1 joerg } 4472 1.1 joerg bool found(APSInt &Value, QualType SubobjType) { 4473 1.1 joerg if (!checkConst(SubobjType)) 4474 1.1 joerg return false; 4475 1.1 joerg 4476 1.1 joerg if (!SubobjType->isIntegerType()) { 4477 1.1 joerg // We don't support increment / decrement on integer-cast-to-pointer 4478 1.1 joerg // values. 4479 1.1 joerg Info.FFDiag(E); 4480 1.1 joerg return false; 4481 1.1 joerg } 4482 1.1 joerg 4483 1.1 joerg if (Old) *Old = APValue(Value); 4484 1.1 joerg 4485 1.1 joerg // bool arithmetic promotes to int, and the conversion back to bool 4486 1.1 joerg // doesn't reduce mod 2^n, so special-case it. 4487 1.1 joerg if (SubobjType->isBooleanType()) { 4488 1.1 joerg if (AccessKind == AK_Increment) 4489 1.1 joerg Value = 1; 4490 1.1 joerg else 4491 1.1 joerg Value = !Value; 4492 1.1 joerg return true; 4493 1.1 joerg } 4494 1.1 joerg 4495 1.1 joerg bool WasNegative = Value.isNegative(); 4496 1.1 joerg if (AccessKind == AK_Increment) { 4497 1.1 joerg ++Value; 4498 1.1 joerg 4499 1.1 joerg if (!WasNegative && Value.isNegative() && E->canOverflow()) { 4500 1.1 joerg APSInt ActualValue(Value, /*IsUnsigned*/true); 4501 1.1 joerg return HandleOverflow(Info, E, ActualValue, SubobjType); 4502 1.1 joerg } 4503 1.1 joerg } else { 4504 1.1 joerg --Value; 4505 1.1 joerg 4506 1.1 joerg if (WasNegative && !Value.isNegative() && E->canOverflow()) { 4507 1.1 joerg unsigned BitWidth = Value.getBitWidth(); 4508 1.1 joerg APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false); 4509 1.1 joerg ActualValue.setBit(BitWidth); 4510 1.1 joerg return HandleOverflow(Info, E, ActualValue, SubobjType); 4511 1.1 joerg } 4512 1.1 joerg } 4513 1.1 joerg return true; 4514 1.1 joerg } 4515 1.1 joerg bool found(APFloat &Value, QualType SubobjType) { 4516 1.1 joerg if (!checkConst(SubobjType)) 4517 1.1 joerg return false; 4518 1.1 joerg 4519 1.1 joerg if (Old) *Old = APValue(Value); 4520 1.1 joerg 4521 1.1 joerg APFloat One(Value.getSemantics(), 1); 4522 1.1 joerg if (AccessKind == AK_Increment) 4523 1.1 joerg Value.add(One, APFloat::rmNearestTiesToEven); 4524 1.1 joerg else 4525 1.1 joerg Value.subtract(One, APFloat::rmNearestTiesToEven); 4526 1.1 joerg return true; 4527 1.1 joerg } 4528 1.1 joerg bool foundPointer(APValue &Subobj, QualType SubobjType) { 4529 1.1 joerg if (!checkConst(SubobjType)) 4530 1.1 joerg return false; 4531 1.1 joerg 4532 1.1 joerg QualType PointeeType; 4533 1.1 joerg if (const PointerType *PT = SubobjType->getAs<PointerType>()) 4534 1.1 joerg PointeeType = PT->getPointeeType(); 4535 1.1 joerg else { 4536 1.1 joerg Info.FFDiag(E); 4537 1.1 joerg return false; 4538 1.1 joerg } 4539 1.1 joerg 4540 1.1 joerg LValue LVal; 4541 1.1 joerg LVal.setFrom(Info.Ctx, Subobj); 4542 1.1 joerg if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, 4543 1.1 joerg AccessKind == AK_Increment ? 1 : -1)) 4544 1.1 joerg return false; 4545 1.1 joerg LVal.moveInto(Subobj); 4546 1.1 joerg return true; 4547 1.1 joerg } 4548 1.1 joerg }; 4549 1.1 joerg } // end anonymous namespace 4550 1.1 joerg 4551 1.1 joerg /// Perform an increment or decrement on LVal. 4552 1.1 joerg static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal, 4553 1.1 joerg QualType LValType, bool IsIncrement, APValue *Old) { 4554 1.1 joerg if (LVal.Designator.Invalid) 4555 1.1 joerg return false; 4556 1.1 joerg 4557 1.1 joerg if (!Info.getLangOpts().CPlusPlus14) { 4558 1.1 joerg Info.FFDiag(E); 4559 1.1 joerg return false; 4560 1.1 joerg } 4561 1.1 joerg 4562 1.1 joerg AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement; 4563 1.1 joerg CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType); 4564 1.1 joerg IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old}; 4565 1.1 joerg return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); 4566 1.1 joerg } 4567 1.1 joerg 4568 1.1 joerg /// Build an lvalue for the object argument of a member function call. 4569 1.1 joerg static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object, 4570 1.1 joerg LValue &This) { 4571 1.1 joerg if (Object->getType()->isPointerType() && Object->isRValue()) 4572 1.1 joerg return EvaluatePointer(Object, This, Info); 4573 1.1 joerg 4574 1.1 joerg if (Object->isGLValue()) 4575 1.1 joerg return EvaluateLValue(Object, This, Info); 4576 1.1 joerg 4577 1.1 joerg if (Object->getType()->isLiteralType(Info.Ctx)) 4578 1.1 joerg return EvaluateTemporary(Object, This, Info); 4579 1.1 joerg 4580 1.1 joerg Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType(); 4581 1.1 joerg return false; 4582 1.1 joerg } 4583 1.1 joerg 4584 1.1 joerg /// HandleMemberPointerAccess - Evaluate a member access operation and build an 4585 1.1 joerg /// lvalue referring to the result. 4586 1.1 joerg /// 4587 1.1 joerg /// \param Info - Information about the ongoing evaluation. 4588 1.1 joerg /// \param LV - An lvalue referring to the base of the member pointer. 4589 1.1 joerg /// \param RHS - The member pointer expression. 4590 1.1 joerg /// \param IncludeMember - Specifies whether the member itself is included in 4591 1.1 joerg /// the resulting LValue subobject designator. This is not possible when 4592 1.1 joerg /// creating a bound member function. 4593 1.1 joerg /// \return The field or method declaration to which the member pointer refers, 4594 1.1 joerg /// or 0 if evaluation fails. 4595 1.1 joerg static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 4596 1.1 joerg QualType LVType, 4597 1.1 joerg LValue &LV, 4598 1.1 joerg const Expr *RHS, 4599 1.1 joerg bool IncludeMember = true) { 4600 1.1 joerg MemberPtr MemPtr; 4601 1.1 joerg if (!EvaluateMemberPointer(RHS, MemPtr, Info)) 4602 1.1 joerg return nullptr; 4603 1.1 joerg 4604 1.1 joerg // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to 4605 1.1 joerg // member value, the behavior is undefined. 4606 1.1 joerg if (!MemPtr.getDecl()) { 4607 1.1 joerg // FIXME: Specific diagnostic. 4608 1.1 joerg Info.FFDiag(RHS); 4609 1.1 joerg return nullptr; 4610 1.1 joerg } 4611 1.1 joerg 4612 1.1 joerg if (MemPtr.isDerivedMember()) { 4613 1.1 joerg // This is a member of some derived class. Truncate LV appropriately. 4614 1.1 joerg // The end of the derived-to-base path for the base object must match the 4615 1.1 joerg // derived-to-base path for the member pointer. 4616 1.1 joerg if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() > 4617 1.1 joerg LV.Designator.Entries.size()) { 4618 1.1 joerg Info.FFDiag(RHS); 4619 1.1 joerg return nullptr; 4620 1.1 joerg } 4621 1.1 joerg unsigned PathLengthToMember = 4622 1.1 joerg LV.Designator.Entries.size() - MemPtr.Path.size(); 4623 1.1 joerg for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) { 4624 1.1 joerg const CXXRecordDecl *LVDecl = getAsBaseClass( 4625 1.1 joerg LV.Designator.Entries[PathLengthToMember + I]); 4626 1.1 joerg const CXXRecordDecl *MPDecl = MemPtr.Path[I]; 4627 1.1 joerg if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) { 4628 1.1 joerg Info.FFDiag(RHS); 4629 1.1 joerg return nullptr; 4630 1.1 joerg } 4631 1.1 joerg } 4632 1.1 joerg 4633 1.1 joerg // Truncate the lvalue to the appropriate derived class. 4634 1.1 joerg if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(), 4635 1.1 joerg PathLengthToMember)) 4636 1.1 joerg return nullptr; 4637 1.1 joerg } else if (!MemPtr.Path.empty()) { 4638 1.1 joerg // Extend the LValue path with the member pointer's path. 4639 1.1 joerg LV.Designator.Entries.reserve(LV.Designator.Entries.size() + 4640 1.1 joerg MemPtr.Path.size() + IncludeMember); 4641 1.1 joerg 4642 1.1 joerg // Walk down to the appropriate base class. 4643 1.1 joerg if (const PointerType *PT = LVType->getAs<PointerType>()) 4644 1.1 joerg LVType = PT->getPointeeType(); 4645 1.1 joerg const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl(); 4646 1.1 joerg assert(RD && "member pointer access on non-class-type expression"); 4647 1.1 joerg // The first class in the path is that of the lvalue. 4648 1.1 joerg for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) { 4649 1.1 joerg const CXXRecordDecl *Base = MemPtr.Path[N - I - 1]; 4650 1.1 joerg if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base)) 4651 1.1 joerg return nullptr; 4652 1.1 joerg RD = Base; 4653 1.1 joerg } 4654 1.1 joerg // Finally cast to the class containing the member. 4655 1.1 joerg if (!HandleLValueDirectBase(Info, RHS, LV, RD, 4656 1.1 joerg MemPtr.getContainingRecord())) 4657 1.1 joerg return nullptr; 4658 1.1 joerg } 4659 1.1 joerg 4660 1.1 joerg // Add the member. Note that we cannot build bound member functions here. 4661 1.1 joerg if (IncludeMember) { 4662 1.1 joerg if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) { 4663 1.1 joerg if (!HandleLValueMember(Info, RHS, LV, FD)) 4664 1.1 joerg return nullptr; 4665 1.1 joerg } else if (const IndirectFieldDecl *IFD = 4666 1.1 joerg dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) { 4667 1.1 joerg if (!HandleLValueIndirectMember(Info, RHS, LV, IFD)) 4668 1.1 joerg return nullptr; 4669 1.1 joerg } else { 4670 1.1 joerg llvm_unreachable("can't construct reference to bound member function"); 4671 1.1 joerg } 4672 1.1 joerg } 4673 1.1 joerg 4674 1.1 joerg return MemPtr.getDecl(); 4675 1.1 joerg } 4676 1.1 joerg 4677 1.1 joerg static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 4678 1.1 joerg const BinaryOperator *BO, 4679 1.1 joerg LValue &LV, 4680 1.1 joerg bool IncludeMember = true) { 4681 1.1 joerg assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI); 4682 1.1 joerg 4683 1.1 joerg if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) { 4684 1.1 joerg if (Info.noteFailure()) { 4685 1.1 joerg MemberPtr MemPtr; 4686 1.1 joerg EvaluateMemberPointer(BO->getRHS(), MemPtr, Info); 4687 1.1 joerg } 4688 1.1 joerg return nullptr; 4689 1.1 joerg } 4690 1.1 joerg 4691 1.1 joerg return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV, 4692 1.1 joerg BO->getRHS(), IncludeMember); 4693 1.1 joerg } 4694 1.1 joerg 4695 1.1 joerg /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on 4696 1.1 joerg /// the provided lvalue, which currently refers to the base object. 4697 1.1 joerg static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E, 4698 1.1 joerg LValue &Result) { 4699 1.1 joerg SubobjectDesignator &D = Result.Designator; 4700 1.1 joerg if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived)) 4701 1.1 joerg return false; 4702 1.1 joerg 4703 1.1 joerg QualType TargetQT = E->getType(); 4704 1.1 joerg if (const PointerType *PT = TargetQT->getAs<PointerType>()) 4705 1.1 joerg TargetQT = PT->getPointeeType(); 4706 1.1 joerg 4707 1.1 joerg // Check this cast lands within the final derived-to-base subobject path. 4708 1.1 joerg if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) { 4709 1.1 joerg Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 4710 1.1 joerg << D.MostDerivedType << TargetQT; 4711 1.1 joerg return false; 4712 1.1 joerg } 4713 1.1 joerg 4714 1.1 joerg // Check the type of the final cast. We don't need to check the path, 4715 1.1 joerg // since a cast can only be formed if the path is unique. 4716 1.1 joerg unsigned NewEntriesSize = D.Entries.size() - E->path_size(); 4717 1.1 joerg const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl(); 4718 1.1 joerg const CXXRecordDecl *FinalType; 4719 1.1 joerg if (NewEntriesSize == D.MostDerivedPathLength) 4720 1.1 joerg FinalType = D.MostDerivedType->getAsCXXRecordDecl(); 4721 1.1 joerg else 4722 1.1 joerg FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]); 4723 1.1 joerg if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) { 4724 1.1 joerg Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 4725 1.1 joerg << D.MostDerivedType << TargetQT; 4726 1.1 joerg return false; 4727 1.1 joerg } 4728 1.1 joerg 4729 1.1 joerg // Truncate the lvalue to the appropriate derived class. 4730 1.1 joerg return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize); 4731 1.1 joerg } 4732 1.1 joerg 4733 1.1 joerg /// Get the value to use for a default-initialized object of type T. 4734 1.1.1.2 joerg /// Return false if it encounters something invalid. 4735 1.1.1.2 joerg static bool getDefaultInitValue(QualType T, APValue &Result) { 4736 1.1.1.2 joerg bool Success = true; 4737 1.1 joerg if (auto *RD = T->getAsCXXRecordDecl()) { 4738 1.1.1.2 joerg if (RD->isInvalidDecl()) { 4739 1.1.1.2 joerg Result = APValue(); 4740 1.1.1.2 joerg return false; 4741 1.1.1.2 joerg } 4742 1.1.1.2 joerg if (RD->isUnion()) { 4743 1.1.1.2 joerg Result = APValue((const FieldDecl *)nullptr); 4744 1.1.1.2 joerg return true; 4745 1.1.1.2 joerg } 4746 1.1.1.2 joerg Result = APValue(APValue::UninitStruct(), RD->getNumBases(), 4747 1.1.1.2 joerg std::distance(RD->field_begin(), RD->field_end())); 4748 1.1 joerg 4749 1.1 joerg unsigned Index = 0; 4750 1.1 joerg for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), 4751 1.1.1.2 joerg End = RD->bases_end(); 4752 1.1.1.2 joerg I != End; ++I, ++Index) 4753 1.1.1.2 joerg Success &= getDefaultInitValue(I->getType(), Result.getStructBase(Index)); 4754 1.1 joerg 4755 1.1 joerg for (const auto *I : RD->fields()) { 4756 1.1 joerg if (I->isUnnamedBitfield()) 4757 1.1 joerg continue; 4758 1.1.1.2 joerg Success &= getDefaultInitValue(I->getType(), 4759 1.1.1.2 joerg Result.getStructField(I->getFieldIndex())); 4760 1.1 joerg } 4761 1.1.1.2 joerg return Success; 4762 1.1 joerg } 4763 1.1 joerg 4764 1.1 joerg if (auto *AT = 4765 1.1 joerg dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) { 4766 1.1.1.2 joerg Result = APValue(APValue::UninitArray(), 0, AT->getSize().getZExtValue()); 4767 1.1.1.2 joerg if (Result.hasArrayFiller()) 4768 1.1.1.2 joerg Success &= 4769 1.1.1.2 joerg getDefaultInitValue(AT->getElementType(), Result.getArrayFiller()); 4770 1.1.1.2 joerg 4771 1.1.1.2 joerg return Success; 4772 1.1 joerg } 4773 1.1 joerg 4774 1.1.1.2 joerg Result = APValue::IndeterminateValue(); 4775 1.1.1.2 joerg return true; 4776 1.1 joerg } 4777 1.1 joerg 4778 1.1 joerg namespace { 4779 1.1 joerg enum EvalStmtResult { 4780 1.1 joerg /// Evaluation failed. 4781 1.1 joerg ESR_Failed, 4782 1.1 joerg /// Hit a 'return' statement. 4783 1.1 joerg ESR_Returned, 4784 1.1 joerg /// Evaluation succeeded. 4785 1.1 joerg ESR_Succeeded, 4786 1.1 joerg /// Hit a 'continue' statement. 4787 1.1 joerg ESR_Continue, 4788 1.1 joerg /// Hit a 'break' statement. 4789 1.1 joerg ESR_Break, 4790 1.1 joerg /// Still scanning for 'case' or 'default' statement. 4791 1.1 joerg ESR_CaseNotFound 4792 1.1 joerg }; 4793 1.1 joerg } 4794 1.1 joerg 4795 1.1 joerg static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) { 4796 1.1 joerg // We don't need to evaluate the initializer for a static local. 4797 1.1 joerg if (!VD->hasLocalStorage()) 4798 1.1 joerg return true; 4799 1.1 joerg 4800 1.1 joerg LValue Result; 4801 1.1.1.2 joerg APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(), 4802 1.1.1.2 joerg ScopeKind::Block, Result); 4803 1.1 joerg 4804 1.1 joerg const Expr *InitE = VD->getInit(); 4805 1.1 joerg if (!InitE) { 4806 1.1.1.2 joerg if (VD->getType()->isDependentType()) 4807 1.1.1.2 joerg return Info.noteSideEffect(); 4808 1.1.1.2 joerg return getDefaultInitValue(VD->getType(), Val); 4809 1.1 joerg } 4810 1.1 joerg if (InitE->isValueDependent()) 4811 1.1 joerg return false; 4812 1.1 joerg 4813 1.1 joerg if (!EvaluateInPlace(Val, Info, Result, InitE)) { 4814 1.1 joerg // Wipe out any partially-computed value, to allow tracking that this 4815 1.1 joerg // evaluation failed. 4816 1.1 joerg Val = APValue(); 4817 1.1 joerg return false; 4818 1.1 joerg } 4819 1.1 joerg 4820 1.1 joerg return true; 4821 1.1 joerg } 4822 1.1 joerg 4823 1.1 joerg static bool EvaluateDecl(EvalInfo &Info, const Decl *D) { 4824 1.1 joerg bool OK = true; 4825 1.1 joerg 4826 1.1 joerg if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 4827 1.1 joerg OK &= EvaluateVarDecl(Info, VD); 4828 1.1 joerg 4829 1.1 joerg if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D)) 4830 1.1 joerg for (auto *BD : DD->bindings()) 4831 1.1 joerg if (auto *VD = BD->getHoldingVar()) 4832 1.1 joerg OK &= EvaluateDecl(Info, VD); 4833 1.1 joerg 4834 1.1 joerg return OK; 4835 1.1 joerg } 4836 1.1 joerg 4837 1.1.1.2 joerg static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) { 4838 1.1.1.2 joerg assert(E->isValueDependent()); 4839 1.1.1.2 joerg if (Info.noteSideEffect()) 4840 1.1.1.2 joerg return true; 4841 1.1.1.2 joerg assert(E->containsErrors() && "valid value-dependent expression should never " 4842 1.1.1.2 joerg "reach invalid code path."); 4843 1.1.1.2 joerg return false; 4844 1.1.1.2 joerg } 4845 1.1 joerg 4846 1.1 joerg /// Evaluate a condition (either a variable declaration or an expression). 4847 1.1 joerg static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl, 4848 1.1 joerg const Expr *Cond, bool &Result) { 4849 1.1.1.2 joerg if (Cond->isValueDependent()) 4850 1.1.1.2 joerg return false; 4851 1.1 joerg FullExpressionRAII Scope(Info); 4852 1.1 joerg if (CondDecl && !EvaluateDecl(Info, CondDecl)) 4853 1.1 joerg return false; 4854 1.1 joerg if (!EvaluateAsBooleanCondition(Cond, Result, Info)) 4855 1.1 joerg return false; 4856 1.1 joerg return Scope.destroy(); 4857 1.1 joerg } 4858 1.1 joerg 4859 1.1 joerg namespace { 4860 1.1 joerg /// A location where the result (returned value) of evaluating a 4861 1.1 joerg /// statement should be stored. 4862 1.1 joerg struct StmtResult { 4863 1.1 joerg /// The APValue that should be filled in with the returned value. 4864 1.1 joerg APValue &Value; 4865 1.1 joerg /// The location containing the result, if any (used to support RVO). 4866 1.1 joerg const LValue *Slot; 4867 1.1 joerg }; 4868 1.1 joerg 4869 1.1 joerg struct TempVersionRAII { 4870 1.1 joerg CallStackFrame &Frame; 4871 1.1 joerg 4872 1.1 joerg TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) { 4873 1.1 joerg Frame.pushTempVersion(); 4874 1.1 joerg } 4875 1.1 joerg 4876 1.1 joerg ~TempVersionRAII() { 4877 1.1 joerg Frame.popTempVersion(); 4878 1.1 joerg } 4879 1.1 joerg }; 4880 1.1 joerg 4881 1.1 joerg } 4882 1.1 joerg 4883 1.1 joerg static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, 4884 1.1 joerg const Stmt *S, 4885 1.1 joerg const SwitchCase *SC = nullptr); 4886 1.1 joerg 4887 1.1 joerg /// Evaluate the body of a loop, and translate the result as appropriate. 4888 1.1 joerg static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info, 4889 1.1 joerg const Stmt *Body, 4890 1.1 joerg const SwitchCase *Case = nullptr) { 4891 1.1 joerg BlockScopeRAII Scope(Info); 4892 1.1 joerg 4893 1.1 joerg EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case); 4894 1.1 joerg if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy()) 4895 1.1 joerg ESR = ESR_Failed; 4896 1.1 joerg 4897 1.1 joerg switch (ESR) { 4898 1.1 joerg case ESR_Break: 4899 1.1 joerg return ESR_Succeeded; 4900 1.1 joerg case ESR_Succeeded: 4901 1.1 joerg case ESR_Continue: 4902 1.1 joerg return ESR_Continue; 4903 1.1 joerg case ESR_Failed: 4904 1.1 joerg case ESR_Returned: 4905 1.1 joerg case ESR_CaseNotFound: 4906 1.1 joerg return ESR; 4907 1.1 joerg } 4908 1.1 joerg llvm_unreachable("Invalid EvalStmtResult!"); 4909 1.1 joerg } 4910 1.1 joerg 4911 1.1 joerg /// Evaluate a switch statement. 4912 1.1 joerg static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info, 4913 1.1 joerg const SwitchStmt *SS) { 4914 1.1 joerg BlockScopeRAII Scope(Info); 4915 1.1 joerg 4916 1.1 joerg // Evaluate the switch condition. 4917 1.1 joerg APSInt Value; 4918 1.1 joerg { 4919 1.1 joerg if (const Stmt *Init = SS->getInit()) { 4920 1.1 joerg EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); 4921 1.1 joerg if (ESR != ESR_Succeeded) { 4922 1.1 joerg if (ESR != ESR_Failed && !Scope.destroy()) 4923 1.1 joerg ESR = ESR_Failed; 4924 1.1 joerg return ESR; 4925 1.1 joerg } 4926 1.1 joerg } 4927 1.1 joerg 4928 1.1 joerg FullExpressionRAII CondScope(Info); 4929 1.1 joerg if (SS->getConditionVariable() && 4930 1.1 joerg !EvaluateDecl(Info, SS->getConditionVariable())) 4931 1.1 joerg return ESR_Failed; 4932 1.1 joerg if (!EvaluateInteger(SS->getCond(), Value, Info)) 4933 1.1 joerg return ESR_Failed; 4934 1.1 joerg if (!CondScope.destroy()) 4935 1.1 joerg return ESR_Failed; 4936 1.1 joerg } 4937 1.1 joerg 4938 1.1 joerg // Find the switch case corresponding to the value of the condition. 4939 1.1 joerg // FIXME: Cache this lookup. 4940 1.1 joerg const SwitchCase *Found = nullptr; 4941 1.1 joerg for (const SwitchCase *SC = SS->getSwitchCaseList(); SC; 4942 1.1 joerg SC = SC->getNextSwitchCase()) { 4943 1.1 joerg if (isa<DefaultStmt>(SC)) { 4944 1.1 joerg Found = SC; 4945 1.1 joerg continue; 4946 1.1 joerg } 4947 1.1 joerg 4948 1.1 joerg const CaseStmt *CS = cast<CaseStmt>(SC); 4949 1.1 joerg APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx); 4950 1.1 joerg APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx) 4951 1.1 joerg : LHS; 4952 1.1 joerg if (LHS <= Value && Value <= RHS) { 4953 1.1 joerg Found = SC; 4954 1.1 joerg break; 4955 1.1 joerg } 4956 1.1 joerg } 4957 1.1 joerg 4958 1.1 joerg if (!Found) 4959 1.1 joerg return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 4960 1.1 joerg 4961 1.1 joerg // Search the switch body for the switch case and evaluate it from there. 4962 1.1 joerg EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found); 4963 1.1 joerg if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy()) 4964 1.1 joerg return ESR_Failed; 4965 1.1 joerg 4966 1.1 joerg switch (ESR) { 4967 1.1 joerg case ESR_Break: 4968 1.1 joerg return ESR_Succeeded; 4969 1.1 joerg case ESR_Succeeded: 4970 1.1 joerg case ESR_Continue: 4971 1.1 joerg case ESR_Failed: 4972 1.1 joerg case ESR_Returned: 4973 1.1 joerg return ESR; 4974 1.1 joerg case ESR_CaseNotFound: 4975 1.1 joerg // This can only happen if the switch case is nested within a statement 4976 1.1 joerg // expression. We have no intention of supporting that. 4977 1.1 joerg Info.FFDiag(Found->getBeginLoc(), 4978 1.1 joerg diag::note_constexpr_stmt_expr_unsupported); 4979 1.1 joerg return ESR_Failed; 4980 1.1 joerg } 4981 1.1 joerg llvm_unreachable("Invalid EvalStmtResult!"); 4982 1.1 joerg } 4983 1.1 joerg 4984 1.1 joerg // Evaluate a statement. 4985 1.1 joerg static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, 4986 1.1 joerg const Stmt *S, const SwitchCase *Case) { 4987 1.1 joerg if (!Info.nextStep(S)) 4988 1.1 joerg return ESR_Failed; 4989 1.1 joerg 4990 1.1 joerg // If we're hunting down a 'case' or 'default' label, recurse through 4991 1.1 joerg // substatements until we hit the label. 4992 1.1 joerg if (Case) { 4993 1.1 joerg switch (S->getStmtClass()) { 4994 1.1 joerg case Stmt::CompoundStmtClass: 4995 1.1 joerg // FIXME: Precompute which substatement of a compound statement we 4996 1.1 joerg // would jump to, and go straight there rather than performing a 4997 1.1 joerg // linear scan each time. 4998 1.1 joerg case Stmt::LabelStmtClass: 4999 1.1 joerg case Stmt::AttributedStmtClass: 5000 1.1 joerg case Stmt::DoStmtClass: 5001 1.1 joerg break; 5002 1.1 joerg 5003 1.1 joerg case Stmt::CaseStmtClass: 5004 1.1 joerg case Stmt::DefaultStmtClass: 5005 1.1 joerg if (Case == S) 5006 1.1 joerg Case = nullptr; 5007 1.1 joerg break; 5008 1.1 joerg 5009 1.1 joerg case Stmt::IfStmtClass: { 5010 1.1 joerg // FIXME: Precompute which side of an 'if' we would jump to, and go 5011 1.1 joerg // straight there rather than scanning both sides. 5012 1.1 joerg const IfStmt *IS = cast<IfStmt>(S); 5013 1.1 joerg 5014 1.1 joerg // Wrap the evaluation in a block scope, in case it's a DeclStmt 5015 1.1 joerg // preceded by our switch label. 5016 1.1 joerg BlockScopeRAII Scope(Info); 5017 1.1 joerg 5018 1.1 joerg // Step into the init statement in case it brings an (uninitialized) 5019 1.1 joerg // variable into scope. 5020 1.1 joerg if (const Stmt *Init = IS->getInit()) { 5021 1.1 joerg EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case); 5022 1.1 joerg if (ESR != ESR_CaseNotFound) { 5023 1.1 joerg assert(ESR != ESR_Succeeded); 5024 1.1 joerg return ESR; 5025 1.1 joerg } 5026 1.1 joerg } 5027 1.1 joerg 5028 1.1 joerg // Condition variable must be initialized if it exists. 5029 1.1 joerg // FIXME: We can skip evaluating the body if there's a condition 5030 1.1 joerg // variable, as there can't be any case labels within it. 5031 1.1 joerg // (The same is true for 'for' statements.) 5032 1.1 joerg 5033 1.1 joerg EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case); 5034 1.1 joerg if (ESR == ESR_Failed) 5035 1.1 joerg return ESR; 5036 1.1 joerg if (ESR != ESR_CaseNotFound) 5037 1.1 joerg return Scope.destroy() ? ESR : ESR_Failed; 5038 1.1 joerg if (!IS->getElse()) 5039 1.1 joerg return ESR_CaseNotFound; 5040 1.1 joerg 5041 1.1 joerg ESR = EvaluateStmt(Result, Info, IS->getElse(), Case); 5042 1.1 joerg if (ESR == ESR_Failed) 5043 1.1 joerg return ESR; 5044 1.1 joerg if (ESR != ESR_CaseNotFound) 5045 1.1 joerg return Scope.destroy() ? ESR : ESR_Failed; 5046 1.1 joerg return ESR_CaseNotFound; 5047 1.1 joerg } 5048 1.1 joerg 5049 1.1 joerg case Stmt::WhileStmtClass: { 5050 1.1 joerg EvalStmtResult ESR = 5051 1.1 joerg EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case); 5052 1.1 joerg if (ESR != ESR_Continue) 5053 1.1 joerg return ESR; 5054 1.1 joerg break; 5055 1.1 joerg } 5056 1.1 joerg 5057 1.1 joerg case Stmt::ForStmtClass: { 5058 1.1 joerg const ForStmt *FS = cast<ForStmt>(S); 5059 1.1 joerg BlockScopeRAII Scope(Info); 5060 1.1 joerg 5061 1.1 joerg // Step into the init statement in case it brings an (uninitialized) 5062 1.1 joerg // variable into scope. 5063 1.1 joerg if (const Stmt *Init = FS->getInit()) { 5064 1.1 joerg EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case); 5065 1.1 joerg if (ESR != ESR_CaseNotFound) { 5066 1.1 joerg assert(ESR != ESR_Succeeded); 5067 1.1 joerg return ESR; 5068 1.1 joerg } 5069 1.1 joerg } 5070 1.1 joerg 5071 1.1 joerg EvalStmtResult ESR = 5072 1.1 joerg EvaluateLoopBody(Result, Info, FS->getBody(), Case); 5073 1.1 joerg if (ESR != ESR_Continue) 5074 1.1 joerg return ESR; 5075 1.1.1.2 joerg if (const auto *Inc = FS->getInc()) { 5076 1.1.1.2 joerg if (Inc->isValueDependent()) { 5077 1.1.1.2 joerg if (!EvaluateDependentExpr(Inc, Info)) 5078 1.1.1.2 joerg return ESR_Failed; 5079 1.1.1.2 joerg } else { 5080 1.1.1.2 joerg FullExpressionRAII IncScope(Info); 5081 1.1.1.2 joerg if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy()) 5082 1.1.1.2 joerg return ESR_Failed; 5083 1.1.1.2 joerg } 5084 1.1 joerg } 5085 1.1 joerg break; 5086 1.1 joerg } 5087 1.1 joerg 5088 1.1 joerg case Stmt::DeclStmtClass: { 5089 1.1 joerg // Start the lifetime of any uninitialized variables we encounter. They 5090 1.1 joerg // might be used by the selected branch of the switch. 5091 1.1 joerg const DeclStmt *DS = cast<DeclStmt>(S); 5092 1.1 joerg for (const auto *D : DS->decls()) { 5093 1.1 joerg if (const auto *VD = dyn_cast<VarDecl>(D)) { 5094 1.1 joerg if (VD->hasLocalStorage() && !VD->getInit()) 5095 1.1 joerg if (!EvaluateVarDecl(Info, VD)) 5096 1.1 joerg return ESR_Failed; 5097 1.1 joerg // FIXME: If the variable has initialization that can't be jumped 5098 1.1 joerg // over, bail out of any immediately-surrounding compound-statement 5099 1.1 joerg // too. There can't be any case labels here. 5100 1.1 joerg } 5101 1.1 joerg } 5102 1.1 joerg return ESR_CaseNotFound; 5103 1.1 joerg } 5104 1.1 joerg 5105 1.1 joerg default: 5106 1.1 joerg return ESR_CaseNotFound; 5107 1.1 joerg } 5108 1.1 joerg } 5109 1.1 joerg 5110 1.1 joerg switch (S->getStmtClass()) { 5111 1.1 joerg default: 5112 1.1 joerg if (const Expr *E = dyn_cast<Expr>(S)) { 5113 1.1.1.2 joerg if (E->isValueDependent()) { 5114 1.1.1.2 joerg if (!EvaluateDependentExpr(E, Info)) 5115 1.1.1.2 joerg return ESR_Failed; 5116 1.1.1.2 joerg } else { 5117 1.1.1.2 joerg // Don't bother evaluating beyond an expression-statement which couldn't 5118 1.1.1.2 joerg // be evaluated. 5119 1.1.1.2 joerg // FIXME: Do we need the FullExpressionRAII object here? 5120 1.1.1.2 joerg // VisitExprWithCleanups should create one when necessary. 5121 1.1.1.2 joerg FullExpressionRAII Scope(Info); 5122 1.1.1.2 joerg if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy()) 5123 1.1.1.2 joerg return ESR_Failed; 5124 1.1.1.2 joerg } 5125 1.1 joerg return ESR_Succeeded; 5126 1.1 joerg } 5127 1.1 joerg 5128 1.1 joerg Info.FFDiag(S->getBeginLoc()); 5129 1.1 joerg return ESR_Failed; 5130 1.1 joerg 5131 1.1 joerg case Stmt::NullStmtClass: 5132 1.1 joerg return ESR_Succeeded; 5133 1.1 joerg 5134 1.1 joerg case Stmt::DeclStmtClass: { 5135 1.1 joerg const DeclStmt *DS = cast<DeclStmt>(S); 5136 1.1 joerg for (const auto *D : DS->decls()) { 5137 1.1 joerg // Each declaration initialization is its own full-expression. 5138 1.1 joerg FullExpressionRAII Scope(Info); 5139 1.1 joerg if (!EvaluateDecl(Info, D) && !Info.noteFailure()) 5140 1.1 joerg return ESR_Failed; 5141 1.1 joerg if (!Scope.destroy()) 5142 1.1 joerg return ESR_Failed; 5143 1.1 joerg } 5144 1.1 joerg return ESR_Succeeded; 5145 1.1 joerg } 5146 1.1 joerg 5147 1.1 joerg case Stmt::ReturnStmtClass: { 5148 1.1 joerg const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue(); 5149 1.1 joerg FullExpressionRAII Scope(Info); 5150 1.1.1.2 joerg if (RetExpr && RetExpr->isValueDependent()) { 5151 1.1.1.2 joerg EvaluateDependentExpr(RetExpr, Info); 5152 1.1.1.2 joerg // We know we returned, but we don't know what the value is. 5153 1.1.1.2 joerg return ESR_Failed; 5154 1.1.1.2 joerg } 5155 1.1 joerg if (RetExpr && 5156 1.1 joerg !(Result.Slot 5157 1.1 joerg ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr) 5158 1.1 joerg : Evaluate(Result.Value, Info, RetExpr))) 5159 1.1 joerg return ESR_Failed; 5160 1.1 joerg return Scope.destroy() ? ESR_Returned : ESR_Failed; 5161 1.1 joerg } 5162 1.1 joerg 5163 1.1 joerg case Stmt::CompoundStmtClass: { 5164 1.1 joerg BlockScopeRAII Scope(Info); 5165 1.1 joerg 5166 1.1 joerg const CompoundStmt *CS = cast<CompoundStmt>(S); 5167 1.1 joerg for (const auto *BI : CS->body()) { 5168 1.1 joerg EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case); 5169 1.1 joerg if (ESR == ESR_Succeeded) 5170 1.1 joerg Case = nullptr; 5171 1.1 joerg else if (ESR != ESR_CaseNotFound) { 5172 1.1 joerg if (ESR != ESR_Failed && !Scope.destroy()) 5173 1.1 joerg return ESR_Failed; 5174 1.1 joerg return ESR; 5175 1.1 joerg } 5176 1.1 joerg } 5177 1.1 joerg if (Case) 5178 1.1 joerg return ESR_CaseNotFound; 5179 1.1 joerg return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 5180 1.1 joerg } 5181 1.1 joerg 5182 1.1 joerg case Stmt::IfStmtClass: { 5183 1.1 joerg const IfStmt *IS = cast<IfStmt>(S); 5184 1.1 joerg 5185 1.1 joerg // Evaluate the condition, as either a var decl or as an expression. 5186 1.1 joerg BlockScopeRAII Scope(Info); 5187 1.1 joerg if (const Stmt *Init = IS->getInit()) { 5188 1.1 joerg EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); 5189 1.1 joerg if (ESR != ESR_Succeeded) { 5190 1.1 joerg if (ESR != ESR_Failed && !Scope.destroy()) 5191 1.1 joerg return ESR_Failed; 5192 1.1 joerg return ESR; 5193 1.1 joerg } 5194 1.1 joerg } 5195 1.1 joerg bool Cond; 5196 1.1 joerg if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond)) 5197 1.1 joerg return ESR_Failed; 5198 1.1 joerg 5199 1.1 joerg if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) { 5200 1.1 joerg EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt); 5201 1.1 joerg if (ESR != ESR_Succeeded) { 5202 1.1 joerg if (ESR != ESR_Failed && !Scope.destroy()) 5203 1.1 joerg return ESR_Failed; 5204 1.1 joerg return ESR; 5205 1.1 joerg } 5206 1.1 joerg } 5207 1.1 joerg return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 5208 1.1 joerg } 5209 1.1 joerg 5210 1.1 joerg case Stmt::WhileStmtClass: { 5211 1.1 joerg const WhileStmt *WS = cast<WhileStmt>(S); 5212 1.1 joerg while (true) { 5213 1.1 joerg BlockScopeRAII Scope(Info); 5214 1.1 joerg bool Continue; 5215 1.1 joerg if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(), 5216 1.1 joerg Continue)) 5217 1.1 joerg return ESR_Failed; 5218 1.1 joerg if (!Continue) 5219 1.1 joerg break; 5220 1.1 joerg 5221 1.1 joerg EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody()); 5222 1.1 joerg if (ESR != ESR_Continue) { 5223 1.1 joerg if (ESR != ESR_Failed && !Scope.destroy()) 5224 1.1 joerg return ESR_Failed; 5225 1.1 joerg return ESR; 5226 1.1 joerg } 5227 1.1 joerg if (!Scope.destroy()) 5228 1.1 joerg return ESR_Failed; 5229 1.1 joerg } 5230 1.1 joerg return ESR_Succeeded; 5231 1.1 joerg } 5232 1.1 joerg 5233 1.1 joerg case Stmt::DoStmtClass: { 5234 1.1 joerg const DoStmt *DS = cast<DoStmt>(S); 5235 1.1 joerg bool Continue; 5236 1.1 joerg do { 5237 1.1 joerg EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case); 5238 1.1 joerg if (ESR != ESR_Continue) 5239 1.1 joerg return ESR; 5240 1.1 joerg Case = nullptr; 5241 1.1 joerg 5242 1.1.1.2 joerg if (DS->getCond()->isValueDependent()) { 5243 1.1.1.2 joerg EvaluateDependentExpr(DS->getCond(), Info); 5244 1.1.1.2 joerg // Bailout as we don't know whether to keep going or terminate the loop. 5245 1.1.1.2 joerg return ESR_Failed; 5246 1.1.1.2 joerg } 5247 1.1 joerg FullExpressionRAII CondScope(Info); 5248 1.1 joerg if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) || 5249 1.1 joerg !CondScope.destroy()) 5250 1.1 joerg return ESR_Failed; 5251 1.1 joerg } while (Continue); 5252 1.1 joerg return ESR_Succeeded; 5253 1.1 joerg } 5254 1.1 joerg 5255 1.1 joerg case Stmt::ForStmtClass: { 5256 1.1 joerg const ForStmt *FS = cast<ForStmt>(S); 5257 1.1 joerg BlockScopeRAII ForScope(Info); 5258 1.1 joerg if (FS->getInit()) { 5259 1.1 joerg EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); 5260 1.1 joerg if (ESR != ESR_Succeeded) { 5261 1.1 joerg if (ESR != ESR_Failed && !ForScope.destroy()) 5262 1.1 joerg return ESR_Failed; 5263 1.1 joerg return ESR; 5264 1.1 joerg } 5265 1.1 joerg } 5266 1.1 joerg while (true) { 5267 1.1 joerg BlockScopeRAII IterScope(Info); 5268 1.1 joerg bool Continue = true; 5269 1.1 joerg if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(), 5270 1.1 joerg FS->getCond(), Continue)) 5271 1.1 joerg return ESR_Failed; 5272 1.1 joerg if (!Continue) 5273 1.1 joerg break; 5274 1.1 joerg 5275 1.1 joerg EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody()); 5276 1.1 joerg if (ESR != ESR_Continue) { 5277 1.1 joerg if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy())) 5278 1.1 joerg return ESR_Failed; 5279 1.1 joerg return ESR; 5280 1.1 joerg } 5281 1.1 joerg 5282 1.1.1.2 joerg if (const auto *Inc = FS->getInc()) { 5283 1.1.1.2 joerg if (Inc->isValueDependent()) { 5284 1.1.1.2 joerg if (!EvaluateDependentExpr(Inc, Info)) 5285 1.1.1.2 joerg return ESR_Failed; 5286 1.1.1.2 joerg } else { 5287 1.1.1.2 joerg FullExpressionRAII IncScope(Info); 5288 1.1.1.2 joerg if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy()) 5289 1.1.1.2 joerg return ESR_Failed; 5290 1.1.1.2 joerg } 5291 1.1 joerg } 5292 1.1 joerg 5293 1.1 joerg if (!IterScope.destroy()) 5294 1.1 joerg return ESR_Failed; 5295 1.1 joerg } 5296 1.1 joerg return ForScope.destroy() ? ESR_Succeeded : ESR_Failed; 5297 1.1 joerg } 5298 1.1 joerg 5299 1.1 joerg case Stmt::CXXForRangeStmtClass: { 5300 1.1 joerg const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S); 5301 1.1 joerg BlockScopeRAII Scope(Info); 5302 1.1 joerg 5303 1.1 joerg // Evaluate the init-statement if present. 5304 1.1 joerg if (FS->getInit()) { 5305 1.1 joerg EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); 5306 1.1 joerg if (ESR != ESR_Succeeded) { 5307 1.1 joerg if (ESR != ESR_Failed && !Scope.destroy()) 5308 1.1 joerg return ESR_Failed; 5309 1.1 joerg return ESR; 5310 1.1 joerg } 5311 1.1 joerg } 5312 1.1 joerg 5313 1.1 joerg // Initialize the __range variable. 5314 1.1 joerg EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt()); 5315 1.1 joerg if (ESR != ESR_Succeeded) { 5316 1.1 joerg if (ESR != ESR_Failed && !Scope.destroy()) 5317 1.1 joerg return ESR_Failed; 5318 1.1 joerg return ESR; 5319 1.1 joerg } 5320 1.1 joerg 5321 1.1 joerg // Create the __begin and __end iterators. 5322 1.1 joerg ESR = EvaluateStmt(Result, Info, FS->getBeginStmt()); 5323 1.1 joerg if (ESR != ESR_Succeeded) { 5324 1.1 joerg if (ESR != ESR_Failed && !Scope.destroy()) 5325 1.1 joerg return ESR_Failed; 5326 1.1 joerg return ESR; 5327 1.1 joerg } 5328 1.1 joerg ESR = EvaluateStmt(Result, Info, FS->getEndStmt()); 5329 1.1 joerg if (ESR != ESR_Succeeded) { 5330 1.1 joerg if (ESR != ESR_Failed && !Scope.destroy()) 5331 1.1 joerg return ESR_Failed; 5332 1.1 joerg return ESR; 5333 1.1 joerg } 5334 1.1 joerg 5335 1.1 joerg while (true) { 5336 1.1 joerg // Condition: __begin != __end. 5337 1.1 joerg { 5338 1.1.1.2 joerg if (FS->getCond()->isValueDependent()) { 5339 1.1.1.2 joerg EvaluateDependentExpr(FS->getCond(), Info); 5340 1.1.1.2 joerg // We don't know whether to keep going or terminate the loop. 5341 1.1.1.2 joerg return ESR_Failed; 5342 1.1.1.2 joerg } 5343 1.1 joerg bool Continue = true; 5344 1.1 joerg FullExpressionRAII CondExpr(Info); 5345 1.1 joerg if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info)) 5346 1.1 joerg return ESR_Failed; 5347 1.1 joerg if (!Continue) 5348 1.1 joerg break; 5349 1.1 joerg } 5350 1.1 joerg 5351 1.1 joerg // User's variable declaration, initialized by *__begin. 5352 1.1 joerg BlockScopeRAII InnerScope(Info); 5353 1.1 joerg ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt()); 5354 1.1 joerg if (ESR != ESR_Succeeded) { 5355 1.1 joerg if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy())) 5356 1.1 joerg return ESR_Failed; 5357 1.1 joerg return ESR; 5358 1.1 joerg } 5359 1.1 joerg 5360 1.1 joerg // Loop body. 5361 1.1 joerg ESR = EvaluateLoopBody(Result, Info, FS->getBody()); 5362 1.1 joerg if (ESR != ESR_Continue) { 5363 1.1 joerg if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy())) 5364 1.1 joerg return ESR_Failed; 5365 1.1 joerg return ESR; 5366 1.1 joerg } 5367 1.1.1.2 joerg if (FS->getInc()->isValueDependent()) { 5368 1.1.1.2 joerg if (!EvaluateDependentExpr(FS->getInc(), Info)) 5369 1.1.1.2 joerg return ESR_Failed; 5370 1.1.1.2 joerg } else { 5371 1.1.1.2 joerg // Increment: ++__begin 5372 1.1.1.2 joerg if (!EvaluateIgnoredValue(Info, FS->getInc())) 5373 1.1.1.2 joerg return ESR_Failed; 5374 1.1.1.2 joerg } 5375 1.1 joerg 5376 1.1 joerg if (!InnerScope.destroy()) 5377 1.1 joerg return ESR_Failed; 5378 1.1 joerg } 5379 1.1 joerg 5380 1.1 joerg return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 5381 1.1 joerg } 5382 1.1 joerg 5383 1.1 joerg case Stmt::SwitchStmtClass: 5384 1.1 joerg return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S)); 5385 1.1 joerg 5386 1.1 joerg case Stmt::ContinueStmtClass: 5387 1.1 joerg return ESR_Continue; 5388 1.1 joerg 5389 1.1 joerg case Stmt::BreakStmtClass: 5390 1.1 joerg return ESR_Break; 5391 1.1 joerg 5392 1.1 joerg case Stmt::LabelStmtClass: 5393 1.1 joerg return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case); 5394 1.1 joerg 5395 1.1 joerg case Stmt::AttributedStmtClass: 5396 1.1 joerg // As a general principle, C++11 attributes can be ignored without 5397 1.1 joerg // any semantic impact. 5398 1.1 joerg return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(), 5399 1.1 joerg Case); 5400 1.1 joerg 5401 1.1 joerg case Stmt::CaseStmtClass: 5402 1.1 joerg case Stmt::DefaultStmtClass: 5403 1.1 joerg return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case); 5404 1.1 joerg case Stmt::CXXTryStmtClass: 5405 1.1 joerg // Evaluate try blocks by evaluating all sub statements. 5406 1.1 joerg return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case); 5407 1.1 joerg } 5408 1.1 joerg } 5409 1.1 joerg 5410 1.1 joerg /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial 5411 1.1 joerg /// default constructor. If so, we'll fold it whether or not it's marked as 5412 1.1 joerg /// constexpr. If it is marked as constexpr, we will never implicitly define it, 5413 1.1 joerg /// so we need special handling. 5414 1.1 joerg static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc, 5415 1.1 joerg const CXXConstructorDecl *CD, 5416 1.1 joerg bool IsValueInitialization) { 5417 1.1 joerg if (!CD->isTrivial() || !CD->isDefaultConstructor()) 5418 1.1 joerg return false; 5419 1.1 joerg 5420 1.1 joerg // Value-initialization does not call a trivial default constructor, so such a 5421 1.1 joerg // call is a core constant expression whether or not the constructor is 5422 1.1 joerg // constexpr. 5423 1.1 joerg if (!CD->isConstexpr() && !IsValueInitialization) { 5424 1.1 joerg if (Info.getLangOpts().CPlusPlus11) { 5425 1.1 joerg // FIXME: If DiagDecl is an implicitly-declared special member function, 5426 1.1 joerg // we should be much more explicit about why it's not constexpr. 5427 1.1 joerg Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1) 5428 1.1 joerg << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD; 5429 1.1 joerg Info.Note(CD->getLocation(), diag::note_declared_at); 5430 1.1 joerg } else { 5431 1.1 joerg Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr); 5432 1.1 joerg } 5433 1.1 joerg } 5434 1.1 joerg return true; 5435 1.1 joerg } 5436 1.1 joerg 5437 1.1 joerg /// CheckConstexprFunction - Check that a function can be called in a constant 5438 1.1 joerg /// expression. 5439 1.1 joerg static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc, 5440 1.1 joerg const FunctionDecl *Declaration, 5441 1.1 joerg const FunctionDecl *Definition, 5442 1.1 joerg const Stmt *Body) { 5443 1.1 joerg // Potential constant expressions can contain calls to declared, but not yet 5444 1.1 joerg // defined, constexpr functions. 5445 1.1 joerg if (Info.checkingPotentialConstantExpression() && !Definition && 5446 1.1 joerg Declaration->isConstexpr()) 5447 1.1 joerg return false; 5448 1.1 joerg 5449 1.1 joerg // Bail out if the function declaration itself is invalid. We will 5450 1.1 joerg // have produced a relevant diagnostic while parsing it, so just 5451 1.1 joerg // note the problematic sub-expression. 5452 1.1 joerg if (Declaration->isInvalidDecl()) { 5453 1.1 joerg Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 5454 1.1 joerg return false; 5455 1.1 joerg } 5456 1.1 joerg 5457 1.1 joerg // DR1872: An instantiated virtual constexpr function can't be called in a 5458 1.1 joerg // constant expression (prior to C++20). We can still constant-fold such a 5459 1.1 joerg // call. 5460 1.1.1.2 joerg if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) && 5461 1.1 joerg cast<CXXMethodDecl>(Declaration)->isVirtual()) 5462 1.1 joerg Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call); 5463 1.1 joerg 5464 1.1 joerg if (Definition && Definition->isInvalidDecl()) { 5465 1.1 joerg Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 5466 1.1 joerg return false; 5467 1.1 joerg } 5468 1.1 joerg 5469 1.1 joerg // Can we evaluate this function call? 5470 1.1 joerg if (Definition && Definition->isConstexpr() && Body) 5471 1.1 joerg return true; 5472 1.1 joerg 5473 1.1 joerg if (Info.getLangOpts().CPlusPlus11) { 5474 1.1 joerg const FunctionDecl *DiagDecl = Definition ? Definition : Declaration; 5475 1.1 joerg 5476 1.1 joerg // If this function is not constexpr because it is an inherited 5477 1.1 joerg // non-constexpr constructor, diagnose that directly. 5478 1.1 joerg auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl); 5479 1.1 joerg if (CD && CD->isInheritingConstructor()) { 5480 1.1 joerg auto *Inherited = CD->getInheritedConstructor().getConstructor(); 5481 1.1 joerg if (!Inherited->isConstexpr()) 5482 1.1 joerg DiagDecl = CD = Inherited; 5483 1.1 joerg } 5484 1.1 joerg 5485 1.1 joerg // FIXME: If DiagDecl is an implicitly-declared special member function 5486 1.1 joerg // or an inheriting constructor, we should be much more explicit about why 5487 1.1 joerg // it's not constexpr. 5488 1.1 joerg if (CD && CD->isInheritingConstructor()) 5489 1.1 joerg Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1) 5490 1.1 joerg << CD->getInheritedConstructor().getConstructor()->getParent(); 5491 1.1 joerg else 5492 1.1 joerg Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1) 5493 1.1 joerg << DiagDecl->isConstexpr() << (bool)CD << DiagDecl; 5494 1.1 joerg Info.Note(DiagDecl->getLocation(), diag::note_declared_at); 5495 1.1 joerg } else { 5496 1.1 joerg Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 5497 1.1 joerg } 5498 1.1 joerg return false; 5499 1.1 joerg } 5500 1.1 joerg 5501 1.1 joerg namespace { 5502 1.1 joerg struct CheckDynamicTypeHandler { 5503 1.1 joerg AccessKinds AccessKind; 5504 1.1 joerg typedef bool result_type; 5505 1.1 joerg bool failed() { return false; } 5506 1.1 joerg bool found(APValue &Subobj, QualType SubobjType) { return true; } 5507 1.1 joerg bool found(APSInt &Value, QualType SubobjType) { return true; } 5508 1.1 joerg bool found(APFloat &Value, QualType SubobjType) { return true; } 5509 1.1 joerg }; 5510 1.1 joerg } // end anonymous namespace 5511 1.1 joerg 5512 1.1 joerg /// Check that we can access the notional vptr of an object / determine its 5513 1.1 joerg /// dynamic type. 5514 1.1 joerg static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This, 5515 1.1 joerg AccessKinds AK, bool Polymorphic) { 5516 1.1 joerg if (This.Designator.Invalid) 5517 1.1 joerg return false; 5518 1.1 joerg 5519 1.1 joerg CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType()); 5520 1.1 joerg 5521 1.1 joerg if (!Obj) 5522 1.1 joerg return false; 5523 1.1 joerg 5524 1.1 joerg if (!Obj.Value) { 5525 1.1 joerg // The object is not usable in constant expressions, so we can't inspect 5526 1.1 joerg // its value to see if it's in-lifetime or what the active union members 5527 1.1 joerg // are. We can still check for a one-past-the-end lvalue. 5528 1.1 joerg if (This.Designator.isOnePastTheEnd() || 5529 1.1 joerg This.Designator.isMostDerivedAnUnsizedArray()) { 5530 1.1 joerg Info.FFDiag(E, This.Designator.isOnePastTheEnd() 5531 1.1 joerg ? diag::note_constexpr_access_past_end 5532 1.1 joerg : diag::note_constexpr_access_unsized_array) 5533 1.1 joerg << AK; 5534 1.1 joerg return false; 5535 1.1 joerg } else if (Polymorphic) { 5536 1.1 joerg // Conservatively refuse to perform a polymorphic operation if we would 5537 1.1 joerg // not be able to read a notional 'vptr' value. 5538 1.1 joerg APValue Val; 5539 1.1 joerg This.moveInto(Val); 5540 1.1 joerg QualType StarThisType = 5541 1.1 joerg Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx)); 5542 1.1 joerg Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type) 5543 1.1 joerg << AK << Val.getAsString(Info.Ctx, StarThisType); 5544 1.1 joerg return false; 5545 1.1 joerg } 5546 1.1 joerg return true; 5547 1.1 joerg } 5548 1.1 joerg 5549 1.1 joerg CheckDynamicTypeHandler Handler{AK}; 5550 1.1 joerg return Obj && findSubobject(Info, E, Obj, This.Designator, Handler); 5551 1.1 joerg } 5552 1.1 joerg 5553 1.1 joerg /// Check that the pointee of the 'this' pointer in a member function call is 5554 1.1 joerg /// either within its lifetime or in its period of construction or destruction. 5555 1.1 joerg static bool 5556 1.1 joerg checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E, 5557 1.1 joerg const LValue &This, 5558 1.1 joerg const CXXMethodDecl *NamedMember) { 5559 1.1 joerg return checkDynamicType( 5560 1.1 joerg Info, E, This, 5561 1.1 joerg isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false); 5562 1.1 joerg } 5563 1.1 joerg 5564 1.1 joerg struct DynamicType { 5565 1.1 joerg /// The dynamic class type of the object. 5566 1.1 joerg const CXXRecordDecl *Type; 5567 1.1 joerg /// The corresponding path length in the lvalue. 5568 1.1 joerg unsigned PathLength; 5569 1.1 joerg }; 5570 1.1 joerg 5571 1.1 joerg static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator, 5572 1.1 joerg unsigned PathLength) { 5573 1.1 joerg assert(PathLength >= Designator.MostDerivedPathLength && PathLength <= 5574 1.1 joerg Designator.Entries.size() && "invalid path length"); 5575 1.1 joerg return (PathLength == Designator.MostDerivedPathLength) 5576 1.1 joerg ? Designator.MostDerivedType->getAsCXXRecordDecl() 5577 1.1 joerg : getAsBaseClass(Designator.Entries[PathLength - 1]); 5578 1.1 joerg } 5579 1.1 joerg 5580 1.1 joerg /// Determine the dynamic type of an object. 5581 1.1 joerg static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E, 5582 1.1 joerg LValue &This, AccessKinds AK) { 5583 1.1 joerg // If we don't have an lvalue denoting an object of class type, there is no 5584 1.1 joerg // meaningful dynamic type. (We consider objects of non-class type to have no 5585 1.1 joerg // dynamic type.) 5586 1.1 joerg if (!checkDynamicType(Info, E, This, AK, true)) 5587 1.1 joerg return None; 5588 1.1 joerg 5589 1.1 joerg // Refuse to compute a dynamic type in the presence of virtual bases. This 5590 1.1 joerg // shouldn't happen other than in constant-folding situations, since literal 5591 1.1 joerg // types can't have virtual bases. 5592 1.1 joerg // 5593 1.1 joerg // Note that consumers of DynamicType assume that the type has no virtual 5594 1.1 joerg // bases, and will need modifications if this restriction is relaxed. 5595 1.1 joerg const CXXRecordDecl *Class = 5596 1.1 joerg This.Designator.MostDerivedType->getAsCXXRecordDecl(); 5597 1.1 joerg if (!Class || Class->getNumVBases()) { 5598 1.1 joerg Info.FFDiag(E); 5599 1.1 joerg return None; 5600 1.1 joerg } 5601 1.1 joerg 5602 1.1 joerg // FIXME: For very deep class hierarchies, it might be beneficial to use a 5603 1.1 joerg // binary search here instead. But the overwhelmingly common case is that 5604 1.1 joerg // we're not in the middle of a constructor, so it probably doesn't matter 5605 1.1 joerg // in practice. 5606 1.1 joerg ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries; 5607 1.1 joerg for (unsigned PathLength = This.Designator.MostDerivedPathLength; 5608 1.1 joerg PathLength <= Path.size(); ++PathLength) { 5609 1.1 joerg switch (Info.isEvaluatingCtorDtor(This.getLValueBase(), 5610 1.1 joerg Path.slice(0, PathLength))) { 5611 1.1 joerg case ConstructionPhase::Bases: 5612 1.1 joerg case ConstructionPhase::DestroyingBases: 5613 1.1 joerg // We're constructing or destroying a base class. This is not the dynamic 5614 1.1 joerg // type. 5615 1.1 joerg break; 5616 1.1 joerg 5617 1.1 joerg case ConstructionPhase::None: 5618 1.1 joerg case ConstructionPhase::AfterBases: 5619 1.1.1.2 joerg case ConstructionPhase::AfterFields: 5620 1.1 joerg case ConstructionPhase::Destroying: 5621 1.1 joerg // We've finished constructing the base classes and not yet started 5622 1.1 joerg // destroying them again, so this is the dynamic type. 5623 1.1 joerg return DynamicType{getBaseClassType(This.Designator, PathLength), 5624 1.1 joerg PathLength}; 5625 1.1 joerg } 5626 1.1 joerg } 5627 1.1 joerg 5628 1.1 joerg // CWG issue 1517: we're constructing a base class of the object described by 5629 1.1 joerg // 'This', so that object has not yet begun its period of construction and 5630 1.1 joerg // any polymorphic operation on it results in undefined behavior. 5631 1.1 joerg Info.FFDiag(E); 5632 1.1 joerg return None; 5633 1.1 joerg } 5634 1.1 joerg 5635 1.1 joerg /// Perform virtual dispatch. 5636 1.1 joerg static const CXXMethodDecl *HandleVirtualDispatch( 5637 1.1 joerg EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found, 5638 1.1 joerg llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) { 5639 1.1 joerg Optional<DynamicType> DynType = ComputeDynamicType( 5640 1.1 joerg Info, E, This, 5641 1.1 joerg isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall); 5642 1.1 joerg if (!DynType) 5643 1.1 joerg return nullptr; 5644 1.1 joerg 5645 1.1 joerg // Find the final overrider. It must be declared in one of the classes on the 5646 1.1 joerg // path from the dynamic type to the static type. 5647 1.1 joerg // FIXME: If we ever allow literal types to have virtual base classes, that 5648 1.1 joerg // won't be true. 5649 1.1 joerg const CXXMethodDecl *Callee = Found; 5650 1.1 joerg unsigned PathLength = DynType->PathLength; 5651 1.1 joerg for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) { 5652 1.1 joerg const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength); 5653 1.1 joerg const CXXMethodDecl *Overrider = 5654 1.1 joerg Found->getCorrespondingMethodDeclaredInClass(Class, false); 5655 1.1 joerg if (Overrider) { 5656 1.1 joerg Callee = Overrider; 5657 1.1 joerg break; 5658 1.1 joerg } 5659 1.1 joerg } 5660 1.1 joerg 5661 1.1 joerg // C++2a [class.abstract]p6: 5662 1.1 joerg // the effect of making a virtual call to a pure virtual function [...] is 5663 1.1 joerg // undefined 5664 1.1 joerg if (Callee->isPure()) { 5665 1.1 joerg Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee; 5666 1.1 joerg Info.Note(Callee->getLocation(), diag::note_declared_at); 5667 1.1 joerg return nullptr; 5668 1.1 joerg } 5669 1.1 joerg 5670 1.1 joerg // If necessary, walk the rest of the path to determine the sequence of 5671 1.1 joerg // covariant adjustment steps to apply. 5672 1.1 joerg if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(), 5673 1.1 joerg Found->getReturnType())) { 5674 1.1 joerg CovariantAdjustmentPath.push_back(Callee->getReturnType()); 5675 1.1 joerg for (unsigned CovariantPathLength = PathLength + 1; 5676 1.1 joerg CovariantPathLength != This.Designator.Entries.size(); 5677 1.1 joerg ++CovariantPathLength) { 5678 1.1 joerg const CXXRecordDecl *NextClass = 5679 1.1 joerg getBaseClassType(This.Designator, CovariantPathLength); 5680 1.1 joerg const CXXMethodDecl *Next = 5681 1.1 joerg Found->getCorrespondingMethodDeclaredInClass(NextClass, false); 5682 1.1 joerg if (Next && !Info.Ctx.hasSameUnqualifiedType( 5683 1.1 joerg Next->getReturnType(), CovariantAdjustmentPath.back())) 5684 1.1 joerg CovariantAdjustmentPath.push_back(Next->getReturnType()); 5685 1.1 joerg } 5686 1.1 joerg if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(), 5687 1.1 joerg CovariantAdjustmentPath.back())) 5688 1.1 joerg CovariantAdjustmentPath.push_back(Found->getReturnType()); 5689 1.1 joerg } 5690 1.1 joerg 5691 1.1 joerg // Perform 'this' adjustment. 5692 1.1 joerg if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength)) 5693 1.1 joerg return nullptr; 5694 1.1 joerg 5695 1.1 joerg return Callee; 5696 1.1 joerg } 5697 1.1 joerg 5698 1.1 joerg /// Perform the adjustment from a value returned by a virtual function to 5699 1.1 joerg /// a value of the statically expected type, which may be a pointer or 5700 1.1 joerg /// reference to a base class of the returned type. 5701 1.1 joerg static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E, 5702 1.1 joerg APValue &Result, 5703 1.1 joerg ArrayRef<QualType> Path) { 5704 1.1 joerg assert(Result.isLValue() && 5705 1.1 joerg "unexpected kind of APValue for covariant return"); 5706 1.1 joerg if (Result.isNullPointer()) 5707 1.1 joerg return true; 5708 1.1 joerg 5709 1.1 joerg LValue LVal; 5710 1.1 joerg LVal.setFrom(Info.Ctx, Result); 5711 1.1 joerg 5712 1.1 joerg const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl(); 5713 1.1 joerg for (unsigned I = 1; I != Path.size(); ++I) { 5714 1.1 joerg const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl(); 5715 1.1 joerg assert(OldClass && NewClass && "unexpected kind of covariant return"); 5716 1.1 joerg if (OldClass != NewClass && 5717 1.1 joerg !CastToBaseClass(Info, E, LVal, OldClass, NewClass)) 5718 1.1 joerg return false; 5719 1.1 joerg OldClass = NewClass; 5720 1.1 joerg } 5721 1.1 joerg 5722 1.1 joerg LVal.moveInto(Result); 5723 1.1 joerg return true; 5724 1.1 joerg } 5725 1.1 joerg 5726 1.1 joerg /// Determine whether \p Base, which is known to be a direct base class of 5727 1.1 joerg /// \p Derived, is a public base class. 5728 1.1 joerg static bool isBaseClassPublic(const CXXRecordDecl *Derived, 5729 1.1 joerg const CXXRecordDecl *Base) { 5730 1.1 joerg for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) { 5731 1.1 joerg auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl(); 5732 1.1 joerg if (BaseClass && declaresSameEntity(BaseClass, Base)) 5733 1.1 joerg return BaseSpec.getAccessSpecifier() == AS_public; 5734 1.1 joerg } 5735 1.1 joerg llvm_unreachable("Base is not a direct base of Derived"); 5736 1.1 joerg } 5737 1.1 joerg 5738 1.1 joerg /// Apply the given dynamic cast operation on the provided lvalue. 5739 1.1 joerg /// 5740 1.1 joerg /// This implements the hard case of dynamic_cast, requiring a "runtime check" 5741 1.1 joerg /// to find a suitable target subobject. 5742 1.1 joerg static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E, 5743 1.1 joerg LValue &Ptr) { 5744 1.1 joerg // We can't do anything with a non-symbolic pointer value. 5745 1.1 joerg SubobjectDesignator &D = Ptr.Designator; 5746 1.1 joerg if (D.Invalid) 5747 1.1 joerg return false; 5748 1.1 joerg 5749 1.1 joerg // C++ [expr.dynamic.cast]p6: 5750 1.1 joerg // If v is a null pointer value, the result is a null pointer value. 5751 1.1 joerg if (Ptr.isNullPointer() && !E->isGLValue()) 5752 1.1 joerg return true; 5753 1.1 joerg 5754 1.1 joerg // For all the other cases, we need the pointer to point to an object within 5755 1.1 joerg // its lifetime / period of construction / destruction, and we need to know 5756 1.1 joerg // its dynamic type. 5757 1.1 joerg Optional<DynamicType> DynType = 5758 1.1 joerg ComputeDynamicType(Info, E, Ptr, AK_DynamicCast); 5759 1.1 joerg if (!DynType) 5760 1.1 joerg return false; 5761 1.1 joerg 5762 1.1 joerg // C++ [expr.dynamic.cast]p7: 5763 1.1 joerg // If T is "pointer to cv void", then the result is a pointer to the most 5764 1.1 joerg // derived object 5765 1.1 joerg if (E->getType()->isVoidPointerType()) 5766 1.1 joerg return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength); 5767 1.1 joerg 5768 1.1 joerg const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl(); 5769 1.1 joerg assert(C && "dynamic_cast target is not void pointer nor class"); 5770 1.1 joerg CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C)); 5771 1.1 joerg 5772 1.1 joerg auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) { 5773 1.1 joerg // C++ [expr.dynamic.cast]p9: 5774 1.1 joerg if (!E->isGLValue()) { 5775 1.1 joerg // The value of a failed cast to pointer type is the null pointer value 5776 1.1 joerg // of the required result type. 5777 1.1 joerg Ptr.setNull(Info.Ctx, E->getType()); 5778 1.1 joerg return true; 5779 1.1 joerg } 5780 1.1 joerg 5781 1.1 joerg // A failed cast to reference type throws [...] std::bad_cast. 5782 1.1 joerg unsigned DiagKind; 5783 1.1 joerg if (!Paths && (declaresSameEntity(DynType->Type, C) || 5784 1.1 joerg DynType->Type->isDerivedFrom(C))) 5785 1.1 joerg DiagKind = 0; 5786 1.1 joerg else if (!Paths || Paths->begin() == Paths->end()) 5787 1.1 joerg DiagKind = 1; 5788 1.1 joerg else if (Paths->isAmbiguous(CQT)) 5789 1.1 joerg DiagKind = 2; 5790 1.1 joerg else { 5791 1.1 joerg assert(Paths->front().Access != AS_public && "why did the cast fail?"); 5792 1.1 joerg DiagKind = 3; 5793 1.1 joerg } 5794 1.1 joerg Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed) 5795 1.1 joerg << DiagKind << Ptr.Designator.getType(Info.Ctx) 5796 1.1 joerg << Info.Ctx.getRecordType(DynType->Type) 5797 1.1 joerg << E->getType().getUnqualifiedType(); 5798 1.1 joerg return false; 5799 1.1 joerg }; 5800 1.1 joerg 5801 1.1 joerg // Runtime check, phase 1: 5802 1.1 joerg // Walk from the base subobject towards the derived object looking for the 5803 1.1 joerg // target type. 5804 1.1 joerg for (int PathLength = Ptr.Designator.Entries.size(); 5805 1.1 joerg PathLength >= (int)DynType->PathLength; --PathLength) { 5806 1.1 joerg const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength); 5807 1.1 joerg if (declaresSameEntity(Class, C)) 5808 1.1 joerg return CastToDerivedClass(Info, E, Ptr, Class, PathLength); 5809 1.1 joerg // We can only walk across public inheritance edges. 5810 1.1 joerg if (PathLength > (int)DynType->PathLength && 5811 1.1 joerg !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1), 5812 1.1 joerg Class)) 5813 1.1 joerg return RuntimeCheckFailed(nullptr); 5814 1.1 joerg } 5815 1.1 joerg 5816 1.1 joerg // Runtime check, phase 2: 5817 1.1 joerg // Search the dynamic type for an unambiguous public base of type C. 5818 1.1 joerg CXXBasePaths Paths(/*FindAmbiguities=*/true, 5819 1.1 joerg /*RecordPaths=*/true, /*DetectVirtual=*/false); 5820 1.1 joerg if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) && 5821 1.1 joerg Paths.front().Access == AS_public) { 5822 1.1 joerg // Downcast to the dynamic type... 5823 1.1 joerg if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength)) 5824 1.1 joerg return false; 5825 1.1 joerg // ... then upcast to the chosen base class subobject. 5826 1.1 joerg for (CXXBasePathElement &Elem : Paths.front()) 5827 1.1 joerg if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base)) 5828 1.1 joerg return false; 5829 1.1 joerg return true; 5830 1.1 joerg } 5831 1.1 joerg 5832 1.1 joerg // Otherwise, the runtime check fails. 5833 1.1 joerg return RuntimeCheckFailed(&Paths); 5834 1.1 joerg } 5835 1.1 joerg 5836 1.1 joerg namespace { 5837 1.1 joerg struct StartLifetimeOfUnionMemberHandler { 5838 1.1.1.2 joerg EvalInfo &Info; 5839 1.1.1.2 joerg const Expr *LHSExpr; 5840 1.1 joerg const FieldDecl *Field; 5841 1.1.1.2 joerg bool DuringInit; 5842 1.1.1.2 joerg bool Failed = false; 5843 1.1 joerg static const AccessKinds AccessKind = AK_Assign; 5844 1.1 joerg 5845 1.1 joerg typedef bool result_type; 5846 1.1.1.2 joerg bool failed() { return Failed; } 5847 1.1 joerg bool found(APValue &Subobj, QualType SubobjType) { 5848 1.1 joerg // We are supposed to perform no initialization but begin the lifetime of 5849 1.1 joerg // the object. We interpret that as meaning to do what default 5850 1.1 joerg // initialization of the object would do if all constructors involved were 5851 1.1 joerg // trivial: 5852 1.1 joerg // * All base, non-variant member, and array element subobjects' lifetimes 5853 1.1 joerg // begin 5854 1.1 joerg // * No variant members' lifetimes begin 5855 1.1 joerg // * All scalar subobjects whose lifetimes begin have indeterminate values 5856 1.1 joerg assert(SubobjType->isUnionType()); 5857 1.1.1.2 joerg if (declaresSameEntity(Subobj.getUnionField(), Field)) { 5858 1.1.1.2 joerg // This union member is already active. If it's also in-lifetime, there's 5859 1.1.1.2 joerg // nothing to do. 5860 1.1.1.2 joerg if (Subobj.getUnionValue().hasValue()) 5861 1.1.1.2 joerg return true; 5862 1.1.1.2 joerg } else if (DuringInit) { 5863 1.1.1.2 joerg // We're currently in the process of initializing a different union 5864 1.1.1.2 joerg // member. If we carried on, that initialization would attempt to 5865 1.1.1.2 joerg // store to an inactive union member, resulting in undefined behavior. 5866 1.1.1.2 joerg Info.FFDiag(LHSExpr, 5867 1.1.1.2 joerg diag::note_constexpr_union_member_change_during_init); 5868 1.1.1.2 joerg return false; 5869 1.1.1.2 joerg } 5870 1.1.1.2 joerg APValue Result; 5871 1.1.1.2 joerg Failed = !getDefaultInitValue(Field->getType(), Result); 5872 1.1.1.2 joerg Subobj.setUnion(Field, Result); 5873 1.1 joerg return true; 5874 1.1 joerg } 5875 1.1 joerg bool found(APSInt &Value, QualType SubobjType) { 5876 1.1 joerg llvm_unreachable("wrong value kind for union object"); 5877 1.1 joerg } 5878 1.1 joerg bool found(APFloat &Value, QualType SubobjType) { 5879 1.1 joerg llvm_unreachable("wrong value kind for union object"); 5880 1.1 joerg } 5881 1.1 joerg }; 5882 1.1 joerg } // end anonymous namespace 5883 1.1 joerg 5884 1.1 joerg const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind; 5885 1.1 joerg 5886 1.1 joerg /// Handle a builtin simple-assignment or a call to a trivial assignment 5887 1.1 joerg /// operator whose left-hand side might involve a union member access. If it 5888 1.1 joerg /// does, implicitly start the lifetime of any accessed union elements per 5889 1.1 joerg /// C++20 [class.union]5. 5890 1.1 joerg static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr, 5891 1.1 joerg const LValue &LHS) { 5892 1.1 joerg if (LHS.InvalidBase || LHS.Designator.Invalid) 5893 1.1 joerg return false; 5894 1.1 joerg 5895 1.1 joerg llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths; 5896 1.1 joerg // C++ [class.union]p5: 5897 1.1 joerg // define the set S(E) of subexpressions of E as follows: 5898 1.1 joerg unsigned PathLength = LHS.Designator.Entries.size(); 5899 1.1 joerg for (const Expr *E = LHSExpr; E != nullptr;) { 5900 1.1 joerg // -- If E is of the form A.B, S(E) contains the elements of S(A)... 5901 1.1 joerg if (auto *ME = dyn_cast<MemberExpr>(E)) { 5902 1.1 joerg auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 5903 1.1 joerg // Note that we can't implicitly start the lifetime of a reference, 5904 1.1 joerg // so we don't need to proceed any further if we reach one. 5905 1.1 joerg if (!FD || FD->getType()->isReferenceType()) 5906 1.1 joerg break; 5907 1.1 joerg 5908 1.1 joerg // ... and also contains A.B if B names a union member ... 5909 1.1 joerg if (FD->getParent()->isUnion()) { 5910 1.1 joerg // ... of a non-class, non-array type, or of a class type with a 5911 1.1 joerg // trivial default constructor that is not deleted, or an array of 5912 1.1 joerg // such types. 5913 1.1 joerg auto *RD = 5914 1.1 joerg FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 5915 1.1 joerg if (!RD || RD->hasTrivialDefaultConstructor()) 5916 1.1 joerg UnionPathLengths.push_back({PathLength - 1, FD}); 5917 1.1 joerg } 5918 1.1 joerg 5919 1.1 joerg E = ME->getBase(); 5920 1.1 joerg --PathLength; 5921 1.1 joerg assert(declaresSameEntity(FD, 5922 1.1 joerg LHS.Designator.Entries[PathLength] 5923 1.1 joerg .getAsBaseOrMember().getPointer())); 5924 1.1 joerg 5925 1.1 joerg // -- If E is of the form A[B] and is interpreted as a built-in array 5926 1.1 joerg // subscripting operator, S(E) is [S(the array operand, if any)]. 5927 1.1 joerg } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) { 5928 1.1 joerg // Step over an ArrayToPointerDecay implicit cast. 5929 1.1 joerg auto *Base = ASE->getBase()->IgnoreImplicit(); 5930 1.1 joerg if (!Base->getType()->isArrayType()) 5931 1.1 joerg break; 5932 1.1 joerg 5933 1.1 joerg E = Base; 5934 1.1 joerg --PathLength; 5935 1.1 joerg 5936 1.1 joerg } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) { 5937 1.1 joerg // Step over a derived-to-base conversion. 5938 1.1 joerg E = ICE->getSubExpr(); 5939 1.1 joerg if (ICE->getCastKind() == CK_NoOp) 5940 1.1 joerg continue; 5941 1.1 joerg if (ICE->getCastKind() != CK_DerivedToBase && 5942 1.1 joerg ICE->getCastKind() != CK_UncheckedDerivedToBase) 5943 1.1 joerg break; 5944 1.1 joerg // Walk path backwards as we walk up from the base to the derived class. 5945 1.1 joerg for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) { 5946 1.1 joerg --PathLength; 5947 1.1 joerg (void)Elt; 5948 1.1 joerg assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(), 5949 1.1 joerg LHS.Designator.Entries[PathLength] 5950 1.1 joerg .getAsBaseOrMember().getPointer())); 5951 1.1 joerg } 5952 1.1 joerg 5953 1.1 joerg // -- Otherwise, S(E) is empty. 5954 1.1 joerg } else { 5955 1.1 joerg break; 5956 1.1 joerg } 5957 1.1 joerg } 5958 1.1 joerg 5959 1.1 joerg // Common case: no unions' lifetimes are started. 5960 1.1 joerg if (UnionPathLengths.empty()) 5961 1.1 joerg return true; 5962 1.1 joerg 5963 1.1 joerg // if modification of X [would access an inactive union member], an object 5964 1.1 joerg // of the type of X is implicitly created 5965 1.1 joerg CompleteObject Obj = 5966 1.1 joerg findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType()); 5967 1.1 joerg if (!Obj) 5968 1.1 joerg return false; 5969 1.1 joerg for (std::pair<unsigned, const FieldDecl *> LengthAndField : 5970 1.1 joerg llvm::reverse(UnionPathLengths)) { 5971 1.1 joerg // Form a designator for the union object. 5972 1.1 joerg SubobjectDesignator D = LHS.Designator; 5973 1.1 joerg D.truncate(Info.Ctx, LHS.Base, LengthAndField.first); 5974 1.1 joerg 5975 1.1.1.2 joerg bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) == 5976 1.1.1.2 joerg ConstructionPhase::AfterBases; 5977 1.1.1.2 joerg StartLifetimeOfUnionMemberHandler StartLifetime{ 5978 1.1.1.2 joerg Info, LHSExpr, LengthAndField.second, DuringInit}; 5979 1.1 joerg if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime)) 5980 1.1 joerg return false; 5981 1.1 joerg } 5982 1.1 joerg 5983 1.1 joerg return true; 5984 1.1 joerg } 5985 1.1 joerg 5986 1.1.1.2 joerg static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg, 5987 1.1.1.2 joerg CallRef Call, EvalInfo &Info, 5988 1.1.1.2 joerg bool NonNull = false) { 5989 1.1.1.2 joerg LValue LV; 5990 1.1.1.2 joerg // Create the parameter slot and register its destruction. For a vararg 5991 1.1.1.2 joerg // argument, create a temporary. 5992 1.1.1.2 joerg // FIXME: For calling conventions that destroy parameters in the callee, 5993 1.1.1.2 joerg // should we consider performing destruction when the function returns 5994 1.1.1.2 joerg // instead? 5995 1.1.1.2 joerg APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV) 5996 1.1.1.2 joerg : Info.CurrentCall->createTemporary(Arg, Arg->getType(), 5997 1.1.1.2 joerg ScopeKind::Call, LV); 5998 1.1.1.2 joerg if (!EvaluateInPlace(V, Info, LV, Arg)) 5999 1.1.1.2 joerg return false; 6000 1.1.1.2 joerg 6001 1.1.1.2 joerg // Passing a null pointer to an __attribute__((nonnull)) parameter results in 6002 1.1.1.2 joerg // undefined behavior, so is non-constant. 6003 1.1.1.2 joerg if (NonNull && V.isLValue() && V.isNullPointer()) { 6004 1.1.1.2 joerg Info.CCEDiag(Arg, diag::note_non_null_attribute_failed); 6005 1.1 joerg return false; 6006 1.1 joerg } 6007 1.1 joerg 6008 1.1.1.2 joerg return true; 6009 1.1 joerg } 6010 1.1 joerg 6011 1.1.1.2 joerg /// Evaluate the arguments to a function call. 6012 1.1.1.2 joerg static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call, 6013 1.1.1.2 joerg EvalInfo &Info, const FunctionDecl *Callee, 6014 1.1.1.2 joerg bool RightToLeft = false) { 6015 1.1 joerg bool Success = true; 6016 1.1 joerg llvm::SmallBitVector ForbiddenNullArgs; 6017 1.1 joerg if (Callee->hasAttr<NonNullAttr>()) { 6018 1.1 joerg ForbiddenNullArgs.resize(Args.size()); 6019 1.1 joerg for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) { 6020 1.1 joerg if (!Attr->args_size()) { 6021 1.1 joerg ForbiddenNullArgs.set(); 6022 1.1 joerg break; 6023 1.1 joerg } else 6024 1.1 joerg for (auto Idx : Attr->args()) { 6025 1.1 joerg unsigned ASTIdx = Idx.getASTIndex(); 6026 1.1 joerg if (ASTIdx >= Args.size()) 6027 1.1 joerg continue; 6028 1.1 joerg ForbiddenNullArgs[ASTIdx] = 1; 6029 1.1 joerg } 6030 1.1 joerg } 6031 1.1 joerg } 6032 1.1.1.2 joerg for (unsigned I = 0; I < Args.size(); I++) { 6033 1.1.1.2 joerg unsigned Idx = RightToLeft ? Args.size() - I - 1 : I; 6034 1.1.1.2 joerg const ParmVarDecl *PVD = 6035 1.1.1.2 joerg Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr; 6036 1.1.1.2 joerg bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx]; 6037 1.1.1.2 joerg if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull)) { 6038 1.1 joerg // If we're checking for a potential constant expression, evaluate all 6039 1.1 joerg // initializers even if some of them fail. 6040 1.1 joerg if (!Info.noteFailure()) 6041 1.1 joerg return false; 6042 1.1 joerg Success = false; 6043 1.1 joerg } 6044 1.1 joerg } 6045 1.1 joerg return Success; 6046 1.1 joerg } 6047 1.1 joerg 6048 1.1.1.2 joerg /// Perform a trivial copy from Param, which is the parameter of a copy or move 6049 1.1.1.2 joerg /// constructor or assignment operator. 6050 1.1.1.2 joerg static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param, 6051 1.1.1.2 joerg const Expr *E, APValue &Result, 6052 1.1.1.2 joerg bool CopyObjectRepresentation) { 6053 1.1.1.2 joerg // Find the reference argument. 6054 1.1.1.2 joerg CallStackFrame *Frame = Info.CurrentCall; 6055 1.1.1.2 joerg APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param); 6056 1.1.1.2 joerg if (!RefValue) { 6057 1.1.1.2 joerg Info.FFDiag(E); 6058 1.1.1.2 joerg return false; 6059 1.1.1.2 joerg } 6060 1.1.1.2 joerg 6061 1.1.1.2 joerg // Copy out the contents of the RHS object. 6062 1.1.1.2 joerg LValue RefLValue; 6063 1.1.1.2 joerg RefLValue.setFrom(Info.Ctx, *RefValue); 6064 1.1.1.2 joerg return handleLValueToRValueConversion( 6065 1.1.1.2 joerg Info, E, Param->getType().getNonReferenceType(), RefLValue, Result, 6066 1.1.1.2 joerg CopyObjectRepresentation); 6067 1.1.1.2 joerg } 6068 1.1.1.2 joerg 6069 1.1 joerg /// Evaluate a function call. 6070 1.1 joerg static bool HandleFunctionCall(SourceLocation CallLoc, 6071 1.1 joerg const FunctionDecl *Callee, const LValue *This, 6072 1.1.1.2 joerg ArrayRef<const Expr *> Args, CallRef Call, 6073 1.1.1.2 joerg const Stmt *Body, EvalInfo &Info, 6074 1.1.1.2 joerg APValue &Result, const LValue *ResultSlot) { 6075 1.1 joerg if (!Info.CheckCallLimit(CallLoc)) 6076 1.1 joerg return false; 6077 1.1 joerg 6078 1.1.1.2 joerg CallStackFrame Frame(Info, CallLoc, Callee, This, Call); 6079 1.1 joerg 6080 1.1 joerg // For a trivial copy or move assignment, perform an APValue copy. This is 6081 1.1 joerg // essential for unions, where the operations performed by the assignment 6082 1.1 joerg // operator cannot be represented as statements. 6083 1.1 joerg // 6084 1.1 joerg // Skip this for non-union classes with no fields; in that case, the defaulted 6085 1.1 joerg // copy/move does not actually read the object. 6086 1.1 joerg const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee); 6087 1.1 joerg if (MD && MD->isDefaulted() && 6088 1.1 joerg (MD->getParent()->isUnion() || 6089 1.1.1.2 joerg (MD->isTrivial() && 6090 1.1.1.2 joerg isReadByLvalueToRvalueConversion(MD->getParent())))) { 6091 1.1 joerg assert(This && 6092 1.1 joerg (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())); 6093 1.1 joerg APValue RHSValue; 6094 1.1.1.2 joerg if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue, 6095 1.1.1.2 joerg MD->getParent()->isUnion())) 6096 1.1 joerg return false; 6097 1.1.1.2 joerg if (Info.getLangOpts().CPlusPlus20 && MD->isTrivial() && 6098 1.1 joerg !HandleUnionActiveMemberChange(Info, Args[0], *This)) 6099 1.1 joerg return false; 6100 1.1 joerg if (!handleAssignment(Info, Args[0], *This, MD->getThisType(), 6101 1.1 joerg RHSValue)) 6102 1.1 joerg return false; 6103 1.1 joerg This->moveInto(Result); 6104 1.1 joerg return true; 6105 1.1 joerg } else if (MD && isLambdaCallOperator(MD)) { 6106 1.1 joerg // We're in a lambda; determine the lambda capture field maps unless we're 6107 1.1 joerg // just constexpr checking a lambda's call operator. constexpr checking is 6108 1.1 joerg // done before the captures have been added to the closure object (unless 6109 1.1 joerg // we're inferring constexpr-ness), so we don't have access to them in this 6110 1.1 joerg // case. But since we don't need the captures to constexpr check, we can 6111 1.1 joerg // just ignore them. 6112 1.1 joerg if (!Info.checkingPotentialConstantExpression()) 6113 1.1 joerg MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields, 6114 1.1 joerg Frame.LambdaThisCaptureField); 6115 1.1 joerg } 6116 1.1 joerg 6117 1.1 joerg StmtResult Ret = {Result, ResultSlot}; 6118 1.1 joerg EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body); 6119 1.1 joerg if (ESR == ESR_Succeeded) { 6120 1.1 joerg if (Callee->getReturnType()->isVoidType()) 6121 1.1 joerg return true; 6122 1.1 joerg Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return); 6123 1.1 joerg } 6124 1.1 joerg return ESR == ESR_Returned; 6125 1.1 joerg } 6126 1.1 joerg 6127 1.1 joerg /// Evaluate a constructor call. 6128 1.1 joerg static bool HandleConstructorCall(const Expr *E, const LValue &This, 6129 1.1.1.2 joerg CallRef Call, 6130 1.1 joerg const CXXConstructorDecl *Definition, 6131 1.1 joerg EvalInfo &Info, APValue &Result) { 6132 1.1 joerg SourceLocation CallLoc = E->getExprLoc(); 6133 1.1 joerg if (!Info.CheckCallLimit(CallLoc)) 6134 1.1 joerg return false; 6135 1.1 joerg 6136 1.1 joerg const CXXRecordDecl *RD = Definition->getParent(); 6137 1.1 joerg if (RD->getNumVBases()) { 6138 1.1 joerg Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD; 6139 1.1 joerg return false; 6140 1.1 joerg } 6141 1.1 joerg 6142 1.1 joerg EvalInfo::EvaluatingConstructorRAII EvalObj( 6143 1.1 joerg Info, 6144 1.1 joerg ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}, 6145 1.1 joerg RD->getNumBases()); 6146 1.1.1.2 joerg CallStackFrame Frame(Info, CallLoc, Definition, &This, Call); 6147 1.1 joerg 6148 1.1 joerg // FIXME: Creating an APValue just to hold a nonexistent return value is 6149 1.1 joerg // wasteful. 6150 1.1 joerg APValue RetVal; 6151 1.1 joerg StmtResult Ret = {RetVal, nullptr}; 6152 1.1 joerg 6153 1.1 joerg // If it's a delegating constructor, delegate. 6154 1.1 joerg if (Definition->isDelegatingConstructor()) { 6155 1.1 joerg CXXConstructorDecl::init_const_iterator I = Definition->init_begin(); 6156 1.1.1.2 joerg if ((*I)->getInit()->isValueDependent()) { 6157 1.1.1.2 joerg if (!EvaluateDependentExpr((*I)->getInit(), Info)) 6158 1.1.1.2 joerg return false; 6159 1.1.1.2 joerg } else { 6160 1.1 joerg FullExpressionRAII InitScope(Info); 6161 1.1 joerg if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) || 6162 1.1 joerg !InitScope.destroy()) 6163 1.1 joerg return false; 6164 1.1 joerg } 6165 1.1 joerg return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed; 6166 1.1 joerg } 6167 1.1 joerg 6168 1.1 joerg // For a trivial copy or move constructor, perform an APValue copy. This is 6169 1.1 joerg // essential for unions (or classes with anonymous union members), where the 6170 1.1 joerg // operations performed by the constructor cannot be represented by 6171 1.1 joerg // ctor-initializers. 6172 1.1 joerg // 6173 1.1 joerg // Skip this for empty non-union classes; we should not perform an 6174 1.1 joerg // lvalue-to-rvalue conversion on them because their copy constructor does not 6175 1.1 joerg // actually read them. 6176 1.1 joerg if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() && 6177 1.1 joerg (Definition->getParent()->isUnion() || 6178 1.1.1.2 joerg (Definition->isTrivial() && 6179 1.1.1.2 joerg isReadByLvalueToRvalueConversion(Definition->getParent())))) { 6180 1.1.1.2 joerg return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result, 6181 1.1.1.2 joerg Definition->getParent()->isUnion()); 6182 1.1 joerg } 6183 1.1 joerg 6184 1.1 joerg // Reserve space for the struct members. 6185 1.1.1.2 joerg if (!Result.hasValue()) { 6186 1.1.1.2 joerg if (!RD->isUnion()) 6187 1.1.1.2 joerg Result = APValue(APValue::UninitStruct(), RD->getNumBases(), 6188 1.1.1.2 joerg std::distance(RD->field_begin(), RD->field_end())); 6189 1.1.1.2 joerg else 6190 1.1.1.2 joerg // A union starts with no active member. 6191 1.1.1.2 joerg Result = APValue((const FieldDecl*)nullptr); 6192 1.1.1.2 joerg } 6193 1.1 joerg 6194 1.1 joerg if (RD->isInvalidDecl()) return false; 6195 1.1 joerg const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6196 1.1 joerg 6197 1.1 joerg // A scope for temporaries lifetime-extended by reference members. 6198 1.1 joerg BlockScopeRAII LifetimeExtendedScope(Info); 6199 1.1 joerg 6200 1.1 joerg bool Success = true; 6201 1.1 joerg unsigned BasesSeen = 0; 6202 1.1 joerg #ifndef NDEBUG 6203 1.1 joerg CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin(); 6204 1.1 joerg #endif 6205 1.1 joerg CXXRecordDecl::field_iterator FieldIt = RD->field_begin(); 6206 1.1 joerg auto SkipToField = [&](FieldDecl *FD, bool Indirect) { 6207 1.1 joerg // We might be initializing the same field again if this is an indirect 6208 1.1 joerg // field initialization. 6209 1.1 joerg if (FieldIt == RD->field_end() || 6210 1.1 joerg FieldIt->getFieldIndex() > FD->getFieldIndex()) { 6211 1.1 joerg assert(Indirect && "fields out of order?"); 6212 1.1 joerg return; 6213 1.1 joerg } 6214 1.1 joerg 6215 1.1 joerg // Default-initialize any fields with no explicit initializer. 6216 1.1 joerg for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) { 6217 1.1 joerg assert(FieldIt != RD->field_end() && "missing field?"); 6218 1.1 joerg if (!FieldIt->isUnnamedBitfield()) 6219 1.1.1.2 joerg Success &= getDefaultInitValue( 6220 1.1.1.2 joerg FieldIt->getType(), 6221 1.1.1.2 joerg Result.getStructField(FieldIt->getFieldIndex())); 6222 1.1 joerg } 6223 1.1 joerg ++FieldIt; 6224 1.1 joerg }; 6225 1.1 joerg for (const auto *I : Definition->inits()) { 6226 1.1 joerg LValue Subobject = This; 6227 1.1 joerg LValue SubobjectParent = This; 6228 1.1 joerg APValue *Value = &Result; 6229 1.1 joerg 6230 1.1 joerg // Determine the subobject to initialize. 6231 1.1 joerg FieldDecl *FD = nullptr; 6232 1.1 joerg if (I->isBaseInitializer()) { 6233 1.1 joerg QualType BaseType(I->getBaseClass(), 0); 6234 1.1 joerg #ifndef NDEBUG 6235 1.1 joerg // Non-virtual base classes are initialized in the order in the class 6236 1.1 joerg // definition. We have already checked for virtual base classes. 6237 1.1 joerg assert(!BaseIt->isVirtual() && "virtual base for literal type"); 6238 1.1 joerg assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) && 6239 1.1 joerg "base class initializers not in expected order"); 6240 1.1 joerg ++BaseIt; 6241 1.1 joerg #endif 6242 1.1 joerg if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD, 6243 1.1 joerg BaseType->getAsCXXRecordDecl(), &Layout)) 6244 1.1 joerg return false; 6245 1.1 joerg Value = &Result.getStructBase(BasesSeen++); 6246 1.1 joerg } else if ((FD = I->getMember())) { 6247 1.1 joerg if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout)) 6248 1.1 joerg return false; 6249 1.1 joerg if (RD->isUnion()) { 6250 1.1 joerg Result = APValue(FD); 6251 1.1 joerg Value = &Result.getUnionValue(); 6252 1.1 joerg } else { 6253 1.1 joerg SkipToField(FD, false); 6254 1.1 joerg Value = &Result.getStructField(FD->getFieldIndex()); 6255 1.1 joerg } 6256 1.1 joerg } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) { 6257 1.1 joerg // Walk the indirect field decl's chain to find the object to initialize, 6258 1.1 joerg // and make sure we've initialized every step along it. 6259 1.1 joerg auto IndirectFieldChain = IFD->chain(); 6260 1.1 joerg for (auto *C : IndirectFieldChain) { 6261 1.1 joerg FD = cast<FieldDecl>(C); 6262 1.1 joerg CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent()); 6263 1.1 joerg // Switch the union field if it differs. This happens if we had 6264 1.1 joerg // preceding zero-initialization, and we're now initializing a union 6265 1.1 joerg // subobject other than the first. 6266 1.1 joerg // FIXME: In this case, the values of the other subobjects are 6267 1.1 joerg // specified, since zero-initialization sets all padding bits to zero. 6268 1.1 joerg if (!Value->hasValue() || 6269 1.1 joerg (Value->isUnion() && Value->getUnionField() != FD)) { 6270 1.1 joerg if (CD->isUnion()) 6271 1.1 joerg *Value = APValue(FD); 6272 1.1 joerg else 6273 1.1.1.2 joerg // FIXME: This immediately starts the lifetime of all members of 6274 1.1.1.2 joerg // an anonymous struct. It would be preferable to strictly start 6275 1.1.1.2 joerg // member lifetime in initialization order. 6276 1.1.1.2 joerg Success &= getDefaultInitValue(Info.Ctx.getRecordType(CD), *Value); 6277 1.1 joerg } 6278 1.1 joerg // Store Subobject as its parent before updating it for the last element 6279 1.1 joerg // in the chain. 6280 1.1 joerg if (C == IndirectFieldChain.back()) 6281 1.1 joerg SubobjectParent = Subobject; 6282 1.1 joerg if (!HandleLValueMember(Info, I->getInit(), Subobject, FD)) 6283 1.1 joerg return false; 6284 1.1 joerg if (CD->isUnion()) 6285 1.1 joerg Value = &Value->getUnionValue(); 6286 1.1 joerg else { 6287 1.1 joerg if (C == IndirectFieldChain.front() && !RD->isUnion()) 6288 1.1 joerg SkipToField(FD, true); 6289 1.1 joerg Value = &Value->getStructField(FD->getFieldIndex()); 6290 1.1 joerg } 6291 1.1 joerg } 6292 1.1 joerg } else { 6293 1.1 joerg llvm_unreachable("unknown base initializer kind"); 6294 1.1 joerg } 6295 1.1 joerg 6296 1.1 joerg // Need to override This for implicit field initializers as in this case 6297 1.1 joerg // This refers to innermost anonymous struct/union containing initializer, 6298 1.1 joerg // not to currently constructed class. 6299 1.1 joerg const Expr *Init = I->getInit(); 6300 1.1.1.2 joerg if (Init->isValueDependent()) { 6301 1.1.1.2 joerg if (!EvaluateDependentExpr(Init, Info)) 6302 1.1 joerg return false; 6303 1.1.1.2 joerg } else { 6304 1.1.1.2 joerg ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent, 6305 1.1.1.2 joerg isa<CXXDefaultInitExpr>(Init)); 6306 1.1.1.2 joerg FullExpressionRAII InitScope(Info); 6307 1.1.1.2 joerg if (!EvaluateInPlace(*Value, Info, Subobject, Init) || 6308 1.1.1.2 joerg (FD && FD->isBitField() && 6309 1.1.1.2 joerg !truncateBitfieldValue(Info, Init, *Value, FD))) { 6310 1.1.1.2 joerg // If we're checking for a potential constant expression, evaluate all 6311 1.1.1.2 joerg // initializers even if some of them fail. 6312 1.1.1.2 joerg if (!Info.noteFailure()) 6313 1.1.1.2 joerg return false; 6314 1.1.1.2 joerg Success = false; 6315 1.1.1.2 joerg } 6316 1.1 joerg } 6317 1.1 joerg 6318 1.1 joerg // This is the point at which the dynamic type of the object becomes this 6319 1.1 joerg // class type. 6320 1.1 joerg if (I->isBaseInitializer() && BasesSeen == RD->getNumBases()) 6321 1.1 joerg EvalObj.finishedConstructingBases(); 6322 1.1 joerg } 6323 1.1 joerg 6324 1.1 joerg // Default-initialize any remaining fields. 6325 1.1 joerg if (!RD->isUnion()) { 6326 1.1 joerg for (; FieldIt != RD->field_end(); ++FieldIt) { 6327 1.1 joerg if (!FieldIt->isUnnamedBitfield()) 6328 1.1.1.2 joerg Success &= getDefaultInitValue( 6329 1.1.1.2 joerg FieldIt->getType(), 6330 1.1.1.2 joerg Result.getStructField(FieldIt->getFieldIndex())); 6331 1.1 joerg } 6332 1.1 joerg } 6333 1.1 joerg 6334 1.1.1.2 joerg EvalObj.finishedConstructingFields(); 6335 1.1.1.2 joerg 6336 1.1 joerg return Success && 6337 1.1 joerg EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed && 6338 1.1 joerg LifetimeExtendedScope.destroy(); 6339 1.1 joerg } 6340 1.1 joerg 6341 1.1 joerg static bool HandleConstructorCall(const Expr *E, const LValue &This, 6342 1.1 joerg ArrayRef<const Expr*> Args, 6343 1.1 joerg const CXXConstructorDecl *Definition, 6344 1.1 joerg EvalInfo &Info, APValue &Result) { 6345 1.1.1.2 joerg CallScopeRAII CallScope(Info); 6346 1.1.1.2 joerg CallRef Call = Info.CurrentCall->createCall(Definition); 6347 1.1.1.2 joerg if (!EvaluateArgs(Args, Call, Info, Definition)) 6348 1.1 joerg return false; 6349 1.1 joerg 6350 1.1.1.2 joerg return HandleConstructorCall(E, This, Call, Definition, Info, Result) && 6351 1.1.1.2 joerg CallScope.destroy(); 6352 1.1 joerg } 6353 1.1 joerg 6354 1.1 joerg static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc, 6355 1.1 joerg const LValue &This, APValue &Value, 6356 1.1 joerg QualType T) { 6357 1.1 joerg // Objects can only be destroyed while they're within their lifetimes. 6358 1.1 joerg // FIXME: We have no representation for whether an object of type nullptr_t 6359 1.1 joerg // is in its lifetime; it usually doesn't matter. Perhaps we should model it 6360 1.1 joerg // as indeterminate instead? 6361 1.1 joerg if (Value.isAbsent() && !T->isNullPtrType()) { 6362 1.1 joerg APValue Printable; 6363 1.1 joerg This.moveInto(Printable); 6364 1.1 joerg Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime) 6365 1.1 joerg << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T)); 6366 1.1 joerg return false; 6367 1.1 joerg } 6368 1.1 joerg 6369 1.1 joerg // Invent an expression for location purposes. 6370 1.1 joerg // FIXME: We shouldn't need to do this. 6371 1.1 joerg OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_RValue); 6372 1.1 joerg 6373 1.1 joerg // For arrays, destroy elements right-to-left. 6374 1.1 joerg if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) { 6375 1.1 joerg uint64_t Size = CAT->getSize().getZExtValue(); 6376 1.1 joerg QualType ElemT = CAT->getElementType(); 6377 1.1 joerg 6378 1.1 joerg LValue ElemLV = This; 6379 1.1 joerg ElemLV.addArray(Info, &LocE, CAT); 6380 1.1 joerg if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size)) 6381 1.1 joerg return false; 6382 1.1 joerg 6383 1.1 joerg // Ensure that we have actual array elements available to destroy; the 6384 1.1 joerg // destructors might mutate the value, so we can't run them on the array 6385 1.1 joerg // filler. 6386 1.1 joerg if (Size && Size > Value.getArrayInitializedElts()) 6387 1.1 joerg expandArray(Value, Value.getArraySize() - 1); 6388 1.1 joerg 6389 1.1 joerg for (; Size != 0; --Size) { 6390 1.1 joerg APValue &Elem = Value.getArrayInitializedElt(Size - 1); 6391 1.1 joerg if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) || 6392 1.1 joerg !HandleDestructionImpl(Info, CallLoc, ElemLV, Elem, ElemT)) 6393 1.1 joerg return false; 6394 1.1 joerg } 6395 1.1 joerg 6396 1.1 joerg // End the lifetime of this array now. 6397 1.1 joerg Value = APValue(); 6398 1.1 joerg return true; 6399 1.1 joerg } 6400 1.1 joerg 6401 1.1 joerg const CXXRecordDecl *RD = T->getAsCXXRecordDecl(); 6402 1.1 joerg if (!RD) { 6403 1.1 joerg if (T.isDestructedType()) { 6404 1.1 joerg Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T; 6405 1.1 joerg return false; 6406 1.1 joerg } 6407 1.1 joerg 6408 1.1 joerg Value = APValue(); 6409 1.1 joerg return true; 6410 1.1 joerg } 6411 1.1 joerg 6412 1.1 joerg if (RD->getNumVBases()) { 6413 1.1 joerg Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD; 6414 1.1 joerg return false; 6415 1.1 joerg } 6416 1.1 joerg 6417 1.1 joerg const CXXDestructorDecl *DD = RD->getDestructor(); 6418 1.1 joerg if (!DD && !RD->hasTrivialDestructor()) { 6419 1.1 joerg Info.FFDiag(CallLoc); 6420 1.1 joerg return false; 6421 1.1 joerg } 6422 1.1 joerg 6423 1.1 joerg if (!DD || DD->isTrivial() || 6424 1.1 joerg (RD->isAnonymousStructOrUnion() && RD->isUnion())) { 6425 1.1 joerg // A trivial destructor just ends the lifetime of the object. Check for 6426 1.1 joerg // this case before checking for a body, because we might not bother 6427 1.1 joerg // building a body for a trivial destructor. Note that it doesn't matter 6428 1.1 joerg // whether the destructor is constexpr in this case; all trivial 6429 1.1 joerg // destructors are constexpr. 6430 1.1 joerg // 6431 1.1 joerg // If an anonymous union would be destroyed, some enclosing destructor must 6432 1.1 joerg // have been explicitly defined, and the anonymous union destruction should 6433 1.1 joerg // have no effect. 6434 1.1 joerg Value = APValue(); 6435 1.1 joerg return true; 6436 1.1 joerg } 6437 1.1 joerg 6438 1.1 joerg if (!Info.CheckCallLimit(CallLoc)) 6439 1.1 joerg return false; 6440 1.1 joerg 6441 1.1 joerg const FunctionDecl *Definition = nullptr; 6442 1.1 joerg const Stmt *Body = DD->getBody(Definition); 6443 1.1 joerg 6444 1.1 joerg if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body)) 6445 1.1 joerg return false; 6446 1.1 joerg 6447 1.1.1.2 joerg CallStackFrame Frame(Info, CallLoc, Definition, &This, CallRef()); 6448 1.1 joerg 6449 1.1 joerg // We're now in the period of destruction of this object. 6450 1.1 joerg unsigned BasesLeft = RD->getNumBases(); 6451 1.1 joerg EvalInfo::EvaluatingDestructorRAII EvalObj( 6452 1.1 joerg Info, 6453 1.1 joerg ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}); 6454 1.1 joerg if (!EvalObj.DidInsert) { 6455 1.1 joerg // C++2a [class.dtor]p19: 6456 1.1 joerg // the behavior is undefined if the destructor is invoked for an object 6457 1.1 joerg // whose lifetime has ended 6458 1.1 joerg // (Note that formally the lifetime ends when the period of destruction 6459 1.1 joerg // begins, even though certain uses of the object remain valid until the 6460 1.1 joerg // period of destruction ends.) 6461 1.1 joerg Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy); 6462 1.1 joerg return false; 6463 1.1 joerg } 6464 1.1 joerg 6465 1.1 joerg // FIXME: Creating an APValue just to hold a nonexistent return value is 6466 1.1 joerg // wasteful. 6467 1.1 joerg APValue RetVal; 6468 1.1 joerg StmtResult Ret = {RetVal, nullptr}; 6469 1.1 joerg if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed) 6470 1.1 joerg return false; 6471 1.1 joerg 6472 1.1 joerg // A union destructor does not implicitly destroy its members. 6473 1.1 joerg if (RD->isUnion()) 6474 1.1 joerg return true; 6475 1.1 joerg 6476 1.1 joerg const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6477 1.1 joerg 6478 1.1 joerg // We don't have a good way to iterate fields in reverse, so collect all the 6479 1.1 joerg // fields first and then walk them backwards. 6480 1.1 joerg SmallVector<FieldDecl*, 16> Fields(RD->field_begin(), RD->field_end()); 6481 1.1 joerg for (const FieldDecl *FD : llvm::reverse(Fields)) { 6482 1.1 joerg if (FD->isUnnamedBitfield()) 6483 1.1 joerg continue; 6484 1.1 joerg 6485 1.1 joerg LValue Subobject = This; 6486 1.1 joerg if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout)) 6487 1.1 joerg return false; 6488 1.1 joerg 6489 1.1 joerg APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex()); 6490 1.1 joerg if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue, 6491 1.1 joerg FD->getType())) 6492 1.1 joerg return false; 6493 1.1 joerg } 6494 1.1 joerg 6495 1.1 joerg if (BasesLeft != 0) 6496 1.1 joerg EvalObj.startedDestroyingBases(); 6497 1.1 joerg 6498 1.1 joerg // Destroy base classes in reverse order. 6499 1.1 joerg for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) { 6500 1.1 joerg --BasesLeft; 6501 1.1 joerg 6502 1.1 joerg QualType BaseType = Base.getType(); 6503 1.1 joerg LValue Subobject = This; 6504 1.1 joerg if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD, 6505 1.1 joerg BaseType->getAsCXXRecordDecl(), &Layout)) 6506 1.1 joerg return false; 6507 1.1 joerg 6508 1.1 joerg APValue *SubobjectValue = &Value.getStructBase(BasesLeft); 6509 1.1 joerg if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue, 6510 1.1 joerg BaseType)) 6511 1.1 joerg return false; 6512 1.1 joerg } 6513 1.1 joerg assert(BasesLeft == 0 && "NumBases was wrong?"); 6514 1.1 joerg 6515 1.1 joerg // The period of destruction ends now. The object is gone. 6516 1.1 joerg Value = APValue(); 6517 1.1 joerg return true; 6518 1.1 joerg } 6519 1.1 joerg 6520 1.1 joerg namespace { 6521 1.1 joerg struct DestroyObjectHandler { 6522 1.1 joerg EvalInfo &Info; 6523 1.1 joerg const Expr *E; 6524 1.1 joerg const LValue &This; 6525 1.1 joerg const AccessKinds AccessKind; 6526 1.1 joerg 6527 1.1 joerg typedef bool result_type; 6528 1.1 joerg bool failed() { return false; } 6529 1.1 joerg bool found(APValue &Subobj, QualType SubobjType) { 6530 1.1 joerg return HandleDestructionImpl(Info, E->getExprLoc(), This, Subobj, 6531 1.1 joerg SubobjType); 6532 1.1 joerg } 6533 1.1 joerg bool found(APSInt &Value, QualType SubobjType) { 6534 1.1 joerg Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem); 6535 1.1 joerg return false; 6536 1.1 joerg } 6537 1.1 joerg bool found(APFloat &Value, QualType SubobjType) { 6538 1.1 joerg Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem); 6539 1.1 joerg return false; 6540 1.1 joerg } 6541 1.1 joerg }; 6542 1.1 joerg } 6543 1.1 joerg 6544 1.1 joerg /// Perform a destructor or pseudo-destructor call on the given object, which 6545 1.1 joerg /// might in general not be a complete object. 6546 1.1 joerg static bool HandleDestruction(EvalInfo &Info, const Expr *E, 6547 1.1 joerg const LValue &This, QualType ThisType) { 6548 1.1 joerg CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType); 6549 1.1 joerg DestroyObjectHandler Handler = {Info, E, This, AK_Destroy}; 6550 1.1 joerg return Obj && findSubobject(Info, E, Obj, This.Designator, Handler); 6551 1.1 joerg } 6552 1.1 joerg 6553 1.1 joerg /// Destroy and end the lifetime of the given complete object. 6554 1.1 joerg static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc, 6555 1.1 joerg APValue::LValueBase LVBase, APValue &Value, 6556 1.1 joerg QualType T) { 6557 1.1 joerg // If we've had an unmodeled side-effect, we can't rely on mutable state 6558 1.1 joerg // (such as the object we're about to destroy) being correct. 6559 1.1 joerg if (Info.EvalStatus.HasSideEffects) 6560 1.1 joerg return false; 6561 1.1 joerg 6562 1.1 joerg LValue LV; 6563 1.1 joerg LV.set({LVBase}); 6564 1.1 joerg return HandleDestructionImpl(Info, Loc, LV, Value, T); 6565 1.1 joerg } 6566 1.1 joerg 6567 1.1 joerg /// Perform a call to 'perator new' or to `__builtin_operator_new'. 6568 1.1 joerg static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E, 6569 1.1 joerg LValue &Result) { 6570 1.1 joerg if (Info.checkingPotentialConstantExpression() || 6571 1.1 joerg Info.SpeculativeEvaluationDepth) 6572 1.1 joerg return false; 6573 1.1 joerg 6574 1.1 joerg // This is permitted only within a call to std::allocator<T>::allocate. 6575 1.1 joerg auto Caller = Info.getStdAllocatorCaller("allocate"); 6576 1.1 joerg if (!Caller) { 6577 1.1.1.2 joerg Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20 6578 1.1 joerg ? diag::note_constexpr_new_untyped 6579 1.1 joerg : diag::note_constexpr_new); 6580 1.1 joerg return false; 6581 1.1 joerg } 6582 1.1 joerg 6583 1.1 joerg QualType ElemType = Caller.ElemType; 6584 1.1 joerg if (ElemType->isIncompleteType() || ElemType->isFunctionType()) { 6585 1.1 joerg Info.FFDiag(E->getExprLoc(), 6586 1.1 joerg diag::note_constexpr_new_not_complete_object_type) 6587 1.1 joerg << (ElemType->isIncompleteType() ? 0 : 1) << ElemType; 6588 1.1 joerg return false; 6589 1.1 joerg } 6590 1.1 joerg 6591 1.1 joerg APSInt ByteSize; 6592 1.1 joerg if (!EvaluateInteger(E->getArg(0), ByteSize, Info)) 6593 1.1 joerg return false; 6594 1.1 joerg bool IsNothrow = false; 6595 1.1 joerg for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) { 6596 1.1 joerg EvaluateIgnoredValue(Info, E->getArg(I)); 6597 1.1 joerg IsNothrow |= E->getType()->isNothrowT(); 6598 1.1 joerg } 6599 1.1 joerg 6600 1.1 joerg CharUnits ElemSize; 6601 1.1 joerg if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize)) 6602 1.1 joerg return false; 6603 1.1 joerg APInt Size, Remainder; 6604 1.1 joerg APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity()); 6605 1.1 joerg APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder); 6606 1.1 joerg if (Remainder != 0) { 6607 1.1 joerg // This likely indicates a bug in the implementation of 'std::allocator'. 6608 1.1 joerg Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size) 6609 1.1 joerg << ByteSize << APSInt(ElemSizeAP, true) << ElemType; 6610 1.1 joerg return false; 6611 1.1 joerg } 6612 1.1 joerg 6613 1.1 joerg if (ByteSize.getActiveBits() > ConstantArrayType::getMaxSizeBits(Info.Ctx)) { 6614 1.1 joerg if (IsNothrow) { 6615 1.1 joerg Result.setNull(Info.Ctx, E->getType()); 6616 1.1 joerg return true; 6617 1.1 joerg } 6618 1.1 joerg 6619 1.1 joerg Info.FFDiag(E, diag::note_constexpr_new_too_large) << APSInt(Size, true); 6620 1.1 joerg return false; 6621 1.1 joerg } 6622 1.1 joerg 6623 1.1 joerg QualType AllocType = Info.Ctx.getConstantArrayType(ElemType, Size, nullptr, 6624 1.1 joerg ArrayType::Normal, 0); 6625 1.1 joerg APValue *Val = Info.createHeapAlloc(E, AllocType, Result); 6626 1.1 joerg *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue()); 6627 1.1 joerg Result.addArray(Info, E, cast<ConstantArrayType>(AllocType)); 6628 1.1 joerg return true; 6629 1.1 joerg } 6630 1.1 joerg 6631 1.1 joerg static bool hasVirtualDestructor(QualType T) { 6632 1.1 joerg if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 6633 1.1 joerg if (CXXDestructorDecl *DD = RD->getDestructor()) 6634 1.1 joerg return DD->isVirtual(); 6635 1.1 joerg return false; 6636 1.1 joerg } 6637 1.1 joerg 6638 1.1 joerg static const FunctionDecl *getVirtualOperatorDelete(QualType T) { 6639 1.1 joerg if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 6640 1.1 joerg if (CXXDestructorDecl *DD = RD->getDestructor()) 6641 1.1 joerg return DD->isVirtual() ? DD->getOperatorDelete() : nullptr; 6642 1.1 joerg return nullptr; 6643 1.1 joerg } 6644 1.1 joerg 6645 1.1 joerg /// Check that the given object is a suitable pointer to a heap allocation that 6646 1.1 joerg /// still exists and is of the right kind for the purpose of a deletion. 6647 1.1 joerg /// 6648 1.1 joerg /// On success, returns the heap allocation to deallocate. On failure, produces 6649 1.1 joerg /// a diagnostic and returns None. 6650 1.1 joerg static Optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E, 6651 1.1 joerg const LValue &Pointer, 6652 1.1 joerg DynAlloc::Kind DeallocKind) { 6653 1.1 joerg auto PointerAsString = [&] { 6654 1.1 joerg return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy); 6655 1.1 joerg }; 6656 1.1 joerg 6657 1.1 joerg DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>(); 6658 1.1 joerg if (!DA) { 6659 1.1 joerg Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc) 6660 1.1 joerg << PointerAsString(); 6661 1.1 joerg if (Pointer.Base) 6662 1.1 joerg NoteLValueLocation(Info, Pointer.Base); 6663 1.1 joerg return None; 6664 1.1 joerg } 6665 1.1 joerg 6666 1.1 joerg Optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA); 6667 1.1 joerg if (!Alloc) { 6668 1.1 joerg Info.FFDiag(E, diag::note_constexpr_double_delete); 6669 1.1 joerg return None; 6670 1.1 joerg } 6671 1.1 joerg 6672 1.1 joerg QualType AllocType = Pointer.Base.getDynamicAllocType(); 6673 1.1 joerg if (DeallocKind != (*Alloc)->getKind()) { 6674 1.1 joerg Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch) 6675 1.1 joerg << DeallocKind << (*Alloc)->getKind() << AllocType; 6676 1.1 joerg NoteLValueLocation(Info, Pointer.Base); 6677 1.1 joerg return None; 6678 1.1 joerg } 6679 1.1 joerg 6680 1.1 joerg bool Subobject = false; 6681 1.1 joerg if (DeallocKind == DynAlloc::New) { 6682 1.1 joerg Subobject = Pointer.Designator.MostDerivedPathLength != 0 || 6683 1.1 joerg Pointer.Designator.isOnePastTheEnd(); 6684 1.1 joerg } else { 6685 1.1 joerg Subobject = Pointer.Designator.Entries.size() != 1 || 6686 1.1 joerg Pointer.Designator.Entries[0].getAsArrayIndex() != 0; 6687 1.1 joerg } 6688 1.1 joerg if (Subobject) { 6689 1.1 joerg Info.FFDiag(E, diag::note_constexpr_delete_subobject) 6690 1.1 joerg << PointerAsString() << Pointer.Designator.isOnePastTheEnd(); 6691 1.1 joerg return None; 6692 1.1 joerg } 6693 1.1 joerg 6694 1.1 joerg return Alloc; 6695 1.1 joerg } 6696 1.1 joerg 6697 1.1 joerg // Perform a call to 'operator delete' or '__builtin_operator_delete'. 6698 1.1 joerg bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) { 6699 1.1 joerg if (Info.checkingPotentialConstantExpression() || 6700 1.1 joerg Info.SpeculativeEvaluationDepth) 6701 1.1 joerg return false; 6702 1.1 joerg 6703 1.1 joerg // This is permitted only within a call to std::allocator<T>::deallocate. 6704 1.1 joerg if (!Info.getStdAllocatorCaller("deallocate")) { 6705 1.1 joerg Info.FFDiag(E->getExprLoc()); 6706 1.1 joerg return true; 6707 1.1 joerg } 6708 1.1 joerg 6709 1.1 joerg LValue Pointer; 6710 1.1 joerg if (!EvaluatePointer(E->getArg(0), Pointer, Info)) 6711 1.1 joerg return false; 6712 1.1 joerg for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) 6713 1.1 joerg EvaluateIgnoredValue(Info, E->getArg(I)); 6714 1.1 joerg 6715 1.1 joerg if (Pointer.Designator.Invalid) 6716 1.1 joerg return false; 6717 1.1 joerg 6718 1.1.1.2 joerg // Deleting a null pointer would have no effect, but it's not permitted by 6719 1.1.1.2 joerg // std::allocator<T>::deallocate's contract. 6720 1.1.1.2 joerg if (Pointer.isNullPointer()) { 6721 1.1.1.2 joerg Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_deallocate_null); 6722 1.1 joerg return true; 6723 1.1.1.2 joerg } 6724 1.1 joerg 6725 1.1 joerg if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator)) 6726 1.1 joerg return false; 6727 1.1 joerg 6728 1.1 joerg Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>()); 6729 1.1 joerg return true; 6730 1.1 joerg } 6731 1.1 joerg 6732 1.1 joerg //===----------------------------------------------------------------------===// 6733 1.1 joerg // Generic Evaluation 6734 1.1 joerg //===----------------------------------------------------------------------===// 6735 1.1 joerg namespace { 6736 1.1 joerg 6737 1.1 joerg class BitCastBuffer { 6738 1.1 joerg // FIXME: We're going to need bit-level granularity when we support 6739 1.1 joerg // bit-fields. 6740 1.1 joerg // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but 6741 1.1 joerg // we don't support a host or target where that is the case. Still, we should 6742 1.1 joerg // use a more generic type in case we ever do. 6743 1.1 joerg SmallVector<Optional<unsigned char>, 32> Bytes; 6744 1.1 joerg 6745 1.1 joerg static_assert(std::numeric_limits<unsigned char>::digits >= 8, 6746 1.1 joerg "Need at least 8 bit unsigned char"); 6747 1.1 joerg 6748 1.1 joerg bool TargetIsLittleEndian; 6749 1.1 joerg 6750 1.1 joerg public: 6751 1.1 joerg BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian) 6752 1.1 joerg : Bytes(Width.getQuantity()), 6753 1.1 joerg TargetIsLittleEndian(TargetIsLittleEndian) {} 6754 1.1 joerg 6755 1.1 joerg LLVM_NODISCARD 6756 1.1 joerg bool readObject(CharUnits Offset, CharUnits Width, 6757 1.1 joerg SmallVectorImpl<unsigned char> &Output) const { 6758 1.1 joerg for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) { 6759 1.1 joerg // If a byte of an integer is uninitialized, then the whole integer is 6760 1.1 joerg // uninitalized. 6761 1.1 joerg if (!Bytes[I.getQuantity()]) 6762 1.1 joerg return false; 6763 1.1 joerg Output.push_back(*Bytes[I.getQuantity()]); 6764 1.1 joerg } 6765 1.1 joerg if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian) 6766 1.1 joerg std::reverse(Output.begin(), Output.end()); 6767 1.1 joerg return true; 6768 1.1 joerg } 6769 1.1 joerg 6770 1.1 joerg void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) { 6771 1.1 joerg if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian) 6772 1.1 joerg std::reverse(Input.begin(), Input.end()); 6773 1.1 joerg 6774 1.1 joerg size_t Index = 0; 6775 1.1 joerg for (unsigned char Byte : Input) { 6776 1.1 joerg assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?"); 6777 1.1 joerg Bytes[Offset.getQuantity() + Index] = Byte; 6778 1.1 joerg ++Index; 6779 1.1 joerg } 6780 1.1 joerg } 6781 1.1 joerg 6782 1.1 joerg size_t size() { return Bytes.size(); } 6783 1.1 joerg }; 6784 1.1 joerg 6785 1.1 joerg /// Traverse an APValue to produce an BitCastBuffer, emulating how the current 6786 1.1 joerg /// target would represent the value at runtime. 6787 1.1 joerg class APValueToBufferConverter { 6788 1.1 joerg EvalInfo &Info; 6789 1.1 joerg BitCastBuffer Buffer; 6790 1.1 joerg const CastExpr *BCE; 6791 1.1 joerg 6792 1.1 joerg APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth, 6793 1.1 joerg const CastExpr *BCE) 6794 1.1 joerg : Info(Info), 6795 1.1 joerg Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()), 6796 1.1 joerg BCE(BCE) {} 6797 1.1 joerg 6798 1.1 joerg bool visit(const APValue &Val, QualType Ty) { 6799 1.1 joerg return visit(Val, Ty, CharUnits::fromQuantity(0)); 6800 1.1 joerg } 6801 1.1 joerg 6802 1.1 joerg // Write out Val with type Ty into Buffer starting at Offset. 6803 1.1 joerg bool visit(const APValue &Val, QualType Ty, CharUnits Offset) { 6804 1.1 joerg assert((size_t)Offset.getQuantity() <= Buffer.size()); 6805 1.1 joerg 6806 1.1 joerg // As a special case, nullptr_t has an indeterminate value. 6807 1.1 joerg if (Ty->isNullPtrType()) 6808 1.1 joerg return true; 6809 1.1 joerg 6810 1.1 joerg // Dig through Src to find the byte at SrcOffset. 6811 1.1 joerg switch (Val.getKind()) { 6812 1.1 joerg case APValue::Indeterminate: 6813 1.1 joerg case APValue::None: 6814 1.1 joerg return true; 6815 1.1 joerg 6816 1.1 joerg case APValue::Int: 6817 1.1 joerg return visitInt(Val.getInt(), Ty, Offset); 6818 1.1 joerg case APValue::Float: 6819 1.1 joerg return visitFloat(Val.getFloat(), Ty, Offset); 6820 1.1 joerg case APValue::Array: 6821 1.1 joerg return visitArray(Val, Ty, Offset); 6822 1.1 joerg case APValue::Struct: 6823 1.1 joerg return visitRecord(Val, Ty, Offset); 6824 1.1 joerg 6825 1.1 joerg case APValue::ComplexInt: 6826 1.1 joerg case APValue::ComplexFloat: 6827 1.1 joerg case APValue::Vector: 6828 1.1 joerg case APValue::FixedPoint: 6829 1.1 joerg // FIXME: We should support these. 6830 1.1 joerg 6831 1.1 joerg case APValue::Union: 6832 1.1 joerg case APValue::MemberPointer: 6833 1.1 joerg case APValue::AddrLabelDiff: { 6834 1.1 joerg Info.FFDiag(BCE->getBeginLoc(), 6835 1.1 joerg diag::note_constexpr_bit_cast_unsupported_type) 6836 1.1 joerg << Ty; 6837 1.1 joerg return false; 6838 1.1 joerg } 6839 1.1 joerg 6840 1.1 joerg case APValue::LValue: 6841 1.1 joerg llvm_unreachable("LValue subobject in bit_cast?"); 6842 1.1 joerg } 6843 1.1 joerg llvm_unreachable("Unhandled APValue::ValueKind"); 6844 1.1 joerg } 6845 1.1 joerg 6846 1.1 joerg bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) { 6847 1.1 joerg const RecordDecl *RD = Ty->getAsRecordDecl(); 6848 1.1 joerg const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6849 1.1 joerg 6850 1.1 joerg // Visit the base classes. 6851 1.1 joerg if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 6852 1.1 joerg for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) { 6853 1.1 joerg const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I]; 6854 1.1 joerg CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); 6855 1.1 joerg 6856 1.1 joerg if (!visitRecord(Val.getStructBase(I), BS.getType(), 6857 1.1 joerg Layout.getBaseClassOffset(BaseDecl) + Offset)) 6858 1.1 joerg return false; 6859 1.1 joerg } 6860 1.1 joerg } 6861 1.1 joerg 6862 1.1 joerg // Visit the fields. 6863 1.1 joerg unsigned FieldIdx = 0; 6864 1.1 joerg for (FieldDecl *FD : RD->fields()) { 6865 1.1 joerg if (FD->isBitField()) { 6866 1.1 joerg Info.FFDiag(BCE->getBeginLoc(), 6867 1.1 joerg diag::note_constexpr_bit_cast_unsupported_bitfield); 6868 1.1 joerg return false; 6869 1.1 joerg } 6870 1.1 joerg 6871 1.1 joerg uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx); 6872 1.1 joerg 6873 1.1 joerg assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 && 6874 1.1 joerg "only bit-fields can have sub-char alignment"); 6875 1.1 joerg CharUnits FieldOffset = 6876 1.1 joerg Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset; 6877 1.1 joerg QualType FieldTy = FD->getType(); 6878 1.1 joerg if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset)) 6879 1.1 joerg return false; 6880 1.1 joerg ++FieldIdx; 6881 1.1 joerg } 6882 1.1 joerg 6883 1.1 joerg return true; 6884 1.1 joerg } 6885 1.1 joerg 6886 1.1 joerg bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) { 6887 1.1 joerg const auto *CAT = 6888 1.1 joerg dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe()); 6889 1.1 joerg if (!CAT) 6890 1.1 joerg return false; 6891 1.1 joerg 6892 1.1 joerg CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType()); 6893 1.1 joerg unsigned NumInitializedElts = Val.getArrayInitializedElts(); 6894 1.1 joerg unsigned ArraySize = Val.getArraySize(); 6895 1.1 joerg // First, initialize the initialized elements. 6896 1.1 joerg for (unsigned I = 0; I != NumInitializedElts; ++I) { 6897 1.1 joerg const APValue &SubObj = Val.getArrayInitializedElt(I); 6898 1.1 joerg if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth)) 6899 1.1 joerg return false; 6900 1.1 joerg } 6901 1.1 joerg 6902 1.1 joerg // Next, initialize the rest of the array using the filler. 6903 1.1 joerg if (Val.hasArrayFiller()) { 6904 1.1 joerg const APValue &Filler = Val.getArrayFiller(); 6905 1.1 joerg for (unsigned I = NumInitializedElts; I != ArraySize; ++I) { 6906 1.1 joerg if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth)) 6907 1.1 joerg return false; 6908 1.1 joerg } 6909 1.1 joerg } 6910 1.1 joerg 6911 1.1 joerg return true; 6912 1.1 joerg } 6913 1.1 joerg 6914 1.1 joerg bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) { 6915 1.1.1.2 joerg APSInt AdjustedVal = Val; 6916 1.1.1.2 joerg unsigned Width = AdjustedVal.getBitWidth(); 6917 1.1.1.2 joerg if (Ty->isBooleanType()) { 6918 1.1.1.2 joerg Width = Info.Ctx.getTypeSize(Ty); 6919 1.1.1.2 joerg AdjustedVal = AdjustedVal.extend(Width); 6920 1.1.1.2 joerg } 6921 1.1.1.2 joerg 6922 1.1.1.2 joerg SmallVector<unsigned char, 8> Bytes(Width / 8); 6923 1.1.1.2 joerg llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8); 6924 1.1 joerg Buffer.writeObject(Offset, Bytes); 6925 1.1 joerg return true; 6926 1.1 joerg } 6927 1.1 joerg 6928 1.1 joerg bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) { 6929 1.1 joerg APSInt AsInt(Val.bitcastToAPInt()); 6930 1.1 joerg return visitInt(AsInt, Ty, Offset); 6931 1.1 joerg } 6932 1.1 joerg 6933 1.1 joerg public: 6934 1.1 joerg static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src, 6935 1.1 joerg const CastExpr *BCE) { 6936 1.1 joerg CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType()); 6937 1.1 joerg APValueToBufferConverter Converter(Info, DstSize, BCE); 6938 1.1 joerg if (!Converter.visit(Src, BCE->getSubExpr()->getType())) 6939 1.1 joerg return None; 6940 1.1 joerg return Converter.Buffer; 6941 1.1 joerg } 6942 1.1 joerg }; 6943 1.1 joerg 6944 1.1 joerg /// Write an BitCastBuffer into an APValue. 6945 1.1 joerg class BufferToAPValueConverter { 6946 1.1 joerg EvalInfo &Info; 6947 1.1 joerg const BitCastBuffer &Buffer; 6948 1.1 joerg const CastExpr *BCE; 6949 1.1 joerg 6950 1.1 joerg BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer, 6951 1.1 joerg const CastExpr *BCE) 6952 1.1 joerg : Info(Info), Buffer(Buffer), BCE(BCE) {} 6953 1.1 joerg 6954 1.1 joerg // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast 6955 1.1 joerg // with an invalid type, so anything left is a deficiency on our part (FIXME). 6956 1.1 joerg // Ideally this will be unreachable. 6957 1.1 joerg llvm::NoneType unsupportedType(QualType Ty) { 6958 1.1 joerg Info.FFDiag(BCE->getBeginLoc(), 6959 1.1 joerg diag::note_constexpr_bit_cast_unsupported_type) 6960 1.1 joerg << Ty; 6961 1.1 joerg return None; 6962 1.1 joerg } 6963 1.1 joerg 6964 1.1.1.2 joerg llvm::NoneType unrepresentableValue(QualType Ty, const APSInt &Val) { 6965 1.1.1.2 joerg Info.FFDiag(BCE->getBeginLoc(), 6966 1.1.1.2 joerg diag::note_constexpr_bit_cast_unrepresentable_value) 6967 1.1.1.2 joerg << Ty << Val.toString(/*Radix=*/10); 6968 1.1.1.2 joerg return None; 6969 1.1.1.2 joerg } 6970 1.1.1.2 joerg 6971 1.1 joerg Optional<APValue> visit(const BuiltinType *T, CharUnits Offset, 6972 1.1 joerg const EnumType *EnumSugar = nullptr) { 6973 1.1 joerg if (T->isNullPtrType()) { 6974 1.1 joerg uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0)); 6975 1.1 joerg return APValue((Expr *)nullptr, 6976 1.1 joerg /*Offset=*/CharUnits::fromQuantity(NullValue), 6977 1.1 joerg APValue::NoLValuePath{}, /*IsNullPtr=*/true); 6978 1.1 joerg } 6979 1.1 joerg 6980 1.1 joerg CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T); 6981 1.1.1.2 joerg 6982 1.1.1.2 joerg // Work around floating point types that contain unused padding bytes. This 6983 1.1.1.2 joerg // is really just `long double` on x86, which is the only fundamental type 6984 1.1.1.2 joerg // with padding bytes. 6985 1.1.1.2 joerg if (T->isRealFloatingType()) { 6986 1.1.1.2 joerg const llvm::fltSemantics &Semantics = 6987 1.1.1.2 joerg Info.Ctx.getFloatTypeSemantics(QualType(T, 0)); 6988 1.1.1.2 joerg unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics); 6989 1.1.1.2 joerg assert(NumBits % 8 == 0); 6990 1.1.1.2 joerg CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8); 6991 1.1.1.2 joerg if (NumBytes != SizeOf) 6992 1.1.1.2 joerg SizeOf = NumBytes; 6993 1.1.1.2 joerg } 6994 1.1.1.2 joerg 6995 1.1 joerg SmallVector<uint8_t, 8> Bytes; 6996 1.1 joerg if (!Buffer.readObject(Offset, SizeOf, Bytes)) { 6997 1.1 joerg // If this is std::byte or unsigned char, then its okay to store an 6998 1.1 joerg // indeterminate value. 6999 1.1 joerg bool IsStdByte = EnumSugar && EnumSugar->isStdByteType(); 7000 1.1 joerg bool IsUChar = 7001 1.1 joerg !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) || 7002 1.1 joerg T->isSpecificBuiltinType(BuiltinType::Char_U)); 7003 1.1 joerg if (!IsStdByte && !IsUChar) { 7004 1.1 joerg QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0); 7005 1.1 joerg Info.FFDiag(BCE->getExprLoc(), 7006 1.1 joerg diag::note_constexpr_bit_cast_indet_dest) 7007 1.1 joerg << DisplayType << Info.Ctx.getLangOpts().CharIsSigned; 7008 1.1 joerg return None; 7009 1.1 joerg } 7010 1.1 joerg 7011 1.1 joerg return APValue::IndeterminateValue(); 7012 1.1 joerg } 7013 1.1 joerg 7014 1.1 joerg APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true); 7015 1.1 joerg llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size()); 7016 1.1 joerg 7017 1.1 joerg if (T->isIntegralOrEnumerationType()) { 7018 1.1 joerg Val.setIsSigned(T->isSignedIntegerOrEnumerationType()); 7019 1.1.1.2 joerg 7020 1.1.1.2 joerg unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0)); 7021 1.1.1.2 joerg if (IntWidth != Val.getBitWidth()) { 7022 1.1.1.2 joerg APSInt Truncated = Val.trunc(IntWidth); 7023 1.1.1.2 joerg if (Truncated.extend(Val.getBitWidth()) != Val) 7024 1.1.1.2 joerg return unrepresentableValue(QualType(T, 0), Val); 7025 1.1.1.2 joerg Val = Truncated; 7026 1.1.1.2 joerg } 7027 1.1.1.2 joerg 7028 1.1 joerg return APValue(Val); 7029 1.1 joerg } 7030 1.1 joerg 7031 1.1 joerg if (T->isRealFloatingType()) { 7032 1.1 joerg const llvm::fltSemantics &Semantics = 7033 1.1 joerg Info.Ctx.getFloatTypeSemantics(QualType(T, 0)); 7034 1.1 joerg return APValue(APFloat(Semantics, Val)); 7035 1.1 joerg } 7036 1.1 joerg 7037 1.1 joerg return unsupportedType(QualType(T, 0)); 7038 1.1 joerg } 7039 1.1 joerg 7040 1.1 joerg Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) { 7041 1.1 joerg const RecordDecl *RD = RTy->getAsRecordDecl(); 7042 1.1 joerg const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 7043 1.1 joerg 7044 1.1 joerg unsigned NumBases = 0; 7045 1.1 joerg if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 7046 1.1 joerg NumBases = CXXRD->getNumBases(); 7047 1.1 joerg 7048 1.1 joerg APValue ResultVal(APValue::UninitStruct(), NumBases, 7049 1.1 joerg std::distance(RD->field_begin(), RD->field_end())); 7050 1.1 joerg 7051 1.1 joerg // Visit the base classes. 7052 1.1 joerg if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 7053 1.1 joerg for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) { 7054 1.1 joerg const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I]; 7055 1.1 joerg CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); 7056 1.1 joerg if (BaseDecl->isEmpty() || 7057 1.1 joerg Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero()) 7058 1.1 joerg continue; 7059 1.1 joerg 7060 1.1 joerg Optional<APValue> SubObj = visitType( 7061 1.1 joerg BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset); 7062 1.1 joerg if (!SubObj) 7063 1.1 joerg return None; 7064 1.1 joerg ResultVal.getStructBase(I) = *SubObj; 7065 1.1 joerg } 7066 1.1 joerg } 7067 1.1 joerg 7068 1.1 joerg // Visit the fields. 7069 1.1 joerg unsigned FieldIdx = 0; 7070 1.1 joerg for (FieldDecl *FD : RD->fields()) { 7071 1.1 joerg // FIXME: We don't currently support bit-fields. A lot of the logic for 7072 1.1 joerg // this is in CodeGen, so we need to factor it around. 7073 1.1 joerg if (FD->isBitField()) { 7074 1.1 joerg Info.FFDiag(BCE->getBeginLoc(), 7075 1.1 joerg diag::note_constexpr_bit_cast_unsupported_bitfield); 7076 1.1 joerg return None; 7077 1.1 joerg } 7078 1.1 joerg 7079 1.1 joerg uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx); 7080 1.1 joerg assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0); 7081 1.1 joerg 7082 1.1 joerg CharUnits FieldOffset = 7083 1.1 joerg CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) + 7084 1.1 joerg Offset; 7085 1.1 joerg QualType FieldTy = FD->getType(); 7086 1.1 joerg Optional<APValue> SubObj = visitType(FieldTy, FieldOffset); 7087 1.1 joerg if (!SubObj) 7088 1.1 joerg return None; 7089 1.1 joerg ResultVal.getStructField(FieldIdx) = *SubObj; 7090 1.1 joerg ++FieldIdx; 7091 1.1 joerg } 7092 1.1 joerg 7093 1.1 joerg return ResultVal; 7094 1.1 joerg } 7095 1.1 joerg 7096 1.1 joerg Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) { 7097 1.1 joerg QualType RepresentationType = Ty->getDecl()->getIntegerType(); 7098 1.1 joerg assert(!RepresentationType.isNull() && 7099 1.1 joerg "enum forward decl should be caught by Sema"); 7100 1.1 joerg const auto *AsBuiltin = 7101 1.1 joerg RepresentationType.getCanonicalType()->castAs<BuiltinType>(); 7102 1.1 joerg // Recurse into the underlying type. Treat std::byte transparently as 7103 1.1 joerg // unsigned char. 7104 1.1 joerg return visit(AsBuiltin, Offset, /*EnumTy=*/Ty); 7105 1.1 joerg } 7106 1.1 joerg 7107 1.1 joerg Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) { 7108 1.1 joerg size_t Size = Ty->getSize().getLimitedValue(); 7109 1.1 joerg CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType()); 7110 1.1 joerg 7111 1.1 joerg APValue ArrayValue(APValue::UninitArray(), Size, Size); 7112 1.1 joerg for (size_t I = 0; I != Size; ++I) { 7113 1.1 joerg Optional<APValue> ElementValue = 7114 1.1 joerg visitType(Ty->getElementType(), Offset + I * ElementWidth); 7115 1.1 joerg if (!ElementValue) 7116 1.1 joerg return None; 7117 1.1 joerg ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue); 7118 1.1 joerg } 7119 1.1 joerg 7120 1.1 joerg return ArrayValue; 7121 1.1 joerg } 7122 1.1 joerg 7123 1.1 joerg Optional<APValue> visit(const Type *Ty, CharUnits Offset) { 7124 1.1 joerg return unsupportedType(QualType(Ty, 0)); 7125 1.1 joerg } 7126 1.1 joerg 7127 1.1 joerg Optional<APValue> visitType(QualType Ty, CharUnits Offset) { 7128 1.1 joerg QualType Can = Ty.getCanonicalType(); 7129 1.1 joerg 7130 1.1 joerg switch (Can->getTypeClass()) { 7131 1.1 joerg #define TYPE(Class, Base) \ 7132 1.1 joerg case Type::Class: \ 7133 1.1 joerg return visit(cast<Class##Type>(Can.getTypePtr()), Offset); 7134 1.1 joerg #define ABSTRACT_TYPE(Class, Base) 7135 1.1 joerg #define NON_CANONICAL_TYPE(Class, Base) \ 7136 1.1 joerg case Type::Class: \ 7137 1.1 joerg llvm_unreachable("non-canonical type should be impossible!"); 7138 1.1 joerg #define DEPENDENT_TYPE(Class, Base) \ 7139 1.1 joerg case Type::Class: \ 7140 1.1 joerg llvm_unreachable( \ 7141 1.1 joerg "dependent types aren't supported in the constant evaluator!"); 7142 1.1 joerg #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \ 7143 1.1 joerg case Type::Class: \ 7144 1.1 joerg llvm_unreachable("either dependent or not canonical!"); 7145 1.1 joerg #include "clang/AST/TypeNodes.inc" 7146 1.1 joerg } 7147 1.1 joerg llvm_unreachable("Unhandled Type::TypeClass"); 7148 1.1 joerg } 7149 1.1 joerg 7150 1.1 joerg public: 7151 1.1 joerg // Pull out a full value of type DstType. 7152 1.1 joerg static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer, 7153 1.1 joerg const CastExpr *BCE) { 7154 1.1 joerg BufferToAPValueConverter Converter(Info, Buffer, BCE); 7155 1.1 joerg return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0)); 7156 1.1 joerg } 7157 1.1 joerg }; 7158 1.1 joerg 7159 1.1 joerg static bool checkBitCastConstexprEligibilityType(SourceLocation Loc, 7160 1.1 joerg QualType Ty, EvalInfo *Info, 7161 1.1 joerg const ASTContext &Ctx, 7162 1.1 joerg bool CheckingDest) { 7163 1.1 joerg Ty = Ty.getCanonicalType(); 7164 1.1 joerg 7165 1.1 joerg auto diag = [&](int Reason) { 7166 1.1 joerg if (Info) 7167 1.1 joerg Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type) 7168 1.1 joerg << CheckingDest << (Reason == 4) << Reason; 7169 1.1 joerg return false; 7170 1.1 joerg }; 7171 1.1 joerg auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) { 7172 1.1 joerg if (Info) 7173 1.1 joerg Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype) 7174 1.1 joerg << NoteTy << Construct << Ty; 7175 1.1 joerg return false; 7176 1.1 joerg }; 7177 1.1 joerg 7178 1.1 joerg if (Ty->isUnionType()) 7179 1.1 joerg return diag(0); 7180 1.1 joerg if (Ty->isPointerType()) 7181 1.1 joerg return diag(1); 7182 1.1 joerg if (Ty->isMemberPointerType()) 7183 1.1 joerg return diag(2); 7184 1.1 joerg if (Ty.isVolatileQualified()) 7185 1.1 joerg return diag(3); 7186 1.1 joerg 7187 1.1 joerg if (RecordDecl *Record = Ty->getAsRecordDecl()) { 7188 1.1 joerg if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) { 7189 1.1 joerg for (CXXBaseSpecifier &BS : CXXRD->bases()) 7190 1.1 joerg if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx, 7191 1.1 joerg CheckingDest)) 7192 1.1 joerg return note(1, BS.getType(), BS.getBeginLoc()); 7193 1.1 joerg } 7194 1.1 joerg for (FieldDecl *FD : Record->fields()) { 7195 1.1 joerg if (FD->getType()->isReferenceType()) 7196 1.1 joerg return diag(4); 7197 1.1 joerg if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx, 7198 1.1 joerg CheckingDest)) 7199 1.1 joerg return note(0, FD->getType(), FD->getBeginLoc()); 7200 1.1 joerg } 7201 1.1 joerg } 7202 1.1 joerg 7203 1.1 joerg if (Ty->isArrayType() && 7204 1.1 joerg !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty), 7205 1.1 joerg Info, Ctx, CheckingDest)) 7206 1.1 joerg return false; 7207 1.1 joerg 7208 1.1 joerg return true; 7209 1.1 joerg } 7210 1.1 joerg 7211 1.1 joerg static bool checkBitCastConstexprEligibility(EvalInfo *Info, 7212 1.1 joerg const ASTContext &Ctx, 7213 1.1 joerg const CastExpr *BCE) { 7214 1.1 joerg bool DestOK = checkBitCastConstexprEligibilityType( 7215 1.1 joerg BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true); 7216 1.1 joerg bool SourceOK = DestOK && checkBitCastConstexprEligibilityType( 7217 1.1 joerg BCE->getBeginLoc(), 7218 1.1 joerg BCE->getSubExpr()->getType(), Info, Ctx, false); 7219 1.1 joerg return SourceOK; 7220 1.1 joerg } 7221 1.1 joerg 7222 1.1 joerg static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue, 7223 1.1 joerg APValue &SourceValue, 7224 1.1 joerg const CastExpr *BCE) { 7225 1.1 joerg assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 && 7226 1.1 joerg "no host or target supports non 8-bit chars"); 7227 1.1 joerg assert(SourceValue.isLValue() && 7228 1.1 joerg "LValueToRValueBitcast requires an lvalue operand!"); 7229 1.1 joerg 7230 1.1 joerg if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE)) 7231 1.1 joerg return false; 7232 1.1 joerg 7233 1.1 joerg LValue SourceLValue; 7234 1.1 joerg APValue SourceRValue; 7235 1.1 joerg SourceLValue.setFrom(Info.Ctx, SourceValue); 7236 1.1 joerg if (!handleLValueToRValueConversion( 7237 1.1 joerg Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue, 7238 1.1 joerg SourceRValue, /*WantObjectRepresentation=*/true)) 7239 1.1 joerg return false; 7240 1.1 joerg 7241 1.1 joerg // Read out SourceValue into a char buffer. 7242 1.1 joerg Optional<BitCastBuffer> Buffer = 7243 1.1 joerg APValueToBufferConverter::convert(Info, SourceRValue, BCE); 7244 1.1 joerg if (!Buffer) 7245 1.1 joerg return false; 7246 1.1 joerg 7247 1.1 joerg // Write out the buffer into a new APValue. 7248 1.1 joerg Optional<APValue> MaybeDestValue = 7249 1.1 joerg BufferToAPValueConverter::convert(Info, *Buffer, BCE); 7250 1.1 joerg if (!MaybeDestValue) 7251 1.1 joerg return false; 7252 1.1 joerg 7253 1.1 joerg DestValue = std::move(*MaybeDestValue); 7254 1.1 joerg return true; 7255 1.1 joerg } 7256 1.1 joerg 7257 1.1 joerg template <class Derived> 7258 1.1 joerg class ExprEvaluatorBase 7259 1.1 joerg : public ConstStmtVisitor<Derived, bool> { 7260 1.1 joerg private: 7261 1.1 joerg Derived &getDerived() { return static_cast<Derived&>(*this); } 7262 1.1 joerg bool DerivedSuccess(const APValue &V, const Expr *E) { 7263 1.1 joerg return getDerived().Success(V, E); 7264 1.1 joerg } 7265 1.1 joerg bool DerivedZeroInitialization(const Expr *E) { 7266 1.1 joerg return getDerived().ZeroInitialization(E); 7267 1.1 joerg } 7268 1.1 joerg 7269 1.1 joerg // Check whether a conditional operator with a non-constant condition is a 7270 1.1 joerg // potential constant expression. If neither arm is a potential constant 7271 1.1 joerg // expression, then the conditional operator is not either. 7272 1.1 joerg template<typename ConditionalOperator> 7273 1.1 joerg void CheckPotentialConstantConditional(const ConditionalOperator *E) { 7274 1.1 joerg assert(Info.checkingPotentialConstantExpression()); 7275 1.1 joerg 7276 1.1 joerg // Speculatively evaluate both arms. 7277 1.1 joerg SmallVector<PartialDiagnosticAt, 8> Diag; 7278 1.1 joerg { 7279 1.1 joerg SpeculativeEvaluationRAII Speculate(Info, &Diag); 7280 1.1 joerg StmtVisitorTy::Visit(E->getFalseExpr()); 7281 1.1 joerg if (Diag.empty()) 7282 1.1 joerg return; 7283 1.1 joerg } 7284 1.1 joerg 7285 1.1 joerg { 7286 1.1 joerg SpeculativeEvaluationRAII Speculate(Info, &Diag); 7287 1.1 joerg Diag.clear(); 7288 1.1 joerg StmtVisitorTy::Visit(E->getTrueExpr()); 7289 1.1 joerg if (Diag.empty()) 7290 1.1 joerg return; 7291 1.1 joerg } 7292 1.1 joerg 7293 1.1 joerg Error(E, diag::note_constexpr_conditional_never_const); 7294 1.1 joerg } 7295 1.1 joerg 7296 1.1 joerg 7297 1.1 joerg template<typename ConditionalOperator> 7298 1.1 joerg bool HandleConditionalOperator(const ConditionalOperator *E) { 7299 1.1 joerg bool BoolResult; 7300 1.1 joerg if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) { 7301 1.1 joerg if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) { 7302 1.1 joerg CheckPotentialConstantConditional(E); 7303 1.1 joerg return false; 7304 1.1 joerg } 7305 1.1 joerg if (Info.noteFailure()) { 7306 1.1 joerg StmtVisitorTy::Visit(E->getTrueExpr()); 7307 1.1 joerg StmtVisitorTy::Visit(E->getFalseExpr()); 7308 1.1 joerg } 7309 1.1 joerg return false; 7310 1.1 joerg } 7311 1.1 joerg 7312 1.1 joerg Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr(); 7313 1.1 joerg return StmtVisitorTy::Visit(EvalExpr); 7314 1.1 joerg } 7315 1.1 joerg 7316 1.1 joerg protected: 7317 1.1 joerg EvalInfo &Info; 7318 1.1 joerg typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy; 7319 1.1 joerg typedef ExprEvaluatorBase ExprEvaluatorBaseTy; 7320 1.1 joerg 7321 1.1 joerg OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 7322 1.1 joerg return Info.CCEDiag(E, D); 7323 1.1 joerg } 7324 1.1 joerg 7325 1.1 joerg bool ZeroInitialization(const Expr *E) { return Error(E); } 7326 1.1 joerg 7327 1.1 joerg public: 7328 1.1 joerg ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {} 7329 1.1 joerg 7330 1.1 joerg EvalInfo &getEvalInfo() { return Info; } 7331 1.1 joerg 7332 1.1 joerg /// Report an evaluation error. This should only be called when an error is 7333 1.1 joerg /// first discovered. When propagating an error, just return false. 7334 1.1 joerg bool Error(const Expr *E, diag::kind D) { 7335 1.1 joerg Info.FFDiag(E, D); 7336 1.1 joerg return false; 7337 1.1 joerg } 7338 1.1 joerg bool Error(const Expr *E) { 7339 1.1 joerg return Error(E, diag::note_invalid_subexpr_in_const_expr); 7340 1.1 joerg } 7341 1.1 joerg 7342 1.1 joerg bool VisitStmt(const Stmt *) { 7343 1.1 joerg llvm_unreachable("Expression evaluator should not be called on stmts"); 7344 1.1 joerg } 7345 1.1 joerg bool VisitExpr(const Expr *E) { 7346 1.1 joerg return Error(E); 7347 1.1 joerg } 7348 1.1 joerg 7349 1.1.1.2 joerg bool VisitConstantExpr(const ConstantExpr *E) { 7350 1.1.1.2 joerg if (E->hasAPValueResult()) 7351 1.1.1.2 joerg return DerivedSuccess(E->getAPValueResult(), E); 7352 1.1.1.2 joerg 7353 1.1.1.2 joerg return StmtVisitorTy::Visit(E->getSubExpr()); 7354 1.1.1.2 joerg } 7355 1.1.1.2 joerg 7356 1.1 joerg bool VisitParenExpr(const ParenExpr *E) 7357 1.1 joerg { return StmtVisitorTy::Visit(E->getSubExpr()); } 7358 1.1 joerg bool VisitUnaryExtension(const UnaryOperator *E) 7359 1.1 joerg { return StmtVisitorTy::Visit(E->getSubExpr()); } 7360 1.1 joerg bool VisitUnaryPlus(const UnaryOperator *E) 7361 1.1 joerg { return StmtVisitorTy::Visit(E->getSubExpr()); } 7362 1.1 joerg bool VisitChooseExpr(const ChooseExpr *E) 7363 1.1 joerg { return StmtVisitorTy::Visit(E->getChosenSubExpr()); } 7364 1.1 joerg bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) 7365 1.1 joerg { return StmtVisitorTy::Visit(E->getResultExpr()); } 7366 1.1 joerg bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E) 7367 1.1 joerg { return StmtVisitorTy::Visit(E->getReplacement()); } 7368 1.1 joerg bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { 7369 1.1 joerg TempVersionRAII RAII(*Info.CurrentCall); 7370 1.1 joerg SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope); 7371 1.1 joerg return StmtVisitorTy::Visit(E->getExpr()); 7372 1.1 joerg } 7373 1.1 joerg bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) { 7374 1.1 joerg TempVersionRAII RAII(*Info.CurrentCall); 7375 1.1 joerg // The initializer may not have been parsed yet, or might be erroneous. 7376 1.1 joerg if (!E->getExpr()) 7377 1.1 joerg return Error(E); 7378 1.1 joerg SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope); 7379 1.1 joerg return StmtVisitorTy::Visit(E->getExpr()); 7380 1.1 joerg } 7381 1.1 joerg 7382 1.1 joerg bool VisitExprWithCleanups(const ExprWithCleanups *E) { 7383 1.1 joerg FullExpressionRAII Scope(Info); 7384 1.1 joerg return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy(); 7385 1.1 joerg } 7386 1.1 joerg 7387 1.1 joerg // Temporaries are registered when created, so we don't care about 7388 1.1 joerg // CXXBindTemporaryExpr. 7389 1.1 joerg bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) { 7390 1.1 joerg return StmtVisitorTy::Visit(E->getSubExpr()); 7391 1.1 joerg } 7392 1.1 joerg 7393 1.1 joerg bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) { 7394 1.1 joerg CCEDiag(E, diag::note_constexpr_invalid_cast) << 0; 7395 1.1 joerg return static_cast<Derived*>(this)->VisitCastExpr(E); 7396 1.1 joerg } 7397 1.1 joerg bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) { 7398 1.1.1.2 joerg if (!Info.Ctx.getLangOpts().CPlusPlus20) 7399 1.1 joerg CCEDiag(E, diag::note_constexpr_invalid_cast) << 1; 7400 1.1 joerg return static_cast<Derived*>(this)->VisitCastExpr(E); 7401 1.1 joerg } 7402 1.1 joerg bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) { 7403 1.1 joerg return static_cast<Derived*>(this)->VisitCastExpr(E); 7404 1.1 joerg } 7405 1.1 joerg 7406 1.1 joerg bool VisitBinaryOperator(const BinaryOperator *E) { 7407 1.1 joerg switch (E->getOpcode()) { 7408 1.1 joerg default: 7409 1.1 joerg return Error(E); 7410 1.1 joerg 7411 1.1 joerg case BO_Comma: 7412 1.1 joerg VisitIgnoredValue(E->getLHS()); 7413 1.1 joerg return StmtVisitorTy::Visit(E->getRHS()); 7414 1.1 joerg 7415 1.1 joerg case BO_PtrMemD: 7416 1.1 joerg case BO_PtrMemI: { 7417 1.1 joerg LValue Obj; 7418 1.1 joerg if (!HandleMemberPointerAccess(Info, E, Obj)) 7419 1.1 joerg return false; 7420 1.1 joerg APValue Result; 7421 1.1 joerg if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result)) 7422 1.1 joerg return false; 7423 1.1 joerg return DerivedSuccess(Result, E); 7424 1.1 joerg } 7425 1.1 joerg } 7426 1.1 joerg } 7427 1.1 joerg 7428 1.1 joerg bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) { 7429 1.1 joerg return StmtVisitorTy::Visit(E->getSemanticForm()); 7430 1.1 joerg } 7431 1.1 joerg 7432 1.1 joerg bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) { 7433 1.1 joerg // Evaluate and cache the common expression. We treat it as a temporary, 7434 1.1 joerg // even though it's not quite the same thing. 7435 1.1 joerg LValue CommonLV; 7436 1.1 joerg if (!Evaluate(Info.CurrentCall->createTemporary( 7437 1.1 joerg E->getOpaqueValue(), 7438 1.1.1.2 joerg getStorageType(Info.Ctx, E->getOpaqueValue()), 7439 1.1.1.2 joerg ScopeKind::FullExpression, CommonLV), 7440 1.1 joerg Info, E->getCommon())) 7441 1.1 joerg return false; 7442 1.1 joerg 7443 1.1 joerg return HandleConditionalOperator(E); 7444 1.1 joerg } 7445 1.1 joerg 7446 1.1 joerg bool VisitConditionalOperator(const ConditionalOperator *E) { 7447 1.1 joerg bool IsBcpCall = false; 7448 1.1 joerg // If the condition (ignoring parens) is a __builtin_constant_p call, 7449 1.1 joerg // the result is a constant expression if it can be folded without 7450 1.1 joerg // side-effects. This is an important GNU extension. See GCC PR38377 7451 1.1 joerg // for discussion. 7452 1.1 joerg if (const CallExpr *CallCE = 7453 1.1 joerg dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts())) 7454 1.1 joerg if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 7455 1.1 joerg IsBcpCall = true; 7456 1.1 joerg 7457 1.1 joerg // Always assume __builtin_constant_p(...) ? ... : ... is a potential 7458 1.1 joerg // constant expression; we can't check whether it's potentially foldable. 7459 1.1 joerg // FIXME: We should instead treat __builtin_constant_p as non-constant if 7460 1.1 joerg // it would return 'false' in this mode. 7461 1.1 joerg if (Info.checkingPotentialConstantExpression() && IsBcpCall) 7462 1.1 joerg return false; 7463 1.1 joerg 7464 1.1 joerg FoldConstant Fold(Info, IsBcpCall); 7465 1.1 joerg if (!HandleConditionalOperator(E)) { 7466 1.1 joerg Fold.keepDiagnostics(); 7467 1.1 joerg return false; 7468 1.1 joerg } 7469 1.1 joerg 7470 1.1 joerg return true; 7471 1.1 joerg } 7472 1.1 joerg 7473 1.1 joerg bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) { 7474 1.1 joerg if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E)) 7475 1.1 joerg return DerivedSuccess(*Value, E); 7476 1.1 joerg 7477 1.1 joerg const Expr *Source = E->getSourceExpr(); 7478 1.1 joerg if (!Source) 7479 1.1 joerg return Error(E); 7480 1.1 joerg if (Source == E) { // sanity checking. 7481 1.1 joerg assert(0 && "OpaqueValueExpr recursively refers to itself"); 7482 1.1 joerg return Error(E); 7483 1.1 joerg } 7484 1.1 joerg return StmtVisitorTy::Visit(Source); 7485 1.1 joerg } 7486 1.1 joerg 7487 1.1.1.2 joerg bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) { 7488 1.1.1.2 joerg for (const Expr *SemE : E->semantics()) { 7489 1.1.1.2 joerg if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) { 7490 1.1.1.2 joerg // FIXME: We can't handle the case where an OpaqueValueExpr is also the 7491 1.1.1.2 joerg // result expression: there could be two different LValues that would 7492 1.1.1.2 joerg // refer to the same object in that case, and we can't model that. 7493 1.1.1.2 joerg if (SemE == E->getResultExpr()) 7494 1.1.1.2 joerg return Error(E); 7495 1.1.1.2 joerg 7496 1.1.1.2 joerg // Unique OVEs get evaluated if and when we encounter them when 7497 1.1.1.2 joerg // emitting the rest of the semantic form, rather than eagerly. 7498 1.1.1.2 joerg if (OVE->isUnique()) 7499 1.1.1.2 joerg continue; 7500 1.1.1.2 joerg 7501 1.1.1.2 joerg LValue LV; 7502 1.1.1.2 joerg if (!Evaluate(Info.CurrentCall->createTemporary( 7503 1.1.1.2 joerg OVE, getStorageType(Info.Ctx, OVE), 7504 1.1.1.2 joerg ScopeKind::FullExpression, LV), 7505 1.1.1.2 joerg Info, OVE->getSourceExpr())) 7506 1.1.1.2 joerg return false; 7507 1.1.1.2 joerg } else if (SemE == E->getResultExpr()) { 7508 1.1.1.2 joerg if (!StmtVisitorTy::Visit(SemE)) 7509 1.1.1.2 joerg return false; 7510 1.1.1.2 joerg } else { 7511 1.1.1.2 joerg if (!EvaluateIgnoredValue(Info, SemE)) 7512 1.1.1.2 joerg return false; 7513 1.1.1.2 joerg } 7514 1.1.1.2 joerg } 7515 1.1.1.2 joerg return true; 7516 1.1.1.2 joerg } 7517 1.1.1.2 joerg 7518 1.1 joerg bool VisitCallExpr(const CallExpr *E) { 7519 1.1 joerg APValue Result; 7520 1.1 joerg if (!handleCallExpr(E, Result, nullptr)) 7521 1.1 joerg return false; 7522 1.1 joerg return DerivedSuccess(Result, E); 7523 1.1 joerg } 7524 1.1 joerg 7525 1.1 joerg bool handleCallExpr(const CallExpr *E, APValue &Result, 7526 1.1 joerg const LValue *ResultSlot) { 7527 1.1.1.2 joerg CallScopeRAII CallScope(Info); 7528 1.1.1.2 joerg 7529 1.1 joerg const Expr *Callee = E->getCallee()->IgnoreParens(); 7530 1.1 joerg QualType CalleeType = Callee->getType(); 7531 1.1 joerg 7532 1.1 joerg const FunctionDecl *FD = nullptr; 7533 1.1 joerg LValue *This = nullptr, ThisVal; 7534 1.1 joerg auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); 7535 1.1 joerg bool HasQualifier = false; 7536 1.1 joerg 7537 1.1.1.2 joerg CallRef Call; 7538 1.1.1.2 joerg 7539 1.1 joerg // Extract function decl and 'this' pointer from the callee. 7540 1.1 joerg if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) { 7541 1.1 joerg const CXXMethodDecl *Member = nullptr; 7542 1.1 joerg if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) { 7543 1.1 joerg // Explicit bound member calls, such as x.f() or p->g(); 7544 1.1 joerg if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal)) 7545 1.1 joerg return false; 7546 1.1 joerg Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 7547 1.1 joerg if (!Member) 7548 1.1 joerg return Error(Callee); 7549 1.1 joerg This = &ThisVal; 7550 1.1 joerg HasQualifier = ME->hasQualifier(); 7551 1.1 joerg } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) { 7552 1.1 joerg // Indirect bound member calls ('.*' or '->*'). 7553 1.1 joerg const ValueDecl *D = 7554 1.1 joerg HandleMemberPointerAccess(Info, BE, ThisVal, false); 7555 1.1 joerg if (!D) 7556 1.1 joerg return false; 7557 1.1 joerg Member = dyn_cast<CXXMethodDecl>(D); 7558 1.1 joerg if (!Member) 7559 1.1 joerg return Error(Callee); 7560 1.1 joerg This = &ThisVal; 7561 1.1 joerg } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) { 7562 1.1.1.2 joerg if (!Info.getLangOpts().CPlusPlus20) 7563 1.1 joerg Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor); 7564 1.1.1.2 joerg return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) && 7565 1.1.1.2 joerg HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType()); 7566 1.1 joerg } else 7567 1.1 joerg return Error(Callee); 7568 1.1 joerg FD = Member; 7569 1.1 joerg } else if (CalleeType->isFunctionPointerType()) { 7570 1.1.1.2 joerg LValue CalleeLV; 7571 1.1.1.2 joerg if (!EvaluatePointer(Callee, CalleeLV, Info)) 7572 1.1 joerg return false; 7573 1.1 joerg 7574 1.1.1.2 joerg if (!CalleeLV.getLValueOffset().isZero()) 7575 1.1 joerg return Error(Callee); 7576 1.1 joerg FD = dyn_cast_or_null<FunctionDecl>( 7577 1.1.1.2 joerg CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>()); 7578 1.1 joerg if (!FD) 7579 1.1 joerg return Error(Callee); 7580 1.1 joerg // Don't call function pointers which have been cast to some other type. 7581 1.1 joerg // Per DR (no number yet), the caller and callee can differ in noexcept. 7582 1.1 joerg if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec( 7583 1.1 joerg CalleeType->getPointeeType(), FD->getType())) { 7584 1.1 joerg return Error(E); 7585 1.1 joerg } 7586 1.1 joerg 7587 1.1.1.2 joerg // For an (overloaded) assignment expression, evaluate the RHS before the 7588 1.1.1.2 joerg // LHS. 7589 1.1.1.2 joerg auto *OCE = dyn_cast<CXXOperatorCallExpr>(E); 7590 1.1.1.2 joerg if (OCE && OCE->isAssignmentOp()) { 7591 1.1.1.2 joerg assert(Args.size() == 2 && "wrong number of arguments in assignment"); 7592 1.1.1.2 joerg Call = Info.CurrentCall->createCall(FD); 7593 1.1.1.2 joerg if (!EvaluateArgs(isa<CXXMethodDecl>(FD) ? Args.slice(1) : Args, Call, 7594 1.1.1.2 joerg Info, FD, /*RightToLeft=*/true)) 7595 1.1.1.2 joerg return false; 7596 1.1.1.2 joerg } 7597 1.1.1.2 joerg 7598 1.1 joerg // Overloaded operator calls to member functions are represented as normal 7599 1.1 joerg // calls with '*this' as the first argument. 7600 1.1 joerg const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 7601 1.1 joerg if (MD && !MD->isStatic()) { 7602 1.1 joerg // FIXME: When selecting an implicit conversion for an overloaded 7603 1.1 joerg // operator delete, we sometimes try to evaluate calls to conversion 7604 1.1 joerg // operators without a 'this' parameter! 7605 1.1 joerg if (Args.empty()) 7606 1.1 joerg return Error(E); 7607 1.1 joerg 7608 1.1 joerg if (!EvaluateObjectArgument(Info, Args[0], ThisVal)) 7609 1.1 joerg return false; 7610 1.1 joerg This = &ThisVal; 7611 1.1 joerg Args = Args.slice(1); 7612 1.1 joerg } else if (MD && MD->isLambdaStaticInvoker()) { 7613 1.1 joerg // Map the static invoker for the lambda back to the call operator. 7614 1.1 joerg // Conveniently, we don't have to slice out the 'this' argument (as is 7615 1.1 joerg // being done for the non-static case), since a static member function 7616 1.1 joerg // doesn't have an implicit argument passed in. 7617 1.1 joerg const CXXRecordDecl *ClosureClass = MD->getParent(); 7618 1.1 joerg assert( 7619 1.1 joerg ClosureClass->captures_begin() == ClosureClass->captures_end() && 7620 1.1 joerg "Number of captures must be zero for conversion to function-ptr"); 7621 1.1 joerg 7622 1.1 joerg const CXXMethodDecl *LambdaCallOp = 7623 1.1 joerg ClosureClass->getLambdaCallOperator(); 7624 1.1 joerg 7625 1.1 joerg // Set 'FD', the function that will be called below, to the call 7626 1.1 joerg // operator. If the closure object represents a generic lambda, find 7627 1.1 joerg // the corresponding specialization of the call operator. 7628 1.1 joerg 7629 1.1 joerg if (ClosureClass->isGenericLambda()) { 7630 1.1 joerg assert(MD->isFunctionTemplateSpecialization() && 7631 1.1 joerg "A generic lambda's static-invoker function must be a " 7632 1.1 joerg "template specialization"); 7633 1.1 joerg const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs(); 7634 1.1 joerg FunctionTemplateDecl *CallOpTemplate = 7635 1.1 joerg LambdaCallOp->getDescribedFunctionTemplate(); 7636 1.1 joerg void *InsertPos = nullptr; 7637 1.1 joerg FunctionDecl *CorrespondingCallOpSpecialization = 7638 1.1 joerg CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos); 7639 1.1 joerg assert(CorrespondingCallOpSpecialization && 7640 1.1 joerg "We must always have a function call operator specialization " 7641 1.1 joerg "that corresponds to our static invoker specialization"); 7642 1.1 joerg FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization); 7643 1.1 joerg } else 7644 1.1 joerg FD = LambdaCallOp; 7645 1.1 joerg } else if (FD->isReplaceableGlobalAllocationFunction()) { 7646 1.1 joerg if (FD->getDeclName().getCXXOverloadedOperator() == OO_New || 7647 1.1 joerg FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) { 7648 1.1 joerg LValue Ptr; 7649 1.1 joerg if (!HandleOperatorNewCall(Info, E, Ptr)) 7650 1.1 joerg return false; 7651 1.1 joerg Ptr.moveInto(Result); 7652 1.1.1.2 joerg return CallScope.destroy(); 7653 1.1 joerg } else { 7654 1.1.1.2 joerg return HandleOperatorDeleteCall(Info, E) && CallScope.destroy(); 7655 1.1 joerg } 7656 1.1 joerg } 7657 1.1 joerg } else 7658 1.1 joerg return Error(E); 7659 1.1 joerg 7660 1.1.1.2 joerg // Evaluate the arguments now if we've not already done so. 7661 1.1.1.2 joerg if (!Call) { 7662 1.1.1.2 joerg Call = Info.CurrentCall->createCall(FD); 7663 1.1.1.2 joerg if (!EvaluateArgs(Args, Call, Info, FD)) 7664 1.1.1.2 joerg return false; 7665 1.1.1.2 joerg } 7666 1.1.1.2 joerg 7667 1.1 joerg SmallVector<QualType, 4> CovariantAdjustmentPath; 7668 1.1 joerg if (This) { 7669 1.1 joerg auto *NamedMember = dyn_cast<CXXMethodDecl>(FD); 7670 1.1 joerg if (NamedMember && NamedMember->isVirtual() && !HasQualifier) { 7671 1.1 joerg // Perform virtual dispatch, if necessary. 7672 1.1 joerg FD = HandleVirtualDispatch(Info, E, *This, NamedMember, 7673 1.1 joerg CovariantAdjustmentPath); 7674 1.1 joerg if (!FD) 7675 1.1 joerg return false; 7676 1.1 joerg } else { 7677 1.1 joerg // Check that the 'this' pointer points to an object of the right type. 7678 1.1 joerg // FIXME: If this is an assignment operator call, we may need to change 7679 1.1 joerg // the active union member before we check this. 7680 1.1 joerg if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember)) 7681 1.1 joerg return false; 7682 1.1 joerg } 7683 1.1 joerg } 7684 1.1 joerg 7685 1.1 joerg // Destructor calls are different enough that they have their own codepath. 7686 1.1 joerg if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) { 7687 1.1 joerg assert(This && "no 'this' pointer for destructor call"); 7688 1.1 joerg return HandleDestruction(Info, E, *This, 7689 1.1.1.2 joerg Info.Ctx.getRecordType(DD->getParent())) && 7690 1.1.1.2 joerg CallScope.destroy(); 7691 1.1 joerg } 7692 1.1 joerg 7693 1.1 joerg const FunctionDecl *Definition = nullptr; 7694 1.1 joerg Stmt *Body = FD->getBody(Definition); 7695 1.1 joerg 7696 1.1 joerg if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) || 7697 1.1.1.2 joerg !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Call, 7698 1.1.1.2 joerg Body, Info, Result, ResultSlot)) 7699 1.1 joerg return false; 7700 1.1 joerg 7701 1.1 joerg if (!CovariantAdjustmentPath.empty() && 7702 1.1 joerg !HandleCovariantReturnAdjustment(Info, E, Result, 7703 1.1 joerg CovariantAdjustmentPath)) 7704 1.1 joerg return false; 7705 1.1 joerg 7706 1.1.1.2 joerg return CallScope.destroy(); 7707 1.1 joerg } 7708 1.1 joerg 7709 1.1 joerg bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 7710 1.1 joerg return StmtVisitorTy::Visit(E->getInitializer()); 7711 1.1 joerg } 7712 1.1 joerg bool VisitInitListExpr(const InitListExpr *E) { 7713 1.1 joerg if (E->getNumInits() == 0) 7714 1.1 joerg return DerivedZeroInitialization(E); 7715 1.1 joerg if (E->getNumInits() == 1) 7716 1.1 joerg return StmtVisitorTy::Visit(E->getInit(0)); 7717 1.1 joerg return Error(E); 7718 1.1 joerg } 7719 1.1 joerg bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) { 7720 1.1 joerg return DerivedZeroInitialization(E); 7721 1.1 joerg } 7722 1.1 joerg bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) { 7723 1.1 joerg return DerivedZeroInitialization(E); 7724 1.1 joerg } 7725 1.1 joerg bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) { 7726 1.1 joerg return DerivedZeroInitialization(E); 7727 1.1 joerg } 7728 1.1 joerg 7729 1.1 joerg /// A member expression where the object is a prvalue is itself a prvalue. 7730 1.1 joerg bool VisitMemberExpr(const MemberExpr *E) { 7731 1.1 joerg assert(!Info.Ctx.getLangOpts().CPlusPlus11 && 7732 1.1 joerg "missing temporary materialization conversion"); 7733 1.1 joerg assert(!E->isArrow() && "missing call to bound member function?"); 7734 1.1 joerg 7735 1.1 joerg APValue Val; 7736 1.1 joerg if (!Evaluate(Val, Info, E->getBase())) 7737 1.1 joerg return false; 7738 1.1 joerg 7739 1.1 joerg QualType BaseTy = E->getBase()->getType(); 7740 1.1 joerg 7741 1.1 joerg const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl()); 7742 1.1 joerg if (!FD) return Error(E); 7743 1.1 joerg assert(!FD->getType()->isReferenceType() && "prvalue reference?"); 7744 1.1 joerg assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == 7745 1.1 joerg FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 7746 1.1 joerg 7747 1.1 joerg // Note: there is no lvalue base here. But this case should only ever 7748 1.1 joerg // happen in C or in C++98, where we cannot be evaluating a constexpr 7749 1.1 joerg // constructor, which is the only case the base matters. 7750 1.1 joerg CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy); 7751 1.1 joerg SubobjectDesignator Designator(BaseTy); 7752 1.1 joerg Designator.addDeclUnchecked(FD); 7753 1.1 joerg 7754 1.1 joerg APValue Result; 7755 1.1 joerg return extractSubobject(Info, E, Obj, Designator, Result) && 7756 1.1 joerg DerivedSuccess(Result, E); 7757 1.1 joerg } 7758 1.1 joerg 7759 1.1.1.2 joerg bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) { 7760 1.1.1.2 joerg APValue Val; 7761 1.1.1.2 joerg if (!Evaluate(Val, Info, E->getBase())) 7762 1.1.1.2 joerg return false; 7763 1.1.1.2 joerg 7764 1.1.1.2 joerg if (Val.isVector()) { 7765 1.1.1.2 joerg SmallVector<uint32_t, 4> Indices; 7766 1.1.1.2 joerg E->getEncodedElementAccess(Indices); 7767 1.1.1.2 joerg if (Indices.size() == 1) { 7768 1.1.1.2 joerg // Return scalar. 7769 1.1.1.2 joerg return DerivedSuccess(Val.getVectorElt(Indices[0]), E); 7770 1.1.1.2 joerg } else { 7771 1.1.1.2 joerg // Construct new APValue vector. 7772 1.1.1.2 joerg SmallVector<APValue, 4> Elts; 7773 1.1.1.2 joerg for (unsigned I = 0; I < Indices.size(); ++I) { 7774 1.1.1.2 joerg Elts.push_back(Val.getVectorElt(Indices[I])); 7775 1.1.1.2 joerg } 7776 1.1.1.2 joerg APValue VecResult(Elts.data(), Indices.size()); 7777 1.1.1.2 joerg return DerivedSuccess(VecResult, E); 7778 1.1.1.2 joerg } 7779 1.1.1.2 joerg } 7780 1.1.1.2 joerg 7781 1.1.1.2 joerg return false; 7782 1.1.1.2 joerg } 7783 1.1.1.2 joerg 7784 1.1 joerg bool VisitCastExpr(const CastExpr *E) { 7785 1.1 joerg switch (E->getCastKind()) { 7786 1.1 joerg default: 7787 1.1 joerg break; 7788 1.1 joerg 7789 1.1 joerg case CK_AtomicToNonAtomic: { 7790 1.1 joerg APValue AtomicVal; 7791 1.1 joerg // This does not need to be done in place even for class/array types: 7792 1.1 joerg // atomic-to-non-atomic conversion implies copying the object 7793 1.1 joerg // representation. 7794 1.1 joerg if (!Evaluate(AtomicVal, Info, E->getSubExpr())) 7795 1.1 joerg return false; 7796 1.1 joerg return DerivedSuccess(AtomicVal, E); 7797 1.1 joerg } 7798 1.1 joerg 7799 1.1 joerg case CK_NoOp: 7800 1.1 joerg case CK_UserDefinedConversion: 7801 1.1 joerg return StmtVisitorTy::Visit(E->getSubExpr()); 7802 1.1 joerg 7803 1.1 joerg case CK_LValueToRValue: { 7804 1.1 joerg LValue LVal; 7805 1.1 joerg if (!EvaluateLValue(E->getSubExpr(), LVal, Info)) 7806 1.1 joerg return false; 7807 1.1 joerg APValue RVal; 7808 1.1 joerg // Note, we use the subexpression's type in order to retain cv-qualifiers. 7809 1.1 joerg if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 7810 1.1 joerg LVal, RVal)) 7811 1.1 joerg return false; 7812 1.1 joerg return DerivedSuccess(RVal, E); 7813 1.1 joerg } 7814 1.1 joerg case CK_LValueToRValueBitCast: { 7815 1.1 joerg APValue DestValue, SourceValue; 7816 1.1 joerg if (!Evaluate(SourceValue, Info, E->getSubExpr())) 7817 1.1 joerg return false; 7818 1.1 joerg if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E)) 7819 1.1 joerg return false; 7820 1.1 joerg return DerivedSuccess(DestValue, E); 7821 1.1 joerg } 7822 1.1.1.2 joerg 7823 1.1.1.2 joerg case CK_AddressSpaceConversion: { 7824 1.1.1.2 joerg APValue Value; 7825 1.1.1.2 joerg if (!Evaluate(Value, Info, E->getSubExpr())) 7826 1.1.1.2 joerg return false; 7827 1.1.1.2 joerg return DerivedSuccess(Value, E); 7828 1.1.1.2 joerg } 7829 1.1 joerg } 7830 1.1 joerg 7831 1.1 joerg return Error(E); 7832 1.1 joerg } 7833 1.1 joerg 7834 1.1 joerg bool VisitUnaryPostInc(const UnaryOperator *UO) { 7835 1.1 joerg return VisitUnaryPostIncDec(UO); 7836 1.1 joerg } 7837 1.1 joerg bool VisitUnaryPostDec(const UnaryOperator *UO) { 7838 1.1 joerg return VisitUnaryPostIncDec(UO); 7839 1.1 joerg } 7840 1.1 joerg bool VisitUnaryPostIncDec(const UnaryOperator *UO) { 7841 1.1 joerg if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 7842 1.1 joerg return Error(UO); 7843 1.1 joerg 7844 1.1 joerg LValue LVal; 7845 1.1 joerg if (!EvaluateLValue(UO->getSubExpr(), LVal, Info)) 7846 1.1 joerg return false; 7847 1.1 joerg APValue RVal; 7848 1.1 joerg if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(), 7849 1.1 joerg UO->isIncrementOp(), &RVal)) 7850 1.1 joerg return false; 7851 1.1 joerg return DerivedSuccess(RVal, UO); 7852 1.1 joerg } 7853 1.1 joerg 7854 1.1 joerg bool VisitStmtExpr(const StmtExpr *E) { 7855 1.1 joerg // We will have checked the full-expressions inside the statement expression 7856 1.1 joerg // when they were completed, and don't need to check them again now. 7857 1.1.1.2 joerg llvm::SaveAndRestore<bool> NotCheckingForUB( 7858 1.1.1.2 joerg Info.CheckingForUndefinedBehavior, false); 7859 1.1 joerg 7860 1.1 joerg const CompoundStmt *CS = E->getSubStmt(); 7861 1.1 joerg if (CS->body_empty()) 7862 1.1 joerg return true; 7863 1.1 joerg 7864 1.1 joerg BlockScopeRAII Scope(Info); 7865 1.1 joerg for (CompoundStmt::const_body_iterator BI = CS->body_begin(), 7866 1.1 joerg BE = CS->body_end(); 7867 1.1 joerg /**/; ++BI) { 7868 1.1 joerg if (BI + 1 == BE) { 7869 1.1 joerg const Expr *FinalExpr = dyn_cast<Expr>(*BI); 7870 1.1 joerg if (!FinalExpr) { 7871 1.1 joerg Info.FFDiag((*BI)->getBeginLoc(), 7872 1.1 joerg diag::note_constexpr_stmt_expr_unsupported); 7873 1.1 joerg return false; 7874 1.1 joerg } 7875 1.1 joerg return this->Visit(FinalExpr) && Scope.destroy(); 7876 1.1 joerg } 7877 1.1 joerg 7878 1.1 joerg APValue ReturnValue; 7879 1.1 joerg StmtResult Result = { ReturnValue, nullptr }; 7880 1.1 joerg EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI); 7881 1.1 joerg if (ESR != ESR_Succeeded) { 7882 1.1 joerg // FIXME: If the statement-expression terminated due to 'return', 7883 1.1 joerg // 'break', or 'continue', it would be nice to propagate that to 7884 1.1 joerg // the outer statement evaluation rather than bailing out. 7885 1.1 joerg if (ESR != ESR_Failed) 7886 1.1 joerg Info.FFDiag((*BI)->getBeginLoc(), 7887 1.1 joerg diag::note_constexpr_stmt_expr_unsupported); 7888 1.1 joerg return false; 7889 1.1 joerg } 7890 1.1 joerg } 7891 1.1 joerg 7892 1.1 joerg llvm_unreachable("Return from function from the loop above."); 7893 1.1 joerg } 7894 1.1 joerg 7895 1.1 joerg /// Visit a value which is evaluated, but whose value is ignored. 7896 1.1 joerg void VisitIgnoredValue(const Expr *E) { 7897 1.1 joerg EvaluateIgnoredValue(Info, E); 7898 1.1 joerg } 7899 1.1 joerg 7900 1.1 joerg /// Potentially visit a MemberExpr's base expression. 7901 1.1 joerg void VisitIgnoredBaseExpression(const Expr *E) { 7902 1.1 joerg // While MSVC doesn't evaluate the base expression, it does diagnose the 7903 1.1 joerg // presence of side-effecting behavior. 7904 1.1 joerg if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx)) 7905 1.1 joerg return; 7906 1.1 joerg VisitIgnoredValue(E); 7907 1.1 joerg } 7908 1.1 joerg }; 7909 1.1 joerg 7910 1.1 joerg } // namespace 7911 1.1 joerg 7912 1.1 joerg //===----------------------------------------------------------------------===// 7913 1.1 joerg // Common base class for lvalue and temporary evaluation. 7914 1.1 joerg //===----------------------------------------------------------------------===// 7915 1.1 joerg namespace { 7916 1.1 joerg template<class Derived> 7917 1.1 joerg class LValueExprEvaluatorBase 7918 1.1 joerg : public ExprEvaluatorBase<Derived> { 7919 1.1 joerg protected: 7920 1.1 joerg LValue &Result; 7921 1.1 joerg bool InvalidBaseOK; 7922 1.1 joerg typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy; 7923 1.1 joerg typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy; 7924 1.1 joerg 7925 1.1 joerg bool Success(APValue::LValueBase B) { 7926 1.1 joerg Result.set(B); 7927 1.1 joerg return true; 7928 1.1 joerg } 7929 1.1 joerg 7930 1.1 joerg bool evaluatePointer(const Expr *E, LValue &Result) { 7931 1.1 joerg return EvaluatePointer(E, Result, this->Info, InvalidBaseOK); 7932 1.1 joerg } 7933 1.1 joerg 7934 1.1 joerg public: 7935 1.1 joerg LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) 7936 1.1 joerg : ExprEvaluatorBaseTy(Info), Result(Result), 7937 1.1 joerg InvalidBaseOK(InvalidBaseOK) {} 7938 1.1 joerg 7939 1.1 joerg bool Success(const APValue &V, const Expr *E) { 7940 1.1 joerg Result.setFrom(this->Info.Ctx, V); 7941 1.1 joerg return true; 7942 1.1 joerg } 7943 1.1 joerg 7944 1.1 joerg bool VisitMemberExpr(const MemberExpr *E) { 7945 1.1 joerg // Handle non-static data members. 7946 1.1 joerg QualType BaseTy; 7947 1.1 joerg bool EvalOK; 7948 1.1 joerg if (E->isArrow()) { 7949 1.1 joerg EvalOK = evaluatePointer(E->getBase(), Result); 7950 1.1 joerg BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType(); 7951 1.1 joerg } else if (E->getBase()->isRValue()) { 7952 1.1 joerg assert(E->getBase()->getType()->isRecordType()); 7953 1.1 joerg EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info); 7954 1.1 joerg BaseTy = E->getBase()->getType(); 7955 1.1 joerg } else { 7956 1.1 joerg EvalOK = this->Visit(E->getBase()); 7957 1.1 joerg BaseTy = E->getBase()->getType(); 7958 1.1 joerg } 7959 1.1 joerg if (!EvalOK) { 7960 1.1 joerg if (!InvalidBaseOK) 7961 1.1 joerg return false; 7962 1.1 joerg Result.setInvalid(E); 7963 1.1 joerg return true; 7964 1.1 joerg } 7965 1.1 joerg 7966 1.1 joerg const ValueDecl *MD = E->getMemberDecl(); 7967 1.1 joerg if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) { 7968 1.1 joerg assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == 7969 1.1 joerg FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 7970 1.1 joerg (void)BaseTy; 7971 1.1 joerg if (!HandleLValueMember(this->Info, E, Result, FD)) 7972 1.1 joerg return false; 7973 1.1 joerg } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) { 7974 1.1 joerg if (!HandleLValueIndirectMember(this->Info, E, Result, IFD)) 7975 1.1 joerg return false; 7976 1.1 joerg } else 7977 1.1 joerg return this->Error(E); 7978 1.1 joerg 7979 1.1 joerg if (MD->getType()->isReferenceType()) { 7980 1.1 joerg APValue RefValue; 7981 1.1 joerg if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result, 7982 1.1 joerg RefValue)) 7983 1.1 joerg return false; 7984 1.1 joerg return Success(RefValue, E); 7985 1.1 joerg } 7986 1.1 joerg return true; 7987 1.1 joerg } 7988 1.1 joerg 7989 1.1 joerg bool VisitBinaryOperator(const BinaryOperator *E) { 7990 1.1 joerg switch (E->getOpcode()) { 7991 1.1 joerg default: 7992 1.1 joerg return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 7993 1.1 joerg 7994 1.1 joerg case BO_PtrMemD: 7995 1.1 joerg case BO_PtrMemI: 7996 1.1 joerg return HandleMemberPointerAccess(this->Info, E, Result); 7997 1.1 joerg } 7998 1.1 joerg } 7999 1.1 joerg 8000 1.1 joerg bool VisitCastExpr(const CastExpr *E) { 8001 1.1 joerg switch (E->getCastKind()) { 8002 1.1 joerg default: 8003 1.1 joerg return ExprEvaluatorBaseTy::VisitCastExpr(E); 8004 1.1 joerg 8005 1.1 joerg case CK_DerivedToBase: 8006 1.1 joerg case CK_UncheckedDerivedToBase: 8007 1.1 joerg if (!this->Visit(E->getSubExpr())) 8008 1.1 joerg return false; 8009 1.1 joerg 8010 1.1 joerg // Now figure out the necessary offset to add to the base LV to get from 8011 1.1 joerg // the derived class to the base class. 8012 1.1 joerg return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(), 8013 1.1 joerg Result); 8014 1.1 joerg } 8015 1.1 joerg } 8016 1.1 joerg }; 8017 1.1 joerg } 8018 1.1 joerg 8019 1.1 joerg //===----------------------------------------------------------------------===// 8020 1.1 joerg // LValue Evaluation 8021 1.1 joerg // 8022 1.1 joerg // This is used for evaluating lvalues (in C and C++), xvalues (in C++11), 8023 1.1 joerg // function designators (in C), decl references to void objects (in C), and 8024 1.1 joerg // temporaries (if building with -Wno-address-of-temporary). 8025 1.1 joerg // 8026 1.1 joerg // LValue evaluation produces values comprising a base expression of one of the 8027 1.1 joerg // following types: 8028 1.1 joerg // - Declarations 8029 1.1 joerg // * VarDecl 8030 1.1 joerg // * FunctionDecl 8031 1.1 joerg // - Literals 8032 1.1 joerg // * CompoundLiteralExpr in C (and in global scope in C++) 8033 1.1 joerg // * StringLiteral 8034 1.1 joerg // * PredefinedExpr 8035 1.1 joerg // * ObjCStringLiteralExpr 8036 1.1 joerg // * ObjCEncodeExpr 8037 1.1 joerg // * AddrLabelExpr 8038 1.1 joerg // * BlockExpr 8039 1.1 joerg // * CallExpr for a MakeStringConstant builtin 8040 1.1 joerg // - typeid(T) expressions, as TypeInfoLValues 8041 1.1 joerg // - Locals and temporaries 8042 1.1 joerg // * MaterializeTemporaryExpr 8043 1.1 joerg // * Any Expr, with a CallIndex indicating the function in which the temporary 8044 1.1 joerg // was evaluated, for cases where the MaterializeTemporaryExpr is missing 8045 1.1 joerg // from the AST (FIXME). 8046 1.1 joerg // * A MaterializeTemporaryExpr that has static storage duration, with no 8047 1.1 joerg // CallIndex, for a lifetime-extended temporary. 8048 1.1.1.2 joerg // * The ConstantExpr that is currently being evaluated during evaluation of an 8049 1.1.1.2 joerg // immediate invocation. 8050 1.1 joerg // plus an offset in bytes. 8051 1.1 joerg //===----------------------------------------------------------------------===// 8052 1.1 joerg namespace { 8053 1.1 joerg class LValueExprEvaluator 8054 1.1 joerg : public LValueExprEvaluatorBase<LValueExprEvaluator> { 8055 1.1 joerg public: 8056 1.1 joerg LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) : 8057 1.1 joerg LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {} 8058 1.1 joerg 8059 1.1 joerg bool VisitVarDecl(const Expr *E, const VarDecl *VD); 8060 1.1 joerg bool VisitUnaryPreIncDec(const UnaryOperator *UO); 8061 1.1 joerg 8062 1.1 joerg bool VisitDeclRefExpr(const DeclRefExpr *E); 8063 1.1 joerg bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); } 8064 1.1 joerg bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E); 8065 1.1 joerg bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E); 8066 1.1 joerg bool VisitMemberExpr(const MemberExpr *E); 8067 1.1 joerg bool VisitStringLiteral(const StringLiteral *E) { return Success(E); } 8068 1.1 joerg bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); } 8069 1.1 joerg bool VisitCXXTypeidExpr(const CXXTypeidExpr *E); 8070 1.1 joerg bool VisitCXXUuidofExpr(const CXXUuidofExpr *E); 8071 1.1 joerg bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E); 8072 1.1 joerg bool VisitUnaryDeref(const UnaryOperator *E); 8073 1.1 joerg bool VisitUnaryReal(const UnaryOperator *E); 8074 1.1 joerg bool VisitUnaryImag(const UnaryOperator *E); 8075 1.1 joerg bool VisitUnaryPreInc(const UnaryOperator *UO) { 8076 1.1 joerg return VisitUnaryPreIncDec(UO); 8077 1.1 joerg } 8078 1.1 joerg bool VisitUnaryPreDec(const UnaryOperator *UO) { 8079 1.1 joerg return VisitUnaryPreIncDec(UO); 8080 1.1 joerg } 8081 1.1 joerg bool VisitBinAssign(const BinaryOperator *BO); 8082 1.1 joerg bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO); 8083 1.1 joerg 8084 1.1 joerg bool VisitCastExpr(const CastExpr *E) { 8085 1.1 joerg switch (E->getCastKind()) { 8086 1.1 joerg default: 8087 1.1 joerg return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 8088 1.1 joerg 8089 1.1 joerg case CK_LValueBitCast: 8090 1.1 joerg this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 8091 1.1 joerg if (!Visit(E->getSubExpr())) 8092 1.1 joerg return false; 8093 1.1 joerg Result.Designator.setInvalid(); 8094 1.1 joerg return true; 8095 1.1 joerg 8096 1.1 joerg case CK_BaseToDerived: 8097 1.1 joerg if (!Visit(E->getSubExpr())) 8098 1.1 joerg return false; 8099 1.1 joerg return HandleBaseToDerivedCast(Info, E, Result); 8100 1.1 joerg 8101 1.1 joerg case CK_Dynamic: 8102 1.1 joerg if (!Visit(E->getSubExpr())) 8103 1.1 joerg return false; 8104 1.1 joerg return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result); 8105 1.1 joerg } 8106 1.1 joerg } 8107 1.1 joerg }; 8108 1.1 joerg } // end anonymous namespace 8109 1.1 joerg 8110 1.1 joerg /// Evaluate an expression as an lvalue. This can be legitimately called on 8111 1.1 joerg /// expressions which are not glvalues, in three cases: 8112 1.1 joerg /// * function designators in C, and 8113 1.1 joerg /// * "extern void" objects 8114 1.1 joerg /// * @selector() expressions in Objective-C 8115 1.1 joerg static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, 8116 1.1 joerg bool InvalidBaseOK) { 8117 1.1.1.2 joerg assert(!E->isValueDependent()); 8118 1.1 joerg assert(E->isGLValue() || E->getType()->isFunctionType() || 8119 1.1 joerg E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E)); 8120 1.1 joerg return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); 8121 1.1 joerg } 8122 1.1 joerg 8123 1.1 joerg bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) { 8124 1.1.1.2 joerg const NamedDecl *D = E->getDecl(); 8125 1.1.1.2 joerg if (isa<FunctionDecl, MSGuidDecl, TemplateParamObjectDecl>(D)) 8126 1.1.1.2 joerg return Success(cast<ValueDecl>(D)); 8127 1.1.1.2 joerg if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 8128 1.1 joerg return VisitVarDecl(E, VD); 8129 1.1.1.2 joerg if (const BindingDecl *BD = dyn_cast<BindingDecl>(D)) 8130 1.1 joerg return Visit(BD->getBinding()); 8131 1.1 joerg return Error(E); 8132 1.1 joerg } 8133 1.1 joerg 8134 1.1 joerg 8135 1.1 joerg bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) { 8136 1.1 joerg 8137 1.1 joerg // If we are within a lambda's call operator, check whether the 'VD' referred 8138 1.1 joerg // to within 'E' actually represents a lambda-capture that maps to a 8139 1.1 joerg // data-member/field within the closure object, and if so, evaluate to the 8140 1.1 joerg // field or what the field refers to. 8141 1.1 joerg if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) && 8142 1.1 joerg isa<DeclRefExpr>(E) && 8143 1.1 joerg cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) { 8144 1.1 joerg // We don't always have a complete capture-map when checking or inferring if 8145 1.1 joerg // the function call operator meets the requirements of a constexpr function 8146 1.1 joerg // - but we don't need to evaluate the captures to determine constexprness 8147 1.1 joerg // (dcl.constexpr C++17). 8148 1.1 joerg if (Info.checkingPotentialConstantExpression()) 8149 1.1 joerg return false; 8150 1.1 joerg 8151 1.1 joerg if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) { 8152 1.1 joerg // Start with 'Result' referring to the complete closure object... 8153 1.1 joerg Result = *Info.CurrentCall->This; 8154 1.1 joerg // ... then update it to refer to the field of the closure object 8155 1.1 joerg // that represents the capture. 8156 1.1 joerg if (!HandleLValueMember(Info, E, Result, FD)) 8157 1.1 joerg return false; 8158 1.1 joerg // And if the field is of reference type, update 'Result' to refer to what 8159 1.1 joerg // the field refers to. 8160 1.1 joerg if (FD->getType()->isReferenceType()) { 8161 1.1 joerg APValue RVal; 8162 1.1 joerg if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result, 8163 1.1 joerg RVal)) 8164 1.1 joerg return false; 8165 1.1 joerg Result.setFrom(Info.Ctx, RVal); 8166 1.1 joerg } 8167 1.1 joerg return true; 8168 1.1 joerg } 8169 1.1 joerg } 8170 1.1.1.2 joerg 8171 1.1 joerg CallStackFrame *Frame = nullptr; 8172 1.1.1.2 joerg unsigned Version = 0; 8173 1.1.1.2 joerg if (VD->hasLocalStorage()) { 8174 1.1 joerg // Only if a local variable was declared in the function currently being 8175 1.1 joerg // evaluated, do we expect to be able to find its value in the current 8176 1.1 joerg // frame. (Otherwise it was likely declared in an enclosing context and 8177 1.1 joerg // could either have a valid evaluatable value (for e.g. a constexpr 8178 1.1 joerg // variable) or be ill-formed (and trigger an appropriate evaluation 8179 1.1 joerg // diagnostic)). 8180 1.1.1.2 joerg CallStackFrame *CurrFrame = Info.CurrentCall; 8181 1.1.1.2 joerg if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) { 8182 1.1.1.2 joerg // Function parameters are stored in some caller's frame. (Usually the 8183 1.1.1.2 joerg // immediate caller, but for an inherited constructor they may be more 8184 1.1.1.2 joerg // distant.) 8185 1.1.1.2 joerg if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) { 8186 1.1.1.2 joerg if (CurrFrame->Arguments) { 8187 1.1.1.2 joerg VD = CurrFrame->Arguments.getOrigParam(PVD); 8188 1.1.1.2 joerg Frame = 8189 1.1.1.2 joerg Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first; 8190 1.1.1.2 joerg Version = CurrFrame->Arguments.Version; 8191 1.1.1.2 joerg } 8192 1.1.1.2 joerg } else { 8193 1.1.1.2 joerg Frame = CurrFrame; 8194 1.1.1.2 joerg Version = CurrFrame->getCurrentTemporaryVersion(VD); 8195 1.1.1.2 joerg } 8196 1.1 joerg } 8197 1.1 joerg } 8198 1.1 joerg 8199 1.1 joerg if (!VD->getType()->isReferenceType()) { 8200 1.1 joerg if (Frame) { 8201 1.1.1.2 joerg Result.set({VD, Frame->Index, Version}); 8202 1.1 joerg return true; 8203 1.1 joerg } 8204 1.1 joerg return Success(VD); 8205 1.1 joerg } 8206 1.1 joerg 8207 1.1.1.2 joerg if (!Info.getLangOpts().CPlusPlus11) { 8208 1.1.1.2 joerg Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1) 8209 1.1.1.2 joerg << VD << VD->getType(); 8210 1.1.1.2 joerg Info.Note(VD->getLocation(), diag::note_declared_at); 8211 1.1.1.2 joerg } 8212 1.1.1.2 joerg 8213 1.1 joerg APValue *V; 8214 1.1.1.2 joerg if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V)) 8215 1.1 joerg return false; 8216 1.1 joerg if (!V->hasValue()) { 8217 1.1 joerg // FIXME: Is it possible for V to be indeterminate here? If so, we should 8218 1.1 joerg // adjust the diagnostic to say that. 8219 1.1 joerg if (!Info.checkingPotentialConstantExpression()) 8220 1.1 joerg Info.FFDiag(E, diag::note_constexpr_use_uninit_reference); 8221 1.1 joerg return false; 8222 1.1 joerg } 8223 1.1 joerg return Success(*V, E); 8224 1.1 joerg } 8225 1.1 joerg 8226 1.1 joerg bool LValueExprEvaluator::VisitMaterializeTemporaryExpr( 8227 1.1 joerg const MaterializeTemporaryExpr *E) { 8228 1.1 joerg // Walk through the expression to find the materialized temporary itself. 8229 1.1 joerg SmallVector<const Expr *, 2> CommaLHSs; 8230 1.1 joerg SmallVector<SubobjectAdjustment, 2> Adjustments; 8231 1.1.1.2 joerg const Expr *Inner = 8232 1.1.1.2 joerg E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments); 8233 1.1 joerg 8234 1.1 joerg // If we passed any comma operators, evaluate their LHSs. 8235 1.1 joerg for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I) 8236 1.1 joerg if (!EvaluateIgnoredValue(Info, CommaLHSs[I])) 8237 1.1 joerg return false; 8238 1.1 joerg 8239 1.1 joerg // A materialized temporary with static storage duration can appear within the 8240 1.1 joerg // result of a constant expression evaluation, so we need to preserve its 8241 1.1 joerg // value for use outside this evaluation. 8242 1.1 joerg APValue *Value; 8243 1.1 joerg if (E->getStorageDuration() == SD_Static) { 8244 1.1.1.2 joerg // FIXME: What about SD_Thread? 8245 1.1.1.2 joerg Value = E->getOrCreateValue(true); 8246 1.1 joerg *Value = APValue(); 8247 1.1 joerg Result.set(E); 8248 1.1 joerg } else { 8249 1.1 joerg Value = &Info.CurrentCall->createTemporary( 8250 1.1.1.2 joerg E, E->getType(), 8251 1.1.1.2 joerg E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression 8252 1.1.1.2 joerg : ScopeKind::Block, 8253 1.1.1.2 joerg Result); 8254 1.1 joerg } 8255 1.1 joerg 8256 1.1 joerg QualType Type = Inner->getType(); 8257 1.1 joerg 8258 1.1 joerg // Materialize the temporary itself. 8259 1.1 joerg if (!EvaluateInPlace(*Value, Info, Result, Inner)) { 8260 1.1 joerg *Value = APValue(); 8261 1.1 joerg return false; 8262 1.1 joerg } 8263 1.1 joerg 8264 1.1 joerg // Adjust our lvalue to refer to the desired subobject. 8265 1.1 joerg for (unsigned I = Adjustments.size(); I != 0; /**/) { 8266 1.1 joerg --I; 8267 1.1 joerg switch (Adjustments[I].Kind) { 8268 1.1 joerg case SubobjectAdjustment::DerivedToBaseAdjustment: 8269 1.1 joerg if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath, 8270 1.1 joerg Type, Result)) 8271 1.1 joerg return false; 8272 1.1 joerg Type = Adjustments[I].DerivedToBase.BasePath->getType(); 8273 1.1 joerg break; 8274 1.1 joerg 8275 1.1 joerg case SubobjectAdjustment::FieldAdjustment: 8276 1.1 joerg if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field)) 8277 1.1 joerg return false; 8278 1.1 joerg Type = Adjustments[I].Field->getType(); 8279 1.1 joerg break; 8280 1.1 joerg 8281 1.1 joerg case SubobjectAdjustment::MemberPointerAdjustment: 8282 1.1 joerg if (!HandleMemberPointerAccess(this->Info, Type, Result, 8283 1.1 joerg Adjustments[I].Ptr.RHS)) 8284 1.1 joerg return false; 8285 1.1 joerg Type = Adjustments[I].Ptr.MPT->getPointeeType(); 8286 1.1 joerg break; 8287 1.1 joerg } 8288 1.1 joerg } 8289 1.1 joerg 8290 1.1 joerg return true; 8291 1.1 joerg } 8292 1.1 joerg 8293 1.1 joerg bool 8294 1.1 joerg LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 8295 1.1 joerg assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) && 8296 1.1 joerg "lvalue compound literal in c++?"); 8297 1.1 joerg // Defer visiting the literal until the lvalue-to-rvalue conversion. We can 8298 1.1 joerg // only see this when folding in C, so there's no standard to follow here. 8299 1.1 joerg return Success(E); 8300 1.1 joerg } 8301 1.1 joerg 8302 1.1 joerg bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) { 8303 1.1 joerg TypeInfoLValue TypeInfo; 8304 1.1 joerg 8305 1.1 joerg if (!E->isPotentiallyEvaluated()) { 8306 1.1 joerg if (E->isTypeOperand()) 8307 1.1 joerg TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr()); 8308 1.1 joerg else 8309 1.1 joerg TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr()); 8310 1.1 joerg } else { 8311 1.1.1.2 joerg if (!Info.Ctx.getLangOpts().CPlusPlus20) { 8312 1.1 joerg Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic) 8313 1.1 joerg << E->getExprOperand()->getType() 8314 1.1 joerg << E->getExprOperand()->getSourceRange(); 8315 1.1 joerg } 8316 1.1 joerg 8317 1.1 joerg if (!Visit(E->getExprOperand())) 8318 1.1 joerg return false; 8319 1.1 joerg 8320 1.1 joerg Optional<DynamicType> DynType = 8321 1.1 joerg ComputeDynamicType(Info, E, Result, AK_TypeId); 8322 1.1 joerg if (!DynType) 8323 1.1 joerg return false; 8324 1.1 joerg 8325 1.1 joerg TypeInfo = 8326 1.1 joerg TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr()); 8327 1.1 joerg } 8328 1.1 joerg 8329 1.1 joerg return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType())); 8330 1.1 joerg } 8331 1.1 joerg 8332 1.1 joerg bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) { 8333 1.1.1.2 joerg return Success(E->getGuidDecl()); 8334 1.1 joerg } 8335 1.1 joerg 8336 1.1 joerg bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) { 8337 1.1 joerg // Handle static data members. 8338 1.1 joerg if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) { 8339 1.1 joerg VisitIgnoredBaseExpression(E->getBase()); 8340 1.1 joerg return VisitVarDecl(E, VD); 8341 1.1 joerg } 8342 1.1 joerg 8343 1.1 joerg // Handle static member functions. 8344 1.1 joerg if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) { 8345 1.1 joerg if (MD->isStatic()) { 8346 1.1 joerg VisitIgnoredBaseExpression(E->getBase()); 8347 1.1 joerg return Success(MD); 8348 1.1 joerg } 8349 1.1 joerg } 8350 1.1 joerg 8351 1.1 joerg // Handle non-static data members. 8352 1.1 joerg return LValueExprEvaluatorBaseTy::VisitMemberExpr(E); 8353 1.1 joerg } 8354 1.1 joerg 8355 1.1 joerg bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) { 8356 1.1 joerg // FIXME: Deal with vectors as array subscript bases. 8357 1.1 joerg if (E->getBase()->getType()->isVectorType()) 8358 1.1 joerg return Error(E); 8359 1.1 joerg 8360 1.1.1.2 joerg APSInt Index; 8361 1.1 joerg bool Success = true; 8362 1.1 joerg 8363 1.1.1.2 joerg // C++17's rules require us to evaluate the LHS first, regardless of which 8364 1.1.1.2 joerg // side is the base. 8365 1.1.1.2 joerg for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) { 8366 1.1.1.2 joerg if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result) 8367 1.1.1.2 joerg : !EvaluateInteger(SubExpr, Index, Info)) { 8368 1.1.1.2 joerg if (!Info.noteFailure()) 8369 1.1.1.2 joerg return false; 8370 1.1.1.2 joerg Success = false; 8371 1.1.1.2 joerg } 8372 1.1.1.2 joerg } 8373 1.1 joerg 8374 1.1 joerg return Success && 8375 1.1 joerg HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index); 8376 1.1 joerg } 8377 1.1 joerg 8378 1.1 joerg bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) { 8379 1.1 joerg return evaluatePointer(E->getSubExpr(), Result); 8380 1.1 joerg } 8381 1.1 joerg 8382 1.1 joerg bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 8383 1.1 joerg if (!Visit(E->getSubExpr())) 8384 1.1 joerg return false; 8385 1.1 joerg // __real is a no-op on scalar lvalues. 8386 1.1 joerg if (E->getSubExpr()->getType()->isAnyComplexType()) 8387 1.1 joerg HandleLValueComplexElement(Info, E, Result, E->getType(), false); 8388 1.1 joerg return true; 8389 1.1 joerg } 8390 1.1 joerg 8391 1.1 joerg bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 8392 1.1 joerg assert(E->getSubExpr()->getType()->isAnyComplexType() && 8393 1.1 joerg "lvalue __imag__ on scalar?"); 8394 1.1 joerg if (!Visit(E->getSubExpr())) 8395 1.1 joerg return false; 8396 1.1 joerg HandleLValueComplexElement(Info, E, Result, E->getType(), true); 8397 1.1 joerg return true; 8398 1.1 joerg } 8399 1.1 joerg 8400 1.1 joerg bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) { 8401 1.1 joerg if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 8402 1.1 joerg return Error(UO); 8403 1.1 joerg 8404 1.1 joerg if (!this->Visit(UO->getSubExpr())) 8405 1.1 joerg return false; 8406 1.1 joerg 8407 1.1 joerg return handleIncDec( 8408 1.1 joerg this->Info, UO, Result, UO->getSubExpr()->getType(), 8409 1.1 joerg UO->isIncrementOp(), nullptr); 8410 1.1 joerg } 8411 1.1 joerg 8412 1.1 joerg bool LValueExprEvaluator::VisitCompoundAssignOperator( 8413 1.1 joerg const CompoundAssignOperator *CAO) { 8414 1.1 joerg if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 8415 1.1 joerg return Error(CAO); 8416 1.1 joerg 8417 1.1.1.2 joerg bool Success = true; 8418 1.1 joerg 8419 1.1.1.2 joerg // C++17 onwards require that we evaluate the RHS first. 8420 1.1.1.2 joerg APValue RHS; 8421 1.1.1.2 joerg if (!Evaluate(RHS, this->Info, CAO->getRHS())) { 8422 1.1.1.2 joerg if (!Info.noteFailure()) 8423 1.1.1.2 joerg return false; 8424 1.1.1.2 joerg Success = false; 8425 1.1 joerg } 8426 1.1 joerg 8427 1.1.1.2 joerg // The overall lvalue result is the result of evaluating the LHS. 8428 1.1.1.2 joerg if (!this->Visit(CAO->getLHS()) || !Success) 8429 1.1 joerg return false; 8430 1.1 joerg 8431 1.1 joerg return handleCompoundAssignment( 8432 1.1 joerg this->Info, CAO, 8433 1.1 joerg Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(), 8434 1.1 joerg CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS); 8435 1.1 joerg } 8436 1.1 joerg 8437 1.1 joerg bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) { 8438 1.1 joerg if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 8439 1.1 joerg return Error(E); 8440 1.1 joerg 8441 1.1.1.2 joerg bool Success = true; 8442 1.1 joerg 8443 1.1.1.2 joerg // C++17 onwards require that we evaluate the RHS first. 8444 1.1.1.2 joerg APValue NewVal; 8445 1.1.1.2 joerg if (!Evaluate(NewVal, this->Info, E->getRHS())) { 8446 1.1.1.2 joerg if (!Info.noteFailure()) 8447 1.1.1.2 joerg return false; 8448 1.1.1.2 joerg Success = false; 8449 1.1 joerg } 8450 1.1 joerg 8451 1.1.1.2 joerg if (!this->Visit(E->getLHS()) || !Success) 8452 1.1 joerg return false; 8453 1.1 joerg 8454 1.1.1.2 joerg if (Info.getLangOpts().CPlusPlus20 && 8455 1.1 joerg !HandleUnionActiveMemberChange(Info, E->getLHS(), Result)) 8456 1.1 joerg return false; 8457 1.1 joerg 8458 1.1 joerg return handleAssignment(this->Info, E, Result, E->getLHS()->getType(), 8459 1.1 joerg NewVal); 8460 1.1 joerg } 8461 1.1 joerg 8462 1.1 joerg //===----------------------------------------------------------------------===// 8463 1.1 joerg // Pointer Evaluation 8464 1.1 joerg //===----------------------------------------------------------------------===// 8465 1.1 joerg 8466 1.1 joerg /// Attempts to compute the number of bytes available at the pointer 8467 1.1 joerg /// returned by a function with the alloc_size attribute. Returns true if we 8468 1.1 joerg /// were successful. Places an unsigned number into `Result`. 8469 1.1 joerg /// 8470 1.1 joerg /// This expects the given CallExpr to be a call to a function with an 8471 1.1 joerg /// alloc_size attribute. 8472 1.1 joerg static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, 8473 1.1 joerg const CallExpr *Call, 8474 1.1 joerg llvm::APInt &Result) { 8475 1.1 joerg const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call); 8476 1.1 joerg 8477 1.1 joerg assert(AllocSize && AllocSize->getElemSizeParam().isValid()); 8478 1.1 joerg unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex(); 8479 1.1 joerg unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType()); 8480 1.1 joerg if (Call->getNumArgs() <= SizeArgNo) 8481 1.1 joerg return false; 8482 1.1 joerg 8483 1.1 joerg auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) { 8484 1.1 joerg Expr::EvalResult ExprResult; 8485 1.1 joerg if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects)) 8486 1.1 joerg return false; 8487 1.1 joerg Into = ExprResult.Val.getInt(); 8488 1.1 joerg if (Into.isNegative() || !Into.isIntN(BitsInSizeT)) 8489 1.1 joerg return false; 8490 1.1 joerg Into = Into.zextOrSelf(BitsInSizeT); 8491 1.1 joerg return true; 8492 1.1 joerg }; 8493 1.1 joerg 8494 1.1 joerg APSInt SizeOfElem; 8495 1.1 joerg if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem)) 8496 1.1 joerg return false; 8497 1.1 joerg 8498 1.1 joerg if (!AllocSize->getNumElemsParam().isValid()) { 8499 1.1 joerg Result = std::move(SizeOfElem); 8500 1.1 joerg return true; 8501 1.1 joerg } 8502 1.1 joerg 8503 1.1 joerg APSInt NumberOfElems; 8504 1.1 joerg unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex(); 8505 1.1 joerg if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems)) 8506 1.1 joerg return false; 8507 1.1 joerg 8508 1.1 joerg bool Overflow; 8509 1.1 joerg llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow); 8510 1.1 joerg if (Overflow) 8511 1.1 joerg return false; 8512 1.1 joerg 8513 1.1 joerg Result = std::move(BytesAvailable); 8514 1.1 joerg return true; 8515 1.1 joerg } 8516 1.1 joerg 8517 1.1 joerg /// Convenience function. LVal's base must be a call to an alloc_size 8518 1.1 joerg /// function. 8519 1.1 joerg static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, 8520 1.1 joerg const LValue &LVal, 8521 1.1 joerg llvm::APInt &Result) { 8522 1.1 joerg assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) && 8523 1.1 joerg "Can't get the size of a non alloc_size function"); 8524 1.1 joerg const auto *Base = LVal.getLValueBase().get<const Expr *>(); 8525 1.1 joerg const CallExpr *CE = tryUnwrapAllocSizeCall(Base); 8526 1.1 joerg return getBytesReturnedByAllocSizeCall(Ctx, CE, Result); 8527 1.1 joerg } 8528 1.1 joerg 8529 1.1 joerg /// Attempts to evaluate the given LValueBase as the result of a call to 8530 1.1 joerg /// a function with the alloc_size attribute. If it was possible to do so, this 8531 1.1 joerg /// function will return true, make Result's Base point to said function call, 8532 1.1 joerg /// and mark Result's Base as invalid. 8533 1.1 joerg static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base, 8534 1.1 joerg LValue &Result) { 8535 1.1 joerg if (Base.isNull()) 8536 1.1 joerg return false; 8537 1.1 joerg 8538 1.1 joerg // Because we do no form of static analysis, we only support const variables. 8539 1.1 joerg // 8540 1.1 joerg // Additionally, we can't support parameters, nor can we support static 8541 1.1 joerg // variables (in the latter case, use-before-assign isn't UB; in the former, 8542 1.1 joerg // we have no clue what they'll be assigned to). 8543 1.1 joerg const auto *VD = 8544 1.1 joerg dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>()); 8545 1.1 joerg if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified()) 8546 1.1 joerg return false; 8547 1.1 joerg 8548 1.1 joerg const Expr *Init = VD->getAnyInitializer(); 8549 1.1 joerg if (!Init) 8550 1.1 joerg return false; 8551 1.1 joerg 8552 1.1 joerg const Expr *E = Init->IgnoreParens(); 8553 1.1 joerg if (!tryUnwrapAllocSizeCall(E)) 8554 1.1 joerg return false; 8555 1.1 joerg 8556 1.1 joerg // Store E instead of E unwrapped so that the type of the LValue's base is 8557 1.1 joerg // what the user wanted. 8558 1.1 joerg Result.setInvalid(E); 8559 1.1 joerg 8560 1.1 joerg QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType(); 8561 1.1 joerg Result.addUnsizedArray(Info, E, Pointee); 8562 1.1 joerg return true; 8563 1.1 joerg } 8564 1.1 joerg 8565 1.1 joerg namespace { 8566 1.1 joerg class PointerExprEvaluator 8567 1.1 joerg : public ExprEvaluatorBase<PointerExprEvaluator> { 8568 1.1 joerg LValue &Result; 8569 1.1 joerg bool InvalidBaseOK; 8570 1.1 joerg 8571 1.1 joerg bool Success(const Expr *E) { 8572 1.1 joerg Result.set(E); 8573 1.1 joerg return true; 8574 1.1 joerg } 8575 1.1 joerg 8576 1.1 joerg bool evaluateLValue(const Expr *E, LValue &Result) { 8577 1.1 joerg return EvaluateLValue(E, Result, Info, InvalidBaseOK); 8578 1.1 joerg } 8579 1.1 joerg 8580 1.1 joerg bool evaluatePointer(const Expr *E, LValue &Result) { 8581 1.1 joerg return EvaluatePointer(E, Result, Info, InvalidBaseOK); 8582 1.1 joerg } 8583 1.1 joerg 8584 1.1 joerg bool visitNonBuiltinCallExpr(const CallExpr *E); 8585 1.1 joerg public: 8586 1.1 joerg 8587 1.1 joerg PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK) 8588 1.1 joerg : ExprEvaluatorBaseTy(info), Result(Result), 8589 1.1 joerg InvalidBaseOK(InvalidBaseOK) {} 8590 1.1 joerg 8591 1.1 joerg bool Success(const APValue &V, const Expr *E) { 8592 1.1 joerg Result.setFrom(Info.Ctx, V); 8593 1.1 joerg return true; 8594 1.1 joerg } 8595 1.1 joerg bool ZeroInitialization(const Expr *E) { 8596 1.1 joerg Result.setNull(Info.Ctx, E->getType()); 8597 1.1 joerg return true; 8598 1.1 joerg } 8599 1.1 joerg 8600 1.1 joerg bool VisitBinaryOperator(const BinaryOperator *E); 8601 1.1 joerg bool VisitCastExpr(const CastExpr* E); 8602 1.1 joerg bool VisitUnaryAddrOf(const UnaryOperator *E); 8603 1.1 joerg bool VisitObjCStringLiteral(const ObjCStringLiteral *E) 8604 1.1 joerg { return Success(E); } 8605 1.1 joerg bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) { 8606 1.1 joerg if (E->isExpressibleAsConstantInitializer()) 8607 1.1 joerg return Success(E); 8608 1.1 joerg if (Info.noteFailure()) 8609 1.1 joerg EvaluateIgnoredValue(Info, E->getSubExpr()); 8610 1.1 joerg return Error(E); 8611 1.1 joerg } 8612 1.1 joerg bool VisitAddrLabelExpr(const AddrLabelExpr *E) 8613 1.1 joerg { return Success(E); } 8614 1.1 joerg bool VisitCallExpr(const CallExpr *E); 8615 1.1 joerg bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); 8616 1.1 joerg bool VisitBlockExpr(const BlockExpr *E) { 8617 1.1 joerg if (!E->getBlockDecl()->hasCaptures()) 8618 1.1 joerg return Success(E); 8619 1.1 joerg return Error(E); 8620 1.1 joerg } 8621 1.1 joerg bool VisitCXXThisExpr(const CXXThisExpr *E) { 8622 1.1 joerg // Can't look at 'this' when checking a potential constant expression. 8623 1.1 joerg if (Info.checkingPotentialConstantExpression()) 8624 1.1 joerg return false; 8625 1.1 joerg if (!Info.CurrentCall->This) { 8626 1.1 joerg if (Info.getLangOpts().CPlusPlus11) 8627 1.1 joerg Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit(); 8628 1.1 joerg else 8629 1.1 joerg Info.FFDiag(E); 8630 1.1 joerg return false; 8631 1.1 joerg } 8632 1.1 joerg Result = *Info.CurrentCall->This; 8633 1.1 joerg // If we are inside a lambda's call operator, the 'this' expression refers 8634 1.1 joerg // to the enclosing '*this' object (either by value or reference) which is 8635 1.1 joerg // either copied into the closure object's field that represents the '*this' 8636 1.1 joerg // or refers to '*this'. 8637 1.1 joerg if (isLambdaCallOperator(Info.CurrentCall->Callee)) { 8638 1.1.1.2 joerg // Ensure we actually have captured 'this'. (an error will have 8639 1.1.1.2 joerg // been previously reported if not). 8640 1.1.1.2 joerg if (!Info.CurrentCall->LambdaThisCaptureField) 8641 1.1.1.2 joerg return false; 8642 1.1.1.2 joerg 8643 1.1 joerg // Update 'Result' to refer to the data member/field of the closure object 8644 1.1 joerg // that represents the '*this' capture. 8645 1.1 joerg if (!HandleLValueMember(Info, E, Result, 8646 1.1 joerg Info.CurrentCall->LambdaThisCaptureField)) 8647 1.1 joerg return false; 8648 1.1 joerg // If we captured '*this' by reference, replace the field with its referent. 8649 1.1 joerg if (Info.CurrentCall->LambdaThisCaptureField->getType() 8650 1.1 joerg ->isPointerType()) { 8651 1.1 joerg APValue RVal; 8652 1.1 joerg if (!handleLValueToRValueConversion(Info, E, E->getType(), Result, 8653 1.1 joerg RVal)) 8654 1.1 joerg return false; 8655 1.1 joerg 8656 1.1 joerg Result.setFrom(Info.Ctx, RVal); 8657 1.1 joerg } 8658 1.1 joerg } 8659 1.1 joerg return true; 8660 1.1 joerg } 8661 1.1 joerg 8662 1.1 joerg bool VisitCXXNewExpr(const CXXNewExpr *E); 8663 1.1 joerg 8664 1.1 joerg bool VisitSourceLocExpr(const SourceLocExpr *E) { 8665 1.1 joerg assert(E->isStringType() && "SourceLocExpr isn't a pointer type?"); 8666 1.1 joerg APValue LValResult = E->EvaluateInContext( 8667 1.1 joerg Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr()); 8668 1.1 joerg Result.setFrom(Info.Ctx, LValResult); 8669 1.1 joerg return true; 8670 1.1 joerg } 8671 1.1 joerg 8672 1.1 joerg // FIXME: Missing: @protocol, @selector 8673 1.1 joerg }; 8674 1.1 joerg } // end anonymous namespace 8675 1.1 joerg 8676 1.1 joerg static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info, 8677 1.1 joerg bool InvalidBaseOK) { 8678 1.1.1.2 joerg assert(!E->isValueDependent()); 8679 1.1 joerg assert(E->isRValue() && E->getType()->hasPointerRepresentation()); 8680 1.1 joerg return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); 8681 1.1 joerg } 8682 1.1 joerg 8683 1.1 joerg bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 8684 1.1 joerg if (E->getOpcode() != BO_Add && 8685 1.1 joerg E->getOpcode() != BO_Sub) 8686 1.1 joerg return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 8687 1.1 joerg 8688 1.1 joerg const Expr *PExp = E->getLHS(); 8689 1.1 joerg const Expr *IExp = E->getRHS(); 8690 1.1 joerg if (IExp->getType()->isPointerType()) 8691 1.1 joerg std::swap(PExp, IExp); 8692 1.1 joerg 8693 1.1 joerg bool EvalPtrOK = evaluatePointer(PExp, Result); 8694 1.1 joerg if (!EvalPtrOK && !Info.noteFailure()) 8695 1.1 joerg return false; 8696 1.1 joerg 8697 1.1 joerg llvm::APSInt Offset; 8698 1.1 joerg if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK) 8699 1.1 joerg return false; 8700 1.1 joerg 8701 1.1 joerg if (E->getOpcode() == BO_Sub) 8702 1.1 joerg negateAsSigned(Offset); 8703 1.1 joerg 8704 1.1 joerg QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType(); 8705 1.1 joerg return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset); 8706 1.1 joerg } 8707 1.1 joerg 8708 1.1 joerg bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 8709 1.1 joerg return evaluateLValue(E->getSubExpr(), Result); 8710 1.1 joerg } 8711 1.1 joerg 8712 1.1 joerg bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) { 8713 1.1 joerg const Expr *SubExpr = E->getSubExpr(); 8714 1.1 joerg 8715 1.1 joerg switch (E->getCastKind()) { 8716 1.1 joerg default: 8717 1.1 joerg break; 8718 1.1 joerg case CK_BitCast: 8719 1.1 joerg case CK_CPointerToObjCPointerCast: 8720 1.1 joerg case CK_BlockPointerToObjCPointerCast: 8721 1.1 joerg case CK_AnyPointerToBlockPointerCast: 8722 1.1 joerg case CK_AddressSpaceConversion: 8723 1.1 joerg if (!Visit(SubExpr)) 8724 1.1 joerg return false; 8725 1.1 joerg // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are 8726 1.1 joerg // permitted in constant expressions in C++11. Bitcasts from cv void* are 8727 1.1 joerg // also static_casts, but we disallow them as a resolution to DR1312. 8728 1.1 joerg if (!E->getType()->isVoidPointerType()) { 8729 1.1 joerg if (!Result.InvalidBase && !Result.Designator.Invalid && 8730 1.1 joerg !Result.IsNullPtr && 8731 1.1 joerg Info.Ctx.hasSameUnqualifiedType(Result.Designator.getType(Info.Ctx), 8732 1.1 joerg E->getType()->getPointeeType()) && 8733 1.1 joerg Info.getStdAllocatorCaller("allocate")) { 8734 1.1 joerg // Inside a call to std::allocator::allocate and friends, we permit 8735 1.1 joerg // casting from void* back to cv1 T* for a pointer that points to a 8736 1.1 joerg // cv2 T. 8737 1.1 joerg } else { 8738 1.1 joerg Result.Designator.setInvalid(); 8739 1.1 joerg if (SubExpr->getType()->isVoidPointerType()) 8740 1.1 joerg CCEDiag(E, diag::note_constexpr_invalid_cast) 8741 1.1 joerg << 3 << SubExpr->getType(); 8742 1.1 joerg else 8743 1.1 joerg CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 8744 1.1 joerg } 8745 1.1 joerg } 8746 1.1 joerg if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr) 8747 1.1 joerg ZeroInitialization(E); 8748 1.1 joerg return true; 8749 1.1 joerg 8750 1.1 joerg case CK_DerivedToBase: 8751 1.1 joerg case CK_UncheckedDerivedToBase: 8752 1.1 joerg if (!evaluatePointer(E->getSubExpr(), Result)) 8753 1.1 joerg return false; 8754 1.1 joerg if (!Result.Base && Result.Offset.isZero()) 8755 1.1 joerg return true; 8756 1.1 joerg 8757 1.1 joerg // Now figure out the necessary offset to add to the base LV to get from 8758 1.1 joerg // the derived class to the base class. 8759 1.1 joerg return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()-> 8760 1.1 joerg castAs<PointerType>()->getPointeeType(), 8761 1.1 joerg Result); 8762 1.1 joerg 8763 1.1 joerg case CK_BaseToDerived: 8764 1.1 joerg if (!Visit(E->getSubExpr())) 8765 1.1 joerg return false; 8766 1.1 joerg if (!Result.Base && Result.Offset.isZero()) 8767 1.1 joerg return true; 8768 1.1 joerg return HandleBaseToDerivedCast(Info, E, Result); 8769 1.1 joerg 8770 1.1 joerg case CK_Dynamic: 8771 1.1 joerg if (!Visit(E->getSubExpr())) 8772 1.1 joerg return false; 8773 1.1 joerg return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result); 8774 1.1 joerg 8775 1.1 joerg case CK_NullToPointer: 8776 1.1 joerg VisitIgnoredValue(E->getSubExpr()); 8777 1.1 joerg return ZeroInitialization(E); 8778 1.1 joerg 8779 1.1 joerg case CK_IntegralToPointer: { 8780 1.1 joerg CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 8781 1.1 joerg 8782 1.1 joerg APValue Value; 8783 1.1 joerg if (!EvaluateIntegerOrLValue(SubExpr, Value, Info)) 8784 1.1 joerg break; 8785 1.1 joerg 8786 1.1 joerg if (Value.isInt()) { 8787 1.1 joerg unsigned Size = Info.Ctx.getTypeSize(E->getType()); 8788 1.1 joerg uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue(); 8789 1.1 joerg Result.Base = (Expr*)nullptr; 8790 1.1 joerg Result.InvalidBase = false; 8791 1.1 joerg Result.Offset = CharUnits::fromQuantity(N); 8792 1.1 joerg Result.Designator.setInvalid(); 8793 1.1 joerg Result.IsNullPtr = false; 8794 1.1 joerg return true; 8795 1.1 joerg } else { 8796 1.1 joerg // Cast is of an lvalue, no need to change value. 8797 1.1 joerg Result.setFrom(Info.Ctx, Value); 8798 1.1 joerg return true; 8799 1.1 joerg } 8800 1.1 joerg } 8801 1.1 joerg 8802 1.1 joerg case CK_ArrayToPointerDecay: { 8803 1.1 joerg if (SubExpr->isGLValue()) { 8804 1.1 joerg if (!evaluateLValue(SubExpr, Result)) 8805 1.1 joerg return false; 8806 1.1 joerg } else { 8807 1.1 joerg APValue &Value = Info.CurrentCall->createTemporary( 8808 1.1.1.2 joerg SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result); 8809 1.1 joerg if (!EvaluateInPlace(Value, Info, Result, SubExpr)) 8810 1.1 joerg return false; 8811 1.1 joerg } 8812 1.1 joerg // The result is a pointer to the first element of the array. 8813 1.1 joerg auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType()); 8814 1.1 joerg if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) 8815 1.1 joerg Result.addArray(Info, E, CAT); 8816 1.1 joerg else 8817 1.1 joerg Result.addUnsizedArray(Info, E, AT->getElementType()); 8818 1.1 joerg return true; 8819 1.1 joerg } 8820 1.1 joerg 8821 1.1 joerg case CK_FunctionToPointerDecay: 8822 1.1 joerg return evaluateLValue(SubExpr, Result); 8823 1.1 joerg 8824 1.1 joerg case CK_LValueToRValue: { 8825 1.1 joerg LValue LVal; 8826 1.1 joerg if (!evaluateLValue(E->getSubExpr(), LVal)) 8827 1.1 joerg return false; 8828 1.1 joerg 8829 1.1 joerg APValue RVal; 8830 1.1 joerg // Note, we use the subexpression's type in order to retain cv-qualifiers. 8831 1.1 joerg if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 8832 1.1 joerg LVal, RVal)) 8833 1.1 joerg return InvalidBaseOK && 8834 1.1 joerg evaluateLValueAsAllocSize(Info, LVal.Base, Result); 8835 1.1 joerg return Success(RVal, E); 8836 1.1 joerg } 8837 1.1 joerg } 8838 1.1 joerg 8839 1.1 joerg return ExprEvaluatorBaseTy::VisitCastExpr(E); 8840 1.1 joerg } 8841 1.1 joerg 8842 1.1 joerg static CharUnits GetAlignOfType(EvalInfo &Info, QualType T, 8843 1.1 joerg UnaryExprOrTypeTrait ExprKind) { 8844 1.1 joerg // C++ [expr.alignof]p3: 8845 1.1 joerg // When alignof is applied to a reference type, the result is the 8846 1.1 joerg // alignment of the referenced type. 8847 1.1 joerg if (const ReferenceType *Ref = T->getAs<ReferenceType>()) 8848 1.1 joerg T = Ref->getPointeeType(); 8849 1.1 joerg 8850 1.1 joerg if (T.getQualifiers().hasUnaligned()) 8851 1.1 joerg return CharUnits::One(); 8852 1.1 joerg 8853 1.1 joerg const bool AlignOfReturnsPreferred = 8854 1.1 joerg Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7; 8855 1.1 joerg 8856 1.1 joerg // __alignof is defined to return the preferred alignment. 8857 1.1 joerg // Before 8, clang returned the preferred alignment for alignof and _Alignof 8858 1.1 joerg // as well. 8859 1.1 joerg if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred) 8860 1.1 joerg return Info.Ctx.toCharUnitsFromBits( 8861 1.1 joerg Info.Ctx.getPreferredTypeAlign(T.getTypePtr())); 8862 1.1 joerg // alignof and _Alignof are defined to return the ABI alignment. 8863 1.1 joerg else if (ExprKind == UETT_AlignOf) 8864 1.1 joerg return Info.Ctx.getTypeAlignInChars(T.getTypePtr()); 8865 1.1 joerg else 8866 1.1 joerg llvm_unreachable("GetAlignOfType on a non-alignment ExprKind"); 8867 1.1 joerg } 8868 1.1 joerg 8869 1.1 joerg static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E, 8870 1.1 joerg UnaryExprOrTypeTrait ExprKind) { 8871 1.1 joerg E = E->IgnoreParens(); 8872 1.1 joerg 8873 1.1 joerg // The kinds of expressions that we have special-case logic here for 8874 1.1 joerg // should be kept up to date with the special checks for those 8875 1.1 joerg // expressions in Sema. 8876 1.1 joerg 8877 1.1 joerg // alignof decl is always accepted, even if it doesn't make sense: we default 8878 1.1 joerg // to 1 in those cases. 8879 1.1 joerg if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 8880 1.1 joerg return Info.Ctx.getDeclAlign(DRE->getDecl(), 8881 1.1 joerg /*RefAsPointee*/true); 8882 1.1 joerg 8883 1.1 joerg if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 8884 1.1 joerg return Info.Ctx.getDeclAlign(ME->getMemberDecl(), 8885 1.1 joerg /*RefAsPointee*/true); 8886 1.1 joerg 8887 1.1 joerg return GetAlignOfType(Info, E->getType(), ExprKind); 8888 1.1 joerg } 8889 1.1 joerg 8890 1.1.1.2 joerg static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) { 8891 1.1.1.2 joerg if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>()) 8892 1.1.1.2 joerg return Info.Ctx.getDeclAlign(VD); 8893 1.1.1.2 joerg if (const auto *E = Value.Base.dyn_cast<const Expr *>()) 8894 1.1.1.2 joerg return GetAlignOfExpr(Info, E, UETT_AlignOf); 8895 1.1.1.2 joerg return GetAlignOfType(Info, Value.Base.getTypeInfoType(), UETT_AlignOf); 8896 1.1.1.2 joerg } 8897 1.1.1.2 joerg 8898 1.1.1.2 joerg /// Evaluate the value of the alignment argument to __builtin_align_{up,down}, 8899 1.1.1.2 joerg /// __builtin_is_aligned and __builtin_assume_aligned. 8900 1.1.1.2 joerg static bool getAlignmentArgument(const Expr *E, QualType ForType, 8901 1.1.1.2 joerg EvalInfo &Info, APSInt &Alignment) { 8902 1.1.1.2 joerg if (!EvaluateInteger(E, Alignment, Info)) 8903 1.1.1.2 joerg return false; 8904 1.1.1.2 joerg if (Alignment < 0 || !Alignment.isPowerOf2()) { 8905 1.1.1.2 joerg Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment; 8906 1.1.1.2 joerg return false; 8907 1.1.1.2 joerg } 8908 1.1.1.2 joerg unsigned SrcWidth = Info.Ctx.getIntWidth(ForType); 8909 1.1.1.2 joerg APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1)); 8910 1.1.1.2 joerg if (APSInt::compareValues(Alignment, MaxValue) > 0) { 8911 1.1.1.2 joerg Info.FFDiag(E, diag::note_constexpr_alignment_too_big) 8912 1.1.1.2 joerg << MaxValue << ForType << Alignment; 8913 1.1.1.2 joerg return false; 8914 1.1.1.2 joerg } 8915 1.1.1.2 joerg // Ensure both alignment and source value have the same bit width so that we 8916 1.1.1.2 joerg // don't assert when computing the resulting value. 8917 1.1.1.2 joerg APSInt ExtAlignment = 8918 1.1.1.2 joerg APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true); 8919 1.1.1.2 joerg assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 && 8920 1.1.1.2 joerg "Alignment should not be changed by ext/trunc"); 8921 1.1.1.2 joerg Alignment = ExtAlignment; 8922 1.1.1.2 joerg assert(Alignment.getBitWidth() == SrcWidth); 8923 1.1.1.2 joerg return true; 8924 1.1.1.2 joerg } 8925 1.1.1.2 joerg 8926 1.1 joerg // To be clear: this happily visits unsupported builtins. Better name welcomed. 8927 1.1 joerg bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) { 8928 1.1 joerg if (ExprEvaluatorBaseTy::VisitCallExpr(E)) 8929 1.1 joerg return true; 8930 1.1 joerg 8931 1.1 joerg if (!(InvalidBaseOK && getAllocSizeAttr(E))) 8932 1.1 joerg return false; 8933 1.1 joerg 8934 1.1 joerg Result.setInvalid(E); 8935 1.1 joerg QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType(); 8936 1.1 joerg Result.addUnsizedArray(Info, E, PointeeTy); 8937 1.1 joerg return true; 8938 1.1 joerg } 8939 1.1 joerg 8940 1.1 joerg bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) { 8941 1.1 joerg if (IsStringLiteralCall(E)) 8942 1.1 joerg return Success(E); 8943 1.1 joerg 8944 1.1 joerg if (unsigned BuiltinOp = E->getBuiltinCallee()) 8945 1.1 joerg return VisitBuiltinCallExpr(E, BuiltinOp); 8946 1.1 joerg 8947 1.1 joerg return visitNonBuiltinCallExpr(E); 8948 1.1 joerg } 8949 1.1 joerg 8950 1.1.1.2 joerg // Determine if T is a character type for which we guarantee that 8951 1.1.1.2 joerg // sizeof(T) == 1. 8952 1.1.1.2 joerg static bool isOneByteCharacterType(QualType T) { 8953 1.1.1.2 joerg return T->isCharType() || T->isChar8Type(); 8954 1.1.1.2 joerg } 8955 1.1.1.2 joerg 8956 1.1 joerg bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, 8957 1.1 joerg unsigned BuiltinOp) { 8958 1.1 joerg switch (BuiltinOp) { 8959 1.1 joerg case Builtin::BI__builtin_addressof: 8960 1.1 joerg return evaluateLValue(E->getArg(0), Result); 8961 1.1 joerg case Builtin::BI__builtin_assume_aligned: { 8962 1.1 joerg // We need to be very careful here because: if the pointer does not have the 8963 1.1 joerg // asserted alignment, then the behavior is undefined, and undefined 8964 1.1 joerg // behavior is non-constant. 8965 1.1 joerg if (!evaluatePointer(E->getArg(0), Result)) 8966 1.1 joerg return false; 8967 1.1 joerg 8968 1.1 joerg LValue OffsetResult(Result); 8969 1.1 joerg APSInt Alignment; 8970 1.1.1.2 joerg if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info, 8971 1.1.1.2 joerg Alignment)) 8972 1.1 joerg return false; 8973 1.1 joerg CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue()); 8974 1.1 joerg 8975 1.1 joerg if (E->getNumArgs() > 2) { 8976 1.1 joerg APSInt Offset; 8977 1.1 joerg if (!EvaluateInteger(E->getArg(2), Offset, Info)) 8978 1.1 joerg return false; 8979 1.1 joerg 8980 1.1 joerg int64_t AdditionalOffset = -Offset.getZExtValue(); 8981 1.1 joerg OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset); 8982 1.1 joerg } 8983 1.1 joerg 8984 1.1 joerg // If there is a base object, then it must have the correct alignment. 8985 1.1 joerg if (OffsetResult.Base) { 8986 1.1.1.2 joerg CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult); 8987 1.1 joerg 8988 1.1 joerg if (BaseAlignment < Align) { 8989 1.1 joerg Result.Designator.setInvalid(); 8990 1.1 joerg // FIXME: Add support to Diagnostic for long / long long. 8991 1.1 joerg CCEDiag(E->getArg(0), 8992 1.1 joerg diag::note_constexpr_baa_insufficient_alignment) << 0 8993 1.1 joerg << (unsigned)BaseAlignment.getQuantity() 8994 1.1 joerg << (unsigned)Align.getQuantity(); 8995 1.1 joerg return false; 8996 1.1 joerg } 8997 1.1 joerg } 8998 1.1 joerg 8999 1.1 joerg // The offset must also have the correct alignment. 9000 1.1 joerg if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) { 9001 1.1 joerg Result.Designator.setInvalid(); 9002 1.1 joerg 9003 1.1 joerg (OffsetResult.Base 9004 1.1 joerg ? CCEDiag(E->getArg(0), 9005 1.1 joerg diag::note_constexpr_baa_insufficient_alignment) << 1 9006 1.1 joerg : CCEDiag(E->getArg(0), 9007 1.1 joerg diag::note_constexpr_baa_value_insufficient_alignment)) 9008 1.1 joerg << (int)OffsetResult.Offset.getQuantity() 9009 1.1 joerg << (unsigned)Align.getQuantity(); 9010 1.1 joerg return false; 9011 1.1 joerg } 9012 1.1 joerg 9013 1.1 joerg return true; 9014 1.1 joerg } 9015 1.1.1.2 joerg case Builtin::BI__builtin_align_up: 9016 1.1.1.2 joerg case Builtin::BI__builtin_align_down: { 9017 1.1.1.2 joerg if (!evaluatePointer(E->getArg(0), Result)) 9018 1.1.1.2 joerg return false; 9019 1.1.1.2 joerg APSInt Alignment; 9020 1.1.1.2 joerg if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info, 9021 1.1.1.2 joerg Alignment)) 9022 1.1.1.2 joerg return false; 9023 1.1.1.2 joerg CharUnits BaseAlignment = getBaseAlignment(Info, Result); 9024 1.1.1.2 joerg CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset); 9025 1.1.1.2 joerg // For align_up/align_down, we can return the same value if the alignment 9026 1.1.1.2 joerg // is known to be greater or equal to the requested value. 9027 1.1.1.2 joerg if (PtrAlign.getQuantity() >= Alignment) 9028 1.1.1.2 joerg return true; 9029 1.1.1.2 joerg 9030 1.1.1.2 joerg // The alignment could be greater than the minimum at run-time, so we cannot 9031 1.1.1.2 joerg // infer much about the resulting pointer value. One case is possible: 9032 1.1.1.2 joerg // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we 9033 1.1.1.2 joerg // can infer the correct index if the requested alignment is smaller than 9034 1.1.1.2 joerg // the base alignment so we can perform the computation on the offset. 9035 1.1.1.2 joerg if (BaseAlignment.getQuantity() >= Alignment) { 9036 1.1.1.2 joerg assert(Alignment.getBitWidth() <= 64 && 9037 1.1.1.2 joerg "Cannot handle > 64-bit address-space"); 9038 1.1.1.2 joerg uint64_t Alignment64 = Alignment.getZExtValue(); 9039 1.1.1.2 joerg CharUnits NewOffset = CharUnits::fromQuantity( 9040 1.1.1.2 joerg BuiltinOp == Builtin::BI__builtin_align_down 9041 1.1.1.2 joerg ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64) 9042 1.1.1.2 joerg : llvm::alignTo(Result.Offset.getQuantity(), Alignment64)); 9043 1.1.1.2 joerg Result.adjustOffset(NewOffset - Result.Offset); 9044 1.1.1.2 joerg // TODO: diagnose out-of-bounds values/only allow for arrays? 9045 1.1.1.2 joerg return true; 9046 1.1.1.2 joerg } 9047 1.1.1.2 joerg // Otherwise, we cannot constant-evaluate the result. 9048 1.1.1.2 joerg Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust) 9049 1.1.1.2 joerg << Alignment; 9050 1.1.1.2 joerg return false; 9051 1.1.1.2 joerg } 9052 1.1 joerg case Builtin::BI__builtin_operator_new: 9053 1.1 joerg return HandleOperatorNewCall(Info, E, Result); 9054 1.1 joerg case Builtin::BI__builtin_launder: 9055 1.1 joerg return evaluatePointer(E->getArg(0), Result); 9056 1.1 joerg case Builtin::BIstrchr: 9057 1.1 joerg case Builtin::BIwcschr: 9058 1.1 joerg case Builtin::BImemchr: 9059 1.1 joerg case Builtin::BIwmemchr: 9060 1.1 joerg if (Info.getLangOpts().CPlusPlus11) 9061 1.1 joerg Info.CCEDiag(E, diag::note_constexpr_invalid_function) 9062 1.1 joerg << /*isConstexpr*/0 << /*isConstructor*/0 9063 1.1 joerg << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 9064 1.1 joerg else 9065 1.1 joerg Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 9066 1.1 joerg LLVM_FALLTHROUGH; 9067 1.1 joerg case Builtin::BI__builtin_strchr: 9068 1.1 joerg case Builtin::BI__builtin_wcschr: 9069 1.1 joerg case Builtin::BI__builtin_memchr: 9070 1.1 joerg case Builtin::BI__builtin_char_memchr: 9071 1.1 joerg case Builtin::BI__builtin_wmemchr: { 9072 1.1 joerg if (!Visit(E->getArg(0))) 9073 1.1 joerg return false; 9074 1.1 joerg APSInt Desired; 9075 1.1 joerg if (!EvaluateInteger(E->getArg(1), Desired, Info)) 9076 1.1 joerg return false; 9077 1.1 joerg uint64_t MaxLength = uint64_t(-1); 9078 1.1 joerg if (BuiltinOp != Builtin::BIstrchr && 9079 1.1 joerg BuiltinOp != Builtin::BIwcschr && 9080 1.1 joerg BuiltinOp != Builtin::BI__builtin_strchr && 9081 1.1 joerg BuiltinOp != Builtin::BI__builtin_wcschr) { 9082 1.1 joerg APSInt N; 9083 1.1 joerg if (!EvaluateInteger(E->getArg(2), N, Info)) 9084 1.1 joerg return false; 9085 1.1 joerg MaxLength = N.getExtValue(); 9086 1.1 joerg } 9087 1.1 joerg // We cannot find the value if there are no candidates to match against. 9088 1.1 joerg if (MaxLength == 0u) 9089 1.1 joerg return ZeroInitialization(E); 9090 1.1 joerg if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) || 9091 1.1 joerg Result.Designator.Invalid) 9092 1.1 joerg return false; 9093 1.1 joerg QualType CharTy = Result.Designator.getType(Info.Ctx); 9094 1.1 joerg bool IsRawByte = BuiltinOp == Builtin::BImemchr || 9095 1.1 joerg BuiltinOp == Builtin::BI__builtin_memchr; 9096 1.1 joerg assert(IsRawByte || 9097 1.1 joerg Info.Ctx.hasSameUnqualifiedType( 9098 1.1 joerg CharTy, E->getArg(0)->getType()->getPointeeType())); 9099 1.1 joerg // Pointers to const void may point to objects of incomplete type. 9100 1.1 joerg if (IsRawByte && CharTy->isIncompleteType()) { 9101 1.1 joerg Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy; 9102 1.1 joerg return false; 9103 1.1 joerg } 9104 1.1 joerg // Give up on byte-oriented matching against multibyte elements. 9105 1.1 joerg // FIXME: We can compare the bytes in the correct order. 9106 1.1.1.2 joerg if (IsRawByte && !isOneByteCharacterType(CharTy)) { 9107 1.1.1.2 joerg Info.FFDiag(E, diag::note_constexpr_memchr_unsupported) 9108 1.1.1.2 joerg << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'") 9109 1.1.1.2 joerg << CharTy; 9110 1.1 joerg return false; 9111 1.1.1.2 joerg } 9112 1.1 joerg // Figure out what value we're actually looking for (after converting to 9113 1.1 joerg // the corresponding unsigned type if necessary). 9114 1.1 joerg uint64_t DesiredVal; 9115 1.1 joerg bool StopAtNull = false; 9116 1.1 joerg switch (BuiltinOp) { 9117 1.1 joerg case Builtin::BIstrchr: 9118 1.1 joerg case Builtin::BI__builtin_strchr: 9119 1.1 joerg // strchr compares directly to the passed integer, and therefore 9120 1.1 joerg // always fails if given an int that is not a char. 9121 1.1 joerg if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy, 9122 1.1 joerg E->getArg(1)->getType(), 9123 1.1 joerg Desired), 9124 1.1 joerg Desired)) 9125 1.1 joerg return ZeroInitialization(E); 9126 1.1 joerg StopAtNull = true; 9127 1.1 joerg LLVM_FALLTHROUGH; 9128 1.1 joerg case Builtin::BImemchr: 9129 1.1 joerg case Builtin::BI__builtin_memchr: 9130 1.1 joerg case Builtin::BI__builtin_char_memchr: 9131 1.1 joerg // memchr compares by converting both sides to unsigned char. That's also 9132 1.1 joerg // correct for strchr if we get this far (to cope with plain char being 9133 1.1 joerg // unsigned in the strchr case). 9134 1.1 joerg DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue(); 9135 1.1 joerg break; 9136 1.1 joerg 9137 1.1 joerg case Builtin::BIwcschr: 9138 1.1 joerg case Builtin::BI__builtin_wcschr: 9139 1.1 joerg StopAtNull = true; 9140 1.1 joerg LLVM_FALLTHROUGH; 9141 1.1 joerg case Builtin::BIwmemchr: 9142 1.1 joerg case Builtin::BI__builtin_wmemchr: 9143 1.1 joerg // wcschr and wmemchr are given a wchar_t to look for. Just use it. 9144 1.1 joerg DesiredVal = Desired.getZExtValue(); 9145 1.1 joerg break; 9146 1.1 joerg } 9147 1.1 joerg 9148 1.1 joerg for (; MaxLength; --MaxLength) { 9149 1.1 joerg APValue Char; 9150 1.1 joerg if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) || 9151 1.1 joerg !Char.isInt()) 9152 1.1 joerg return false; 9153 1.1 joerg if (Char.getInt().getZExtValue() == DesiredVal) 9154 1.1 joerg return true; 9155 1.1 joerg if (StopAtNull && !Char.getInt()) 9156 1.1 joerg break; 9157 1.1 joerg if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1)) 9158 1.1 joerg return false; 9159 1.1 joerg } 9160 1.1 joerg // Not found: return nullptr. 9161 1.1 joerg return ZeroInitialization(E); 9162 1.1 joerg } 9163 1.1 joerg 9164 1.1 joerg case Builtin::BImemcpy: 9165 1.1 joerg case Builtin::BImemmove: 9166 1.1 joerg case Builtin::BIwmemcpy: 9167 1.1 joerg case Builtin::BIwmemmove: 9168 1.1 joerg if (Info.getLangOpts().CPlusPlus11) 9169 1.1 joerg Info.CCEDiag(E, diag::note_constexpr_invalid_function) 9170 1.1 joerg << /*isConstexpr*/0 << /*isConstructor*/0 9171 1.1 joerg << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 9172 1.1 joerg else 9173 1.1 joerg Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 9174 1.1 joerg LLVM_FALLTHROUGH; 9175 1.1 joerg case Builtin::BI__builtin_memcpy: 9176 1.1 joerg case Builtin::BI__builtin_memmove: 9177 1.1 joerg case Builtin::BI__builtin_wmemcpy: 9178 1.1 joerg case Builtin::BI__builtin_wmemmove: { 9179 1.1 joerg bool WChar = BuiltinOp == Builtin::BIwmemcpy || 9180 1.1 joerg BuiltinOp == Builtin::BIwmemmove || 9181 1.1 joerg BuiltinOp == Builtin::BI__builtin_wmemcpy || 9182 1.1 joerg BuiltinOp == Builtin::BI__builtin_wmemmove; 9183 1.1 joerg bool Move = BuiltinOp == Builtin::BImemmove || 9184 1.1 joerg BuiltinOp == Builtin::BIwmemmove || 9185 1.1 joerg BuiltinOp == Builtin::BI__builtin_memmove || 9186 1.1 joerg BuiltinOp == Builtin::BI__builtin_wmemmove; 9187 1.1 joerg 9188 1.1 joerg // The result of mem* is the first argument. 9189 1.1 joerg if (!Visit(E->getArg(0))) 9190 1.1 joerg return false; 9191 1.1 joerg LValue Dest = Result; 9192 1.1 joerg 9193 1.1 joerg LValue Src; 9194 1.1 joerg if (!EvaluatePointer(E->getArg(1), Src, Info)) 9195 1.1 joerg return false; 9196 1.1 joerg 9197 1.1 joerg APSInt N; 9198 1.1 joerg if (!EvaluateInteger(E->getArg(2), N, Info)) 9199 1.1 joerg return false; 9200 1.1 joerg assert(!N.isSigned() && "memcpy and friends take an unsigned size"); 9201 1.1 joerg 9202 1.1 joerg // If the size is zero, we treat this as always being a valid no-op. 9203 1.1 joerg // (Even if one of the src and dest pointers is null.) 9204 1.1 joerg if (!N) 9205 1.1 joerg return true; 9206 1.1 joerg 9207 1.1 joerg // Otherwise, if either of the operands is null, we can't proceed. Don't 9208 1.1 joerg // try to determine the type of the copied objects, because there aren't 9209 1.1 joerg // any. 9210 1.1 joerg if (!Src.Base || !Dest.Base) { 9211 1.1 joerg APValue Val; 9212 1.1 joerg (!Src.Base ? Src : Dest).moveInto(Val); 9213 1.1 joerg Info.FFDiag(E, diag::note_constexpr_memcpy_null) 9214 1.1 joerg << Move << WChar << !!Src.Base 9215 1.1 joerg << Val.getAsString(Info.Ctx, E->getArg(0)->getType()); 9216 1.1 joerg return false; 9217 1.1 joerg } 9218 1.1 joerg if (Src.Designator.Invalid || Dest.Designator.Invalid) 9219 1.1 joerg return false; 9220 1.1 joerg 9221 1.1 joerg // We require that Src and Dest are both pointers to arrays of 9222 1.1 joerg // trivially-copyable type. (For the wide version, the designator will be 9223 1.1 joerg // invalid if the designated object is not a wchar_t.) 9224 1.1 joerg QualType T = Dest.Designator.getType(Info.Ctx); 9225 1.1 joerg QualType SrcT = Src.Designator.getType(Info.Ctx); 9226 1.1 joerg if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) { 9227 1.1.1.2 joerg // FIXME: Consider using our bit_cast implementation to support this. 9228 1.1 joerg Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T; 9229 1.1 joerg return false; 9230 1.1 joerg } 9231 1.1 joerg if (T->isIncompleteType()) { 9232 1.1 joerg Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T; 9233 1.1 joerg return false; 9234 1.1 joerg } 9235 1.1 joerg if (!T.isTriviallyCopyableType(Info.Ctx)) { 9236 1.1 joerg Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T; 9237 1.1 joerg return false; 9238 1.1 joerg } 9239 1.1 joerg 9240 1.1 joerg // Figure out how many T's we're copying. 9241 1.1 joerg uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity(); 9242 1.1 joerg if (!WChar) { 9243 1.1 joerg uint64_t Remainder; 9244 1.1 joerg llvm::APInt OrigN = N; 9245 1.1 joerg llvm::APInt::udivrem(OrigN, TSize, N, Remainder); 9246 1.1 joerg if (Remainder) { 9247 1.1 joerg Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) 9248 1.1 joerg << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false) 9249 1.1 joerg << (unsigned)TSize; 9250 1.1 joerg return false; 9251 1.1 joerg } 9252 1.1 joerg } 9253 1.1 joerg 9254 1.1 joerg // Check that the copying will remain within the arrays, just so that we 9255 1.1 joerg // can give a more meaningful diagnostic. This implicitly also checks that 9256 1.1 joerg // N fits into 64 bits. 9257 1.1 joerg uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second; 9258 1.1 joerg uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second; 9259 1.1 joerg if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) { 9260 1.1 joerg Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) 9261 1.1 joerg << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T 9262 1.1 joerg << N.toString(10, /*Signed*/false); 9263 1.1 joerg return false; 9264 1.1 joerg } 9265 1.1 joerg uint64_t NElems = N.getZExtValue(); 9266 1.1 joerg uint64_t NBytes = NElems * TSize; 9267 1.1 joerg 9268 1.1 joerg // Check for overlap. 9269 1.1 joerg int Direction = 1; 9270 1.1 joerg if (HasSameBase(Src, Dest)) { 9271 1.1 joerg uint64_t SrcOffset = Src.getLValueOffset().getQuantity(); 9272 1.1 joerg uint64_t DestOffset = Dest.getLValueOffset().getQuantity(); 9273 1.1 joerg if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) { 9274 1.1 joerg // Dest is inside the source region. 9275 1.1 joerg if (!Move) { 9276 1.1 joerg Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; 9277 1.1 joerg return false; 9278 1.1 joerg } 9279 1.1 joerg // For memmove and friends, copy backwards. 9280 1.1 joerg if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) || 9281 1.1 joerg !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1)) 9282 1.1 joerg return false; 9283 1.1 joerg Direction = -1; 9284 1.1 joerg } else if (!Move && SrcOffset >= DestOffset && 9285 1.1 joerg SrcOffset - DestOffset < NBytes) { 9286 1.1 joerg // Src is inside the destination region for memcpy: invalid. 9287 1.1 joerg Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; 9288 1.1 joerg return false; 9289 1.1 joerg } 9290 1.1 joerg } 9291 1.1 joerg 9292 1.1 joerg while (true) { 9293 1.1 joerg APValue Val; 9294 1.1 joerg // FIXME: Set WantObjectRepresentation to true if we're copying a 9295 1.1 joerg // char-like type? 9296 1.1 joerg if (!handleLValueToRValueConversion(Info, E, T, Src, Val) || 9297 1.1 joerg !handleAssignment(Info, E, Dest, T, Val)) 9298 1.1 joerg return false; 9299 1.1 joerg // Do not iterate past the last element; if we're copying backwards, that 9300 1.1 joerg // might take us off the start of the array. 9301 1.1 joerg if (--NElems == 0) 9302 1.1 joerg return true; 9303 1.1 joerg if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) || 9304 1.1 joerg !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction)) 9305 1.1 joerg return false; 9306 1.1 joerg } 9307 1.1 joerg } 9308 1.1 joerg 9309 1.1 joerg default: 9310 1.1 joerg break; 9311 1.1 joerg } 9312 1.1 joerg 9313 1.1 joerg return visitNonBuiltinCallExpr(E); 9314 1.1 joerg } 9315 1.1 joerg 9316 1.1 joerg static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, 9317 1.1 joerg APValue &Result, const InitListExpr *ILE, 9318 1.1 joerg QualType AllocType); 9319 1.1.1.2 joerg static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This, 9320 1.1.1.2 joerg APValue &Result, 9321 1.1.1.2 joerg const CXXConstructExpr *CCE, 9322 1.1.1.2 joerg QualType AllocType); 9323 1.1 joerg 9324 1.1 joerg bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) { 9325 1.1.1.2 joerg if (!Info.getLangOpts().CPlusPlus20) 9326 1.1 joerg Info.CCEDiag(E, diag::note_constexpr_new); 9327 1.1 joerg 9328 1.1 joerg // We cannot speculatively evaluate a delete expression. 9329 1.1 joerg if (Info.SpeculativeEvaluationDepth) 9330 1.1 joerg return false; 9331 1.1 joerg 9332 1.1 joerg FunctionDecl *OperatorNew = E->getOperatorNew(); 9333 1.1 joerg 9334 1.1 joerg bool IsNothrow = false; 9335 1.1 joerg bool IsPlacement = false; 9336 1.1 joerg if (OperatorNew->isReservedGlobalPlacementOperator() && 9337 1.1 joerg Info.CurrentCall->isStdFunction() && !E->isArray()) { 9338 1.1 joerg // FIXME Support array placement new. 9339 1.1 joerg assert(E->getNumPlacementArgs() == 1); 9340 1.1 joerg if (!EvaluatePointer(E->getPlacementArg(0), Result, Info)) 9341 1.1 joerg return false; 9342 1.1 joerg if (Result.Designator.Invalid) 9343 1.1 joerg return false; 9344 1.1 joerg IsPlacement = true; 9345 1.1 joerg } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) { 9346 1.1 joerg Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 9347 1.1 joerg << isa<CXXMethodDecl>(OperatorNew) << OperatorNew; 9348 1.1 joerg return false; 9349 1.1 joerg } else if (E->getNumPlacementArgs()) { 9350 1.1 joerg // The only new-placement list we support is of the form (std::nothrow). 9351 1.1 joerg // 9352 1.1 joerg // FIXME: There is no restriction on this, but it's not clear that any 9353 1.1 joerg // other form makes any sense. We get here for cases such as: 9354 1.1 joerg // 9355 1.1 joerg // new (std::align_val_t{N}) X(int) 9356 1.1 joerg // 9357 1.1 joerg // (which should presumably be valid only if N is a multiple of 9358 1.1 joerg // alignof(int), and in any case can't be deallocated unless N is 9359 1.1 joerg // alignof(X) and X has new-extended alignment). 9360 1.1 joerg if (E->getNumPlacementArgs() != 1 || 9361 1.1 joerg !E->getPlacementArg(0)->getType()->isNothrowT()) 9362 1.1 joerg return Error(E, diag::note_constexpr_new_placement); 9363 1.1 joerg 9364 1.1 joerg LValue Nothrow; 9365 1.1 joerg if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info)) 9366 1.1 joerg return false; 9367 1.1 joerg IsNothrow = true; 9368 1.1 joerg } 9369 1.1 joerg 9370 1.1 joerg const Expr *Init = E->getInitializer(); 9371 1.1 joerg const InitListExpr *ResizedArrayILE = nullptr; 9372 1.1.1.2 joerg const CXXConstructExpr *ResizedArrayCCE = nullptr; 9373 1.1.1.2 joerg bool ValueInit = false; 9374 1.1 joerg 9375 1.1 joerg QualType AllocType = E->getAllocatedType(); 9376 1.1 joerg if (Optional<const Expr*> ArraySize = E->getArraySize()) { 9377 1.1 joerg const Expr *Stripped = *ArraySize; 9378 1.1 joerg for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped); 9379 1.1 joerg Stripped = ICE->getSubExpr()) 9380 1.1 joerg if (ICE->getCastKind() != CK_NoOp && 9381 1.1 joerg ICE->getCastKind() != CK_IntegralCast) 9382 1.1 joerg break; 9383 1.1 joerg 9384 1.1 joerg llvm::APSInt ArrayBound; 9385 1.1 joerg if (!EvaluateInteger(Stripped, ArrayBound, Info)) 9386 1.1 joerg return false; 9387 1.1 joerg 9388 1.1 joerg // C++ [expr.new]p9: 9389 1.1 joerg // The expression is erroneous if: 9390 1.1 joerg // -- [...] its value before converting to size_t [or] applying the 9391 1.1 joerg // second standard conversion sequence is less than zero 9392 1.1 joerg if (ArrayBound.isSigned() && ArrayBound.isNegative()) { 9393 1.1 joerg if (IsNothrow) 9394 1.1 joerg return ZeroInitialization(E); 9395 1.1 joerg 9396 1.1 joerg Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative) 9397 1.1 joerg << ArrayBound << (*ArraySize)->getSourceRange(); 9398 1.1 joerg return false; 9399 1.1 joerg } 9400 1.1 joerg 9401 1.1 joerg // -- its value is such that the size of the allocated object would 9402 1.1 joerg // exceed the implementation-defined limit 9403 1.1 joerg if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType, 9404 1.1 joerg ArrayBound) > 9405 1.1 joerg ConstantArrayType::getMaxSizeBits(Info.Ctx)) { 9406 1.1 joerg if (IsNothrow) 9407 1.1 joerg return ZeroInitialization(E); 9408 1.1 joerg 9409 1.1 joerg Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large) 9410 1.1 joerg << ArrayBound << (*ArraySize)->getSourceRange(); 9411 1.1 joerg return false; 9412 1.1 joerg } 9413 1.1 joerg 9414 1.1 joerg // -- the new-initializer is a braced-init-list and the number of 9415 1.1 joerg // array elements for which initializers are provided [...] 9416 1.1 joerg // exceeds the number of elements to initialize 9417 1.1.1.2 joerg if (!Init) { 9418 1.1.1.2 joerg // No initialization is performed. 9419 1.1.1.2 joerg } else if (isa<CXXScalarValueInitExpr>(Init) || 9420 1.1.1.2 joerg isa<ImplicitValueInitExpr>(Init)) { 9421 1.1.1.2 joerg ValueInit = true; 9422 1.1.1.2 joerg } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) { 9423 1.1.1.2 joerg ResizedArrayCCE = CCE; 9424 1.1.1.2 joerg } else { 9425 1.1 joerg auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType()); 9426 1.1 joerg assert(CAT && "unexpected type for array initializer"); 9427 1.1 joerg 9428 1.1 joerg unsigned Bits = 9429 1.1 joerg std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth()); 9430 1.1 joerg llvm::APInt InitBound = CAT->getSize().zextOrSelf(Bits); 9431 1.1 joerg llvm::APInt AllocBound = ArrayBound.zextOrSelf(Bits); 9432 1.1 joerg if (InitBound.ugt(AllocBound)) { 9433 1.1 joerg if (IsNothrow) 9434 1.1 joerg return ZeroInitialization(E); 9435 1.1 joerg 9436 1.1 joerg Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small) 9437 1.1 joerg << AllocBound.toString(10, /*Signed=*/false) 9438 1.1 joerg << InitBound.toString(10, /*Signed=*/false) 9439 1.1 joerg << (*ArraySize)->getSourceRange(); 9440 1.1 joerg return false; 9441 1.1 joerg } 9442 1.1 joerg 9443 1.1 joerg // If the sizes differ, we must have an initializer list, and we need 9444 1.1 joerg // special handling for this case when we initialize. 9445 1.1 joerg if (InitBound != AllocBound) 9446 1.1 joerg ResizedArrayILE = cast<InitListExpr>(Init); 9447 1.1 joerg } 9448 1.1 joerg 9449 1.1 joerg AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr, 9450 1.1 joerg ArrayType::Normal, 0); 9451 1.1 joerg } else { 9452 1.1 joerg assert(!AllocType->isArrayType() && 9453 1.1 joerg "array allocation with non-array new"); 9454 1.1 joerg } 9455 1.1 joerg 9456 1.1 joerg APValue *Val; 9457 1.1 joerg if (IsPlacement) { 9458 1.1 joerg AccessKinds AK = AK_Construct; 9459 1.1 joerg struct FindObjectHandler { 9460 1.1 joerg EvalInfo &Info; 9461 1.1 joerg const Expr *E; 9462 1.1 joerg QualType AllocType; 9463 1.1 joerg const AccessKinds AccessKind; 9464 1.1 joerg APValue *Value; 9465 1.1 joerg 9466 1.1 joerg typedef bool result_type; 9467 1.1 joerg bool failed() { return false; } 9468 1.1 joerg bool found(APValue &Subobj, QualType SubobjType) { 9469 1.1 joerg // FIXME: Reject the cases where [basic.life]p8 would not permit the 9470 1.1 joerg // old name of the object to be used to name the new object. 9471 1.1 joerg if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) { 9472 1.1 joerg Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) << 9473 1.1 joerg SubobjType << AllocType; 9474 1.1 joerg return false; 9475 1.1 joerg } 9476 1.1 joerg Value = &Subobj; 9477 1.1 joerg return true; 9478 1.1 joerg } 9479 1.1 joerg bool found(APSInt &Value, QualType SubobjType) { 9480 1.1 joerg Info.FFDiag(E, diag::note_constexpr_construct_complex_elem); 9481 1.1 joerg return false; 9482 1.1 joerg } 9483 1.1 joerg bool found(APFloat &Value, QualType SubobjType) { 9484 1.1 joerg Info.FFDiag(E, diag::note_constexpr_construct_complex_elem); 9485 1.1 joerg return false; 9486 1.1 joerg } 9487 1.1 joerg } Handler = {Info, E, AllocType, AK, nullptr}; 9488 1.1 joerg 9489 1.1 joerg CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType); 9490 1.1 joerg if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler)) 9491 1.1 joerg return false; 9492 1.1 joerg 9493 1.1 joerg Val = Handler.Value; 9494 1.1 joerg 9495 1.1 joerg // [basic.life]p1: 9496 1.1 joerg // The lifetime of an object o of type T ends when [...] the storage 9497 1.1 joerg // which the object occupies is [...] reused by an object that is not 9498 1.1 joerg // nested within o (6.6.2). 9499 1.1 joerg *Val = APValue(); 9500 1.1 joerg } else { 9501 1.1 joerg // Perform the allocation and obtain a pointer to the resulting object. 9502 1.1 joerg Val = Info.createHeapAlloc(E, AllocType, Result); 9503 1.1 joerg if (!Val) 9504 1.1 joerg return false; 9505 1.1 joerg } 9506 1.1 joerg 9507 1.1.1.2 joerg if (ValueInit) { 9508 1.1.1.2 joerg ImplicitValueInitExpr VIE(AllocType); 9509 1.1.1.2 joerg if (!EvaluateInPlace(*Val, Info, Result, &VIE)) 9510 1.1.1.2 joerg return false; 9511 1.1.1.2 joerg } else if (ResizedArrayILE) { 9512 1.1 joerg if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE, 9513 1.1 joerg AllocType)) 9514 1.1 joerg return false; 9515 1.1.1.2 joerg } else if (ResizedArrayCCE) { 9516 1.1.1.2 joerg if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE, 9517 1.1.1.2 joerg AllocType)) 9518 1.1.1.2 joerg return false; 9519 1.1 joerg } else if (Init) { 9520 1.1 joerg if (!EvaluateInPlace(*Val, Info, Result, Init)) 9521 1.1 joerg return false; 9522 1.1.1.2 joerg } else if (!getDefaultInitValue(AllocType, *Val)) { 9523 1.1.1.2 joerg return false; 9524 1.1 joerg } 9525 1.1 joerg 9526 1.1 joerg // Array new returns a pointer to the first element, not a pointer to the 9527 1.1 joerg // array. 9528 1.1 joerg if (auto *AT = AllocType->getAsArrayTypeUnsafe()) 9529 1.1 joerg Result.addArray(Info, E, cast<ConstantArrayType>(AT)); 9530 1.1 joerg 9531 1.1 joerg return true; 9532 1.1 joerg } 9533 1.1 joerg //===----------------------------------------------------------------------===// 9534 1.1 joerg // Member Pointer Evaluation 9535 1.1 joerg //===----------------------------------------------------------------------===// 9536 1.1 joerg 9537 1.1 joerg namespace { 9538 1.1 joerg class MemberPointerExprEvaluator 9539 1.1 joerg : public ExprEvaluatorBase<MemberPointerExprEvaluator> { 9540 1.1 joerg MemberPtr &Result; 9541 1.1 joerg 9542 1.1 joerg bool Success(const ValueDecl *D) { 9543 1.1 joerg Result = MemberPtr(D); 9544 1.1 joerg return true; 9545 1.1 joerg } 9546 1.1 joerg public: 9547 1.1 joerg 9548 1.1 joerg MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result) 9549 1.1 joerg : ExprEvaluatorBaseTy(Info), Result(Result) {} 9550 1.1 joerg 9551 1.1 joerg bool Success(const APValue &V, const Expr *E) { 9552 1.1 joerg Result.setFrom(V); 9553 1.1 joerg return true; 9554 1.1 joerg } 9555 1.1 joerg bool ZeroInitialization(const Expr *E) { 9556 1.1 joerg return Success((const ValueDecl*)nullptr); 9557 1.1 joerg } 9558 1.1 joerg 9559 1.1 joerg bool VisitCastExpr(const CastExpr *E); 9560 1.1 joerg bool VisitUnaryAddrOf(const UnaryOperator *E); 9561 1.1 joerg }; 9562 1.1 joerg } // end anonymous namespace 9563 1.1 joerg 9564 1.1 joerg static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, 9565 1.1 joerg EvalInfo &Info) { 9566 1.1.1.2 joerg assert(!E->isValueDependent()); 9567 1.1 joerg assert(E->isRValue() && E->getType()->isMemberPointerType()); 9568 1.1 joerg return MemberPointerExprEvaluator(Info, Result).Visit(E); 9569 1.1 joerg } 9570 1.1 joerg 9571 1.1 joerg bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) { 9572 1.1 joerg switch (E->getCastKind()) { 9573 1.1 joerg default: 9574 1.1 joerg return ExprEvaluatorBaseTy::VisitCastExpr(E); 9575 1.1 joerg 9576 1.1 joerg case CK_NullToMemberPointer: 9577 1.1 joerg VisitIgnoredValue(E->getSubExpr()); 9578 1.1 joerg return ZeroInitialization(E); 9579 1.1 joerg 9580 1.1 joerg case CK_BaseToDerivedMemberPointer: { 9581 1.1 joerg if (!Visit(E->getSubExpr())) 9582 1.1 joerg return false; 9583 1.1 joerg if (E->path_empty()) 9584 1.1 joerg return true; 9585 1.1 joerg // Base-to-derived member pointer casts store the path in derived-to-base 9586 1.1 joerg // order, so iterate backwards. The CXXBaseSpecifier also provides us with 9587 1.1 joerg // the wrong end of the derived->base arc, so stagger the path by one class. 9588 1.1 joerg typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter; 9589 1.1 joerg for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin()); 9590 1.1 joerg PathI != PathE; ++PathI) { 9591 1.1 joerg assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 9592 1.1 joerg const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl(); 9593 1.1 joerg if (!Result.castToDerived(Derived)) 9594 1.1 joerg return Error(E); 9595 1.1 joerg } 9596 1.1 joerg const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass(); 9597 1.1 joerg if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl())) 9598 1.1 joerg return Error(E); 9599 1.1 joerg return true; 9600 1.1 joerg } 9601 1.1 joerg 9602 1.1 joerg case CK_DerivedToBaseMemberPointer: 9603 1.1 joerg if (!Visit(E->getSubExpr())) 9604 1.1 joerg return false; 9605 1.1 joerg for (CastExpr::path_const_iterator PathI = E->path_begin(), 9606 1.1 joerg PathE = E->path_end(); PathI != PathE; ++PathI) { 9607 1.1 joerg assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 9608 1.1 joerg const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 9609 1.1 joerg if (!Result.castToBase(Base)) 9610 1.1 joerg return Error(E); 9611 1.1 joerg } 9612 1.1 joerg return true; 9613 1.1 joerg } 9614 1.1 joerg } 9615 1.1 joerg 9616 1.1 joerg bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 9617 1.1 joerg // C++11 [expr.unary.op]p3 has very strict rules on how the address of a 9618 1.1 joerg // member can be formed. 9619 1.1 joerg return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl()); 9620 1.1 joerg } 9621 1.1 joerg 9622 1.1 joerg //===----------------------------------------------------------------------===// 9623 1.1 joerg // Record Evaluation 9624 1.1 joerg //===----------------------------------------------------------------------===// 9625 1.1 joerg 9626 1.1 joerg namespace { 9627 1.1 joerg class RecordExprEvaluator 9628 1.1 joerg : public ExprEvaluatorBase<RecordExprEvaluator> { 9629 1.1 joerg const LValue &This; 9630 1.1 joerg APValue &Result; 9631 1.1 joerg public: 9632 1.1 joerg 9633 1.1 joerg RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result) 9634 1.1 joerg : ExprEvaluatorBaseTy(info), This(This), Result(Result) {} 9635 1.1 joerg 9636 1.1 joerg bool Success(const APValue &V, const Expr *E) { 9637 1.1 joerg Result = V; 9638 1.1 joerg return true; 9639 1.1 joerg } 9640 1.1 joerg bool ZeroInitialization(const Expr *E) { 9641 1.1 joerg return ZeroInitialization(E, E->getType()); 9642 1.1 joerg } 9643 1.1 joerg bool ZeroInitialization(const Expr *E, QualType T); 9644 1.1 joerg 9645 1.1 joerg bool VisitCallExpr(const CallExpr *E) { 9646 1.1 joerg return handleCallExpr(E, Result, &This); 9647 1.1 joerg } 9648 1.1 joerg bool VisitCastExpr(const CastExpr *E); 9649 1.1 joerg bool VisitInitListExpr(const InitListExpr *E); 9650 1.1 joerg bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 9651 1.1 joerg return VisitCXXConstructExpr(E, E->getType()); 9652 1.1 joerg } 9653 1.1 joerg bool VisitLambdaExpr(const LambdaExpr *E); 9654 1.1 joerg bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E); 9655 1.1 joerg bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T); 9656 1.1 joerg bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E); 9657 1.1 joerg bool VisitBinCmp(const BinaryOperator *E); 9658 1.1 joerg }; 9659 1.1 joerg } 9660 1.1 joerg 9661 1.1 joerg /// Perform zero-initialization on an object of non-union class type. 9662 1.1 joerg /// C++11 [dcl.init]p5: 9663 1.1 joerg /// To zero-initialize an object or reference of type T means: 9664 1.1 joerg /// [...] 9665 1.1 joerg /// -- if T is a (possibly cv-qualified) non-union class type, 9666 1.1 joerg /// each non-static data member and each base-class subobject is 9667 1.1 joerg /// zero-initialized 9668 1.1 joerg static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E, 9669 1.1 joerg const RecordDecl *RD, 9670 1.1 joerg const LValue &This, APValue &Result) { 9671 1.1 joerg assert(!RD->isUnion() && "Expected non-union class type"); 9672 1.1 joerg const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD); 9673 1.1 joerg Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0, 9674 1.1 joerg std::distance(RD->field_begin(), RD->field_end())); 9675 1.1 joerg 9676 1.1 joerg if (RD->isInvalidDecl()) return false; 9677 1.1 joerg const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 9678 1.1 joerg 9679 1.1 joerg if (CD) { 9680 1.1 joerg unsigned Index = 0; 9681 1.1 joerg for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(), 9682 1.1 joerg End = CD->bases_end(); I != End; ++I, ++Index) { 9683 1.1 joerg const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl(); 9684 1.1 joerg LValue Subobject = This; 9685 1.1 joerg if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout)) 9686 1.1 joerg return false; 9687 1.1 joerg if (!HandleClassZeroInitialization(Info, E, Base, Subobject, 9688 1.1 joerg Result.getStructBase(Index))) 9689 1.1 joerg return false; 9690 1.1 joerg } 9691 1.1 joerg } 9692 1.1 joerg 9693 1.1 joerg for (const auto *I : RD->fields()) { 9694 1.1 joerg // -- if T is a reference type, no initialization is performed. 9695 1.1.1.2 joerg if (I->isUnnamedBitfield() || I->getType()->isReferenceType()) 9696 1.1 joerg continue; 9697 1.1 joerg 9698 1.1 joerg LValue Subobject = This; 9699 1.1 joerg if (!HandleLValueMember(Info, E, Subobject, I, &Layout)) 9700 1.1 joerg return false; 9701 1.1 joerg 9702 1.1 joerg ImplicitValueInitExpr VIE(I->getType()); 9703 1.1 joerg if (!EvaluateInPlace( 9704 1.1 joerg Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE)) 9705 1.1 joerg return false; 9706 1.1 joerg } 9707 1.1 joerg 9708 1.1 joerg return true; 9709 1.1 joerg } 9710 1.1 joerg 9711 1.1 joerg bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) { 9712 1.1 joerg const RecordDecl *RD = T->castAs<RecordType>()->getDecl(); 9713 1.1 joerg if (RD->isInvalidDecl()) return false; 9714 1.1 joerg if (RD->isUnion()) { 9715 1.1 joerg // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the 9716 1.1 joerg // object's first non-static named data member is zero-initialized 9717 1.1 joerg RecordDecl::field_iterator I = RD->field_begin(); 9718 1.1.1.2 joerg while (I != RD->field_end() && (*I)->isUnnamedBitfield()) 9719 1.1.1.2 joerg ++I; 9720 1.1 joerg if (I == RD->field_end()) { 9721 1.1 joerg Result = APValue((const FieldDecl*)nullptr); 9722 1.1 joerg return true; 9723 1.1 joerg } 9724 1.1 joerg 9725 1.1 joerg LValue Subobject = This; 9726 1.1 joerg if (!HandleLValueMember(Info, E, Subobject, *I)) 9727 1.1 joerg return false; 9728 1.1 joerg Result = APValue(*I); 9729 1.1 joerg ImplicitValueInitExpr VIE(I->getType()); 9730 1.1 joerg return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE); 9731 1.1 joerg } 9732 1.1 joerg 9733 1.1 joerg if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) { 9734 1.1 joerg Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD; 9735 1.1 joerg return false; 9736 1.1 joerg } 9737 1.1 joerg 9738 1.1 joerg return HandleClassZeroInitialization(Info, E, RD, This, Result); 9739 1.1 joerg } 9740 1.1 joerg 9741 1.1 joerg bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) { 9742 1.1 joerg switch (E->getCastKind()) { 9743 1.1 joerg default: 9744 1.1 joerg return ExprEvaluatorBaseTy::VisitCastExpr(E); 9745 1.1 joerg 9746 1.1 joerg case CK_ConstructorConversion: 9747 1.1 joerg return Visit(E->getSubExpr()); 9748 1.1 joerg 9749 1.1 joerg case CK_DerivedToBase: 9750 1.1 joerg case CK_UncheckedDerivedToBase: { 9751 1.1 joerg APValue DerivedObject; 9752 1.1 joerg if (!Evaluate(DerivedObject, Info, E->getSubExpr())) 9753 1.1 joerg return false; 9754 1.1 joerg if (!DerivedObject.isStruct()) 9755 1.1 joerg return Error(E->getSubExpr()); 9756 1.1 joerg 9757 1.1 joerg // Derived-to-base rvalue conversion: just slice off the derived part. 9758 1.1 joerg APValue *Value = &DerivedObject; 9759 1.1 joerg const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl(); 9760 1.1 joerg for (CastExpr::path_const_iterator PathI = E->path_begin(), 9761 1.1 joerg PathE = E->path_end(); PathI != PathE; ++PathI) { 9762 1.1 joerg assert(!(*PathI)->isVirtual() && "record rvalue with virtual base"); 9763 1.1 joerg const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 9764 1.1 joerg Value = &Value->getStructBase(getBaseIndex(RD, Base)); 9765 1.1 joerg RD = Base; 9766 1.1 joerg } 9767 1.1 joerg Result = *Value; 9768 1.1 joerg return true; 9769 1.1 joerg } 9770 1.1 joerg } 9771 1.1 joerg } 9772 1.1 joerg 9773 1.1 joerg bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 9774 1.1 joerg if (E->isTransparent()) 9775 1.1 joerg return Visit(E->getInit(0)); 9776 1.1 joerg 9777 1.1 joerg const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl(); 9778 1.1 joerg if (RD->isInvalidDecl()) return false; 9779 1.1 joerg const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 9780 1.1 joerg auto *CXXRD = dyn_cast<CXXRecordDecl>(RD); 9781 1.1 joerg 9782 1.1 joerg EvalInfo::EvaluatingConstructorRAII EvalObj( 9783 1.1 joerg Info, 9784 1.1 joerg ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}, 9785 1.1 joerg CXXRD && CXXRD->getNumBases()); 9786 1.1 joerg 9787 1.1 joerg if (RD->isUnion()) { 9788 1.1 joerg const FieldDecl *Field = E->getInitializedFieldInUnion(); 9789 1.1 joerg Result = APValue(Field); 9790 1.1 joerg if (!Field) 9791 1.1 joerg return true; 9792 1.1 joerg 9793 1.1 joerg // If the initializer list for a union does not contain any elements, the 9794 1.1 joerg // first element of the union is value-initialized. 9795 1.1 joerg // FIXME: The element should be initialized from an initializer list. 9796 1.1 joerg // Is this difference ever observable for initializer lists which 9797 1.1 joerg // we don't build? 9798 1.1 joerg ImplicitValueInitExpr VIE(Field->getType()); 9799 1.1 joerg const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE; 9800 1.1 joerg 9801 1.1 joerg LValue Subobject = This; 9802 1.1 joerg if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout)) 9803 1.1 joerg return false; 9804 1.1 joerg 9805 1.1 joerg // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 9806 1.1 joerg ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 9807 1.1 joerg isa<CXXDefaultInitExpr>(InitExpr)); 9808 1.1 joerg 9809 1.1.1.2 joerg if (EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr)) { 9810 1.1.1.2 joerg if (Field->isBitField()) 9811 1.1.1.2 joerg return truncateBitfieldValue(Info, InitExpr, Result.getUnionValue(), 9812 1.1.1.2 joerg Field); 9813 1.1.1.2 joerg return true; 9814 1.1.1.2 joerg } 9815 1.1.1.2 joerg 9816 1.1.1.2 joerg return false; 9817 1.1 joerg } 9818 1.1 joerg 9819 1.1 joerg if (!Result.hasValue()) 9820 1.1 joerg Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0, 9821 1.1 joerg std::distance(RD->field_begin(), RD->field_end())); 9822 1.1 joerg unsigned ElementNo = 0; 9823 1.1 joerg bool Success = true; 9824 1.1 joerg 9825 1.1 joerg // Initialize base classes. 9826 1.1 joerg if (CXXRD && CXXRD->getNumBases()) { 9827 1.1 joerg for (const auto &Base : CXXRD->bases()) { 9828 1.1 joerg assert(ElementNo < E->getNumInits() && "missing init for base class"); 9829 1.1 joerg const Expr *Init = E->getInit(ElementNo); 9830 1.1 joerg 9831 1.1 joerg LValue Subobject = This; 9832 1.1 joerg if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base)) 9833 1.1 joerg return false; 9834 1.1 joerg 9835 1.1 joerg APValue &FieldVal = Result.getStructBase(ElementNo); 9836 1.1 joerg if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) { 9837 1.1 joerg if (!Info.noteFailure()) 9838 1.1 joerg return false; 9839 1.1 joerg Success = false; 9840 1.1 joerg } 9841 1.1 joerg ++ElementNo; 9842 1.1 joerg } 9843 1.1 joerg 9844 1.1 joerg EvalObj.finishedConstructingBases(); 9845 1.1 joerg } 9846 1.1 joerg 9847 1.1 joerg // Initialize members. 9848 1.1 joerg for (const auto *Field : RD->fields()) { 9849 1.1 joerg // Anonymous bit-fields are not considered members of the class for 9850 1.1 joerg // purposes of aggregate initialization. 9851 1.1 joerg if (Field->isUnnamedBitfield()) 9852 1.1 joerg continue; 9853 1.1 joerg 9854 1.1 joerg LValue Subobject = This; 9855 1.1 joerg 9856 1.1 joerg bool HaveInit = ElementNo < E->getNumInits(); 9857 1.1 joerg 9858 1.1 joerg // FIXME: Diagnostics here should point to the end of the initializer 9859 1.1 joerg // list, not the start. 9860 1.1 joerg if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E, 9861 1.1 joerg Subobject, Field, &Layout)) 9862 1.1 joerg return false; 9863 1.1 joerg 9864 1.1 joerg // Perform an implicit value-initialization for members beyond the end of 9865 1.1 joerg // the initializer list. 9866 1.1 joerg ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType()); 9867 1.1 joerg const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE; 9868 1.1 joerg 9869 1.1 joerg // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 9870 1.1 joerg ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 9871 1.1 joerg isa<CXXDefaultInitExpr>(Init)); 9872 1.1 joerg 9873 1.1 joerg APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); 9874 1.1 joerg if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) || 9875 1.1 joerg (Field->isBitField() && !truncateBitfieldValue(Info, Init, 9876 1.1 joerg FieldVal, Field))) { 9877 1.1 joerg if (!Info.noteFailure()) 9878 1.1 joerg return false; 9879 1.1 joerg Success = false; 9880 1.1 joerg } 9881 1.1 joerg } 9882 1.1 joerg 9883 1.1.1.2 joerg EvalObj.finishedConstructingFields(); 9884 1.1.1.2 joerg 9885 1.1 joerg return Success; 9886 1.1 joerg } 9887 1.1 joerg 9888 1.1 joerg bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 9889 1.1 joerg QualType T) { 9890 1.1 joerg // Note that E's type is not necessarily the type of our class here; we might 9891 1.1 joerg // be initializing an array element instead. 9892 1.1 joerg const CXXConstructorDecl *FD = E->getConstructor(); 9893 1.1 joerg if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false; 9894 1.1 joerg 9895 1.1 joerg bool ZeroInit = E->requiresZeroInitialization(); 9896 1.1 joerg if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) { 9897 1.1 joerg // If we've already performed zero-initialization, we're already done. 9898 1.1 joerg if (Result.hasValue()) 9899 1.1 joerg return true; 9900 1.1 joerg 9901 1.1 joerg if (ZeroInit) 9902 1.1 joerg return ZeroInitialization(E, T); 9903 1.1 joerg 9904 1.1.1.2 joerg return getDefaultInitValue(T, Result); 9905 1.1 joerg } 9906 1.1 joerg 9907 1.1 joerg const FunctionDecl *Definition = nullptr; 9908 1.1 joerg auto Body = FD->getBody(Definition); 9909 1.1 joerg 9910 1.1 joerg if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) 9911 1.1 joerg return false; 9912 1.1 joerg 9913 1.1 joerg // Avoid materializing a temporary for an elidable copy/move constructor. 9914 1.1 joerg if (E->isElidable() && !ZeroInit) 9915 1.1 joerg if (const MaterializeTemporaryExpr *ME 9916 1.1 joerg = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0))) 9917 1.1.1.2 joerg return Visit(ME->getSubExpr()); 9918 1.1 joerg 9919 1.1 joerg if (ZeroInit && !ZeroInitialization(E, T)) 9920 1.1 joerg return false; 9921 1.1 joerg 9922 1.1 joerg auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); 9923 1.1 joerg return HandleConstructorCall(E, This, Args, 9924 1.1 joerg cast<CXXConstructorDecl>(Definition), Info, 9925 1.1 joerg Result); 9926 1.1 joerg } 9927 1.1 joerg 9928 1.1 joerg bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr( 9929 1.1 joerg const CXXInheritedCtorInitExpr *E) { 9930 1.1 joerg if (!Info.CurrentCall) { 9931 1.1 joerg assert(Info.checkingPotentialConstantExpression()); 9932 1.1 joerg return false; 9933 1.1 joerg } 9934 1.1 joerg 9935 1.1 joerg const CXXConstructorDecl *FD = E->getConstructor(); 9936 1.1 joerg if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) 9937 1.1 joerg return false; 9938 1.1 joerg 9939 1.1 joerg const FunctionDecl *Definition = nullptr; 9940 1.1 joerg auto Body = FD->getBody(Definition); 9941 1.1 joerg 9942 1.1 joerg if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) 9943 1.1 joerg return false; 9944 1.1 joerg 9945 1.1 joerg return HandleConstructorCall(E, This, Info.CurrentCall->Arguments, 9946 1.1 joerg cast<CXXConstructorDecl>(Definition), Info, 9947 1.1 joerg Result); 9948 1.1 joerg } 9949 1.1 joerg 9950 1.1 joerg bool RecordExprEvaluator::VisitCXXStdInitializerListExpr( 9951 1.1 joerg const CXXStdInitializerListExpr *E) { 9952 1.1 joerg const ConstantArrayType *ArrayType = 9953 1.1 joerg Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType()); 9954 1.1 joerg 9955 1.1 joerg LValue Array; 9956 1.1 joerg if (!EvaluateLValue(E->getSubExpr(), Array, Info)) 9957 1.1 joerg return false; 9958 1.1 joerg 9959 1.1 joerg // Get a pointer to the first element of the array. 9960 1.1 joerg Array.addArray(Info, E, ArrayType); 9961 1.1 joerg 9962 1.1.1.2 joerg auto InvalidType = [&] { 9963 1.1.1.2 joerg Info.FFDiag(E, diag::note_constexpr_unsupported_layout) 9964 1.1.1.2 joerg << E->getType(); 9965 1.1.1.2 joerg return false; 9966 1.1.1.2 joerg }; 9967 1.1.1.2 joerg 9968 1.1 joerg // FIXME: Perform the checks on the field types in SemaInit. 9969 1.1 joerg RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl(); 9970 1.1 joerg RecordDecl::field_iterator Field = Record->field_begin(); 9971 1.1 joerg if (Field == Record->field_end()) 9972 1.1.1.2 joerg return InvalidType(); 9973 1.1 joerg 9974 1.1 joerg // Start pointer. 9975 1.1 joerg if (!Field->getType()->isPointerType() || 9976 1.1 joerg !Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 9977 1.1 joerg ArrayType->getElementType())) 9978 1.1.1.2 joerg return InvalidType(); 9979 1.1 joerg 9980 1.1 joerg // FIXME: What if the initializer_list type has base classes, etc? 9981 1.1 joerg Result = APValue(APValue::UninitStruct(), 0, 2); 9982 1.1 joerg Array.moveInto(Result.getStructField(0)); 9983 1.1 joerg 9984 1.1 joerg if (++Field == Record->field_end()) 9985 1.1.1.2 joerg return InvalidType(); 9986 1.1 joerg 9987 1.1 joerg if (Field->getType()->isPointerType() && 9988 1.1 joerg Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 9989 1.1 joerg ArrayType->getElementType())) { 9990 1.1 joerg // End pointer. 9991 1.1 joerg if (!HandleLValueArrayAdjustment(Info, E, Array, 9992 1.1 joerg ArrayType->getElementType(), 9993 1.1 joerg ArrayType->getSize().getZExtValue())) 9994 1.1 joerg return false; 9995 1.1 joerg Array.moveInto(Result.getStructField(1)); 9996 1.1 joerg } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType())) 9997 1.1 joerg // Length. 9998 1.1 joerg Result.getStructField(1) = APValue(APSInt(ArrayType->getSize())); 9999 1.1 joerg else 10000 1.1.1.2 joerg return InvalidType(); 10001 1.1 joerg 10002 1.1 joerg if (++Field != Record->field_end()) 10003 1.1.1.2 joerg return InvalidType(); 10004 1.1 joerg 10005 1.1 joerg return true; 10006 1.1 joerg } 10007 1.1 joerg 10008 1.1 joerg bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) { 10009 1.1 joerg const CXXRecordDecl *ClosureClass = E->getLambdaClass(); 10010 1.1 joerg if (ClosureClass->isInvalidDecl()) 10011 1.1 joerg return false; 10012 1.1 joerg 10013 1.1 joerg const size_t NumFields = 10014 1.1 joerg std::distance(ClosureClass->field_begin(), ClosureClass->field_end()); 10015 1.1 joerg 10016 1.1 joerg assert(NumFields == (size_t)std::distance(E->capture_init_begin(), 10017 1.1 joerg E->capture_init_end()) && 10018 1.1 joerg "The number of lambda capture initializers should equal the number of " 10019 1.1 joerg "fields within the closure type"); 10020 1.1 joerg 10021 1.1 joerg Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields); 10022 1.1 joerg // Iterate through all the lambda's closure object's fields and initialize 10023 1.1 joerg // them. 10024 1.1 joerg auto *CaptureInitIt = E->capture_init_begin(); 10025 1.1 joerg const LambdaCapture *CaptureIt = ClosureClass->captures_begin(); 10026 1.1 joerg bool Success = true; 10027 1.1.1.2 joerg const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(ClosureClass); 10028 1.1 joerg for (const auto *Field : ClosureClass->fields()) { 10029 1.1 joerg assert(CaptureInitIt != E->capture_init_end()); 10030 1.1 joerg // Get the initializer for this field 10031 1.1 joerg Expr *const CurFieldInit = *CaptureInitIt++; 10032 1.1 joerg 10033 1.1 joerg // If there is no initializer, either this is a VLA or an error has 10034 1.1 joerg // occurred. 10035 1.1 joerg if (!CurFieldInit) 10036 1.1 joerg return Error(E); 10037 1.1 joerg 10038 1.1.1.2 joerg LValue Subobject = This; 10039 1.1.1.2 joerg 10040 1.1.1.2 joerg if (!HandleLValueMember(Info, E, Subobject, Field, &Layout)) 10041 1.1.1.2 joerg return false; 10042 1.1.1.2 joerg 10043 1.1 joerg APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); 10044 1.1.1.2 joerg if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) { 10045 1.1 joerg if (!Info.keepEvaluatingAfterFailure()) 10046 1.1 joerg return false; 10047 1.1 joerg Success = false; 10048 1.1 joerg } 10049 1.1 joerg ++CaptureIt; 10050 1.1 joerg } 10051 1.1 joerg return Success; 10052 1.1 joerg } 10053 1.1 joerg 10054 1.1 joerg static bool EvaluateRecord(const Expr *E, const LValue &This, 10055 1.1 joerg APValue &Result, EvalInfo &Info) { 10056 1.1.1.2 joerg assert(!E->isValueDependent()); 10057 1.1 joerg assert(E->isRValue() && E->getType()->isRecordType() && 10058 1.1 joerg "can't evaluate expression as a record rvalue"); 10059 1.1 joerg return RecordExprEvaluator(Info, This, Result).Visit(E); 10060 1.1 joerg } 10061 1.1 joerg 10062 1.1 joerg //===----------------------------------------------------------------------===// 10063 1.1 joerg // Temporary Evaluation 10064 1.1 joerg // 10065 1.1 joerg // Temporaries are represented in the AST as rvalues, but generally behave like 10066 1.1 joerg // lvalues. The full-object of which the temporary is a subobject is implicitly 10067 1.1 joerg // materialized so that a reference can bind to it. 10068 1.1 joerg //===----------------------------------------------------------------------===// 10069 1.1 joerg namespace { 10070 1.1 joerg class TemporaryExprEvaluator 10071 1.1 joerg : public LValueExprEvaluatorBase<TemporaryExprEvaluator> { 10072 1.1 joerg public: 10073 1.1 joerg TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) : 10074 1.1 joerg LValueExprEvaluatorBaseTy(Info, Result, false) {} 10075 1.1 joerg 10076 1.1 joerg /// Visit an expression which constructs the value of this temporary. 10077 1.1 joerg bool VisitConstructExpr(const Expr *E) { 10078 1.1.1.2 joerg APValue &Value = Info.CurrentCall->createTemporary( 10079 1.1.1.2 joerg E, E->getType(), ScopeKind::FullExpression, Result); 10080 1.1 joerg return EvaluateInPlace(Value, Info, Result, E); 10081 1.1 joerg } 10082 1.1 joerg 10083 1.1 joerg bool VisitCastExpr(const CastExpr *E) { 10084 1.1 joerg switch (E->getCastKind()) { 10085 1.1 joerg default: 10086 1.1 joerg return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 10087 1.1 joerg 10088 1.1 joerg case CK_ConstructorConversion: 10089 1.1 joerg return VisitConstructExpr(E->getSubExpr()); 10090 1.1 joerg } 10091 1.1 joerg } 10092 1.1 joerg bool VisitInitListExpr(const InitListExpr *E) { 10093 1.1 joerg return VisitConstructExpr(E); 10094 1.1 joerg } 10095 1.1 joerg bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 10096 1.1 joerg return VisitConstructExpr(E); 10097 1.1 joerg } 10098 1.1 joerg bool VisitCallExpr(const CallExpr *E) { 10099 1.1 joerg return VisitConstructExpr(E); 10100 1.1 joerg } 10101 1.1 joerg bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) { 10102 1.1 joerg return VisitConstructExpr(E); 10103 1.1 joerg } 10104 1.1 joerg bool VisitLambdaExpr(const LambdaExpr *E) { 10105 1.1 joerg return VisitConstructExpr(E); 10106 1.1 joerg } 10107 1.1 joerg }; 10108 1.1 joerg } // end anonymous namespace 10109 1.1 joerg 10110 1.1 joerg /// Evaluate an expression of record type as a temporary. 10111 1.1 joerg static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) { 10112 1.1.1.2 joerg assert(!E->isValueDependent()); 10113 1.1 joerg assert(E->isRValue() && E->getType()->isRecordType()); 10114 1.1 joerg return TemporaryExprEvaluator(Info, Result).Visit(E); 10115 1.1 joerg } 10116 1.1 joerg 10117 1.1 joerg //===----------------------------------------------------------------------===// 10118 1.1 joerg // Vector Evaluation 10119 1.1 joerg //===----------------------------------------------------------------------===// 10120 1.1 joerg 10121 1.1 joerg namespace { 10122 1.1 joerg class VectorExprEvaluator 10123 1.1 joerg : public ExprEvaluatorBase<VectorExprEvaluator> { 10124 1.1 joerg APValue &Result; 10125 1.1 joerg public: 10126 1.1 joerg 10127 1.1 joerg VectorExprEvaluator(EvalInfo &info, APValue &Result) 10128 1.1 joerg : ExprEvaluatorBaseTy(info), Result(Result) {} 10129 1.1 joerg 10130 1.1 joerg bool Success(ArrayRef<APValue> V, const Expr *E) { 10131 1.1 joerg assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements()); 10132 1.1 joerg // FIXME: remove this APValue copy. 10133 1.1 joerg Result = APValue(V.data(), V.size()); 10134 1.1 joerg return true; 10135 1.1 joerg } 10136 1.1 joerg bool Success(const APValue &V, const Expr *E) { 10137 1.1 joerg assert(V.isVector()); 10138 1.1 joerg Result = V; 10139 1.1 joerg return true; 10140 1.1 joerg } 10141 1.1 joerg bool ZeroInitialization(const Expr *E); 10142 1.1 joerg 10143 1.1 joerg bool VisitUnaryReal(const UnaryOperator *E) 10144 1.1 joerg { return Visit(E->getSubExpr()); } 10145 1.1 joerg bool VisitCastExpr(const CastExpr* E); 10146 1.1 joerg bool VisitInitListExpr(const InitListExpr *E); 10147 1.1 joerg bool VisitUnaryImag(const UnaryOperator *E); 10148 1.1.1.2 joerg bool VisitBinaryOperator(const BinaryOperator *E); 10149 1.1.1.2 joerg // FIXME: Missing: unary -, unary ~, conditional operator (for GNU 10150 1.1.1.2 joerg // conditional select), shufflevector, ExtVectorElementExpr 10151 1.1 joerg }; 10152 1.1 joerg } // end anonymous namespace 10153 1.1 joerg 10154 1.1 joerg static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) { 10155 1.1 joerg assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue"); 10156 1.1 joerg return VectorExprEvaluator(Info, Result).Visit(E); 10157 1.1 joerg } 10158 1.1 joerg 10159 1.1 joerg bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) { 10160 1.1 joerg const VectorType *VTy = E->getType()->castAs<VectorType>(); 10161 1.1 joerg unsigned NElts = VTy->getNumElements(); 10162 1.1 joerg 10163 1.1 joerg const Expr *SE = E->getSubExpr(); 10164 1.1 joerg QualType SETy = SE->getType(); 10165 1.1 joerg 10166 1.1 joerg switch (E->getCastKind()) { 10167 1.1 joerg case CK_VectorSplat: { 10168 1.1 joerg APValue Val = APValue(); 10169 1.1 joerg if (SETy->isIntegerType()) { 10170 1.1 joerg APSInt IntResult; 10171 1.1 joerg if (!EvaluateInteger(SE, IntResult, Info)) 10172 1.1 joerg return false; 10173 1.1 joerg Val = APValue(std::move(IntResult)); 10174 1.1 joerg } else if (SETy->isRealFloatingType()) { 10175 1.1 joerg APFloat FloatResult(0.0); 10176 1.1 joerg if (!EvaluateFloat(SE, FloatResult, Info)) 10177 1.1 joerg return false; 10178 1.1 joerg Val = APValue(std::move(FloatResult)); 10179 1.1 joerg } else { 10180 1.1 joerg return Error(E); 10181 1.1 joerg } 10182 1.1 joerg 10183 1.1 joerg // Splat and create vector APValue. 10184 1.1 joerg SmallVector<APValue, 4> Elts(NElts, Val); 10185 1.1 joerg return Success(Elts, E); 10186 1.1 joerg } 10187 1.1 joerg case CK_BitCast: { 10188 1.1 joerg // Evaluate the operand into an APInt we can extract from. 10189 1.1 joerg llvm::APInt SValInt; 10190 1.1 joerg if (!EvalAndBitcastToAPInt(Info, SE, SValInt)) 10191 1.1 joerg return false; 10192 1.1 joerg // Extract the elements 10193 1.1 joerg QualType EltTy = VTy->getElementType(); 10194 1.1 joerg unsigned EltSize = Info.Ctx.getTypeSize(EltTy); 10195 1.1 joerg bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 10196 1.1 joerg SmallVector<APValue, 4> Elts; 10197 1.1 joerg if (EltTy->isRealFloatingType()) { 10198 1.1 joerg const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy); 10199 1.1 joerg unsigned FloatEltSize = EltSize; 10200 1.1 joerg if (&Sem == &APFloat::x87DoubleExtended()) 10201 1.1 joerg FloatEltSize = 80; 10202 1.1 joerg for (unsigned i = 0; i < NElts; i++) { 10203 1.1 joerg llvm::APInt Elt; 10204 1.1 joerg if (BigEndian) 10205 1.1 joerg Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize); 10206 1.1 joerg else 10207 1.1 joerg Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize); 10208 1.1 joerg Elts.push_back(APValue(APFloat(Sem, Elt))); 10209 1.1 joerg } 10210 1.1 joerg } else if (EltTy->isIntegerType()) { 10211 1.1 joerg for (unsigned i = 0; i < NElts; i++) { 10212 1.1 joerg llvm::APInt Elt; 10213 1.1 joerg if (BigEndian) 10214 1.1 joerg Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize); 10215 1.1 joerg else 10216 1.1 joerg Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize); 10217 1.1.1.2 joerg Elts.push_back(APValue(APSInt(Elt, !EltTy->isSignedIntegerType()))); 10218 1.1 joerg } 10219 1.1 joerg } else { 10220 1.1 joerg return Error(E); 10221 1.1 joerg } 10222 1.1 joerg return Success(Elts, E); 10223 1.1 joerg } 10224 1.1 joerg default: 10225 1.1 joerg return ExprEvaluatorBaseTy::VisitCastExpr(E); 10226 1.1 joerg } 10227 1.1 joerg } 10228 1.1 joerg 10229 1.1 joerg bool 10230 1.1 joerg VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 10231 1.1 joerg const VectorType *VT = E->getType()->castAs<VectorType>(); 10232 1.1 joerg unsigned NumInits = E->getNumInits(); 10233 1.1 joerg unsigned NumElements = VT->getNumElements(); 10234 1.1 joerg 10235 1.1 joerg QualType EltTy = VT->getElementType(); 10236 1.1 joerg SmallVector<APValue, 4> Elements; 10237 1.1 joerg 10238 1.1 joerg // The number of initializers can be less than the number of 10239 1.1 joerg // vector elements. For OpenCL, this can be due to nested vector 10240 1.1 joerg // initialization. For GCC compatibility, missing trailing elements 10241 1.1 joerg // should be initialized with zeroes. 10242 1.1 joerg unsigned CountInits = 0, CountElts = 0; 10243 1.1 joerg while (CountElts < NumElements) { 10244 1.1 joerg // Handle nested vector initialization. 10245 1.1 joerg if (CountInits < NumInits 10246 1.1 joerg && E->getInit(CountInits)->getType()->isVectorType()) { 10247 1.1 joerg APValue v; 10248 1.1 joerg if (!EvaluateVector(E->getInit(CountInits), v, Info)) 10249 1.1 joerg return Error(E); 10250 1.1 joerg unsigned vlen = v.getVectorLength(); 10251 1.1 joerg for (unsigned j = 0; j < vlen; j++) 10252 1.1 joerg Elements.push_back(v.getVectorElt(j)); 10253 1.1 joerg CountElts += vlen; 10254 1.1 joerg } else if (EltTy->isIntegerType()) { 10255 1.1 joerg llvm::APSInt sInt(32); 10256 1.1 joerg if (CountInits < NumInits) { 10257 1.1 joerg if (!EvaluateInteger(E->getInit(CountInits), sInt, Info)) 10258 1.1 joerg return false; 10259 1.1 joerg } else // trailing integer zero. 10260 1.1 joerg sInt = Info.Ctx.MakeIntValue(0, EltTy); 10261 1.1 joerg Elements.push_back(APValue(sInt)); 10262 1.1 joerg CountElts++; 10263 1.1 joerg } else { 10264 1.1 joerg llvm::APFloat f(0.0); 10265 1.1 joerg if (CountInits < NumInits) { 10266 1.1 joerg if (!EvaluateFloat(E->getInit(CountInits), f, Info)) 10267 1.1 joerg return false; 10268 1.1 joerg } else // trailing float zero. 10269 1.1 joerg f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)); 10270 1.1 joerg Elements.push_back(APValue(f)); 10271 1.1 joerg CountElts++; 10272 1.1 joerg } 10273 1.1 joerg CountInits++; 10274 1.1 joerg } 10275 1.1 joerg return Success(Elements, E); 10276 1.1 joerg } 10277 1.1 joerg 10278 1.1 joerg bool 10279 1.1 joerg VectorExprEvaluator::ZeroInitialization(const Expr *E) { 10280 1.1 joerg const auto *VT = E->getType()->castAs<VectorType>(); 10281 1.1 joerg QualType EltTy = VT->getElementType(); 10282 1.1 joerg APValue ZeroElement; 10283 1.1 joerg if (EltTy->isIntegerType()) 10284 1.1 joerg ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy)); 10285 1.1 joerg else 10286 1.1 joerg ZeroElement = 10287 1.1 joerg APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy))); 10288 1.1 joerg 10289 1.1 joerg SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement); 10290 1.1 joerg return Success(Elements, E); 10291 1.1 joerg } 10292 1.1 joerg 10293 1.1 joerg bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 10294 1.1 joerg VisitIgnoredValue(E->getSubExpr()); 10295 1.1 joerg return ZeroInitialization(E); 10296 1.1 joerg } 10297 1.1 joerg 10298 1.1.1.2 joerg bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 10299 1.1.1.2 joerg BinaryOperatorKind Op = E->getOpcode(); 10300 1.1.1.2 joerg assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp && 10301 1.1.1.2 joerg "Operation not supported on vector types"); 10302 1.1.1.2 joerg 10303 1.1.1.2 joerg if (Op == BO_Comma) 10304 1.1.1.2 joerg return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 10305 1.1.1.2 joerg 10306 1.1.1.2 joerg Expr *LHS = E->getLHS(); 10307 1.1.1.2 joerg Expr *RHS = E->getRHS(); 10308 1.1.1.2 joerg 10309 1.1.1.2 joerg assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() && 10310 1.1.1.2 joerg "Must both be vector types"); 10311 1.1.1.2 joerg // Checking JUST the types are the same would be fine, except shifts don't 10312 1.1.1.2 joerg // need to have their types be the same (since you always shift by an int). 10313 1.1.1.2 joerg assert(LHS->getType()->castAs<VectorType>()->getNumElements() == 10314 1.1.1.2 joerg E->getType()->castAs<VectorType>()->getNumElements() && 10315 1.1.1.2 joerg RHS->getType()->castAs<VectorType>()->getNumElements() == 10316 1.1.1.2 joerg E->getType()->castAs<VectorType>()->getNumElements() && 10317 1.1.1.2 joerg "All operands must be the same size."); 10318 1.1.1.2 joerg 10319 1.1.1.2 joerg APValue LHSValue; 10320 1.1.1.2 joerg APValue RHSValue; 10321 1.1.1.2 joerg bool LHSOK = Evaluate(LHSValue, Info, LHS); 10322 1.1.1.2 joerg if (!LHSOK && !Info.noteFailure()) 10323 1.1.1.2 joerg return false; 10324 1.1.1.2 joerg if (!Evaluate(RHSValue, Info, RHS) || !LHSOK) 10325 1.1.1.2 joerg return false; 10326 1.1.1.2 joerg 10327 1.1.1.2 joerg if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue)) 10328 1.1.1.2 joerg return false; 10329 1.1.1.2 joerg 10330 1.1.1.2 joerg return Success(LHSValue, E); 10331 1.1.1.2 joerg } 10332 1.1.1.2 joerg 10333 1.1 joerg //===----------------------------------------------------------------------===// 10334 1.1 joerg // Array Evaluation 10335 1.1 joerg //===----------------------------------------------------------------------===// 10336 1.1 joerg 10337 1.1 joerg namespace { 10338 1.1 joerg class ArrayExprEvaluator 10339 1.1 joerg : public ExprEvaluatorBase<ArrayExprEvaluator> { 10340 1.1 joerg const LValue &This; 10341 1.1 joerg APValue &Result; 10342 1.1 joerg public: 10343 1.1 joerg 10344 1.1 joerg ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result) 10345 1.1 joerg : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 10346 1.1 joerg 10347 1.1 joerg bool Success(const APValue &V, const Expr *E) { 10348 1.1 joerg assert(V.isArray() && "expected array"); 10349 1.1 joerg Result = V; 10350 1.1 joerg return true; 10351 1.1 joerg } 10352 1.1 joerg 10353 1.1 joerg bool ZeroInitialization(const Expr *E) { 10354 1.1 joerg const ConstantArrayType *CAT = 10355 1.1 joerg Info.Ctx.getAsConstantArrayType(E->getType()); 10356 1.1.1.2 joerg if (!CAT) { 10357 1.1.1.2 joerg if (E->getType()->isIncompleteArrayType()) { 10358 1.1.1.2 joerg // We can be asked to zero-initialize a flexible array member; this 10359 1.1.1.2 joerg // is represented as an ImplicitValueInitExpr of incomplete array 10360 1.1.1.2 joerg // type. In this case, the array has zero elements. 10361 1.1.1.2 joerg Result = APValue(APValue::UninitArray(), 0, 0); 10362 1.1.1.2 joerg return true; 10363 1.1.1.2 joerg } 10364 1.1.1.2 joerg // FIXME: We could handle VLAs here. 10365 1.1 joerg return Error(E); 10366 1.1.1.2 joerg } 10367 1.1 joerg 10368 1.1 joerg Result = APValue(APValue::UninitArray(), 0, 10369 1.1 joerg CAT->getSize().getZExtValue()); 10370 1.1 joerg if (!Result.hasArrayFiller()) return true; 10371 1.1 joerg 10372 1.1 joerg // Zero-initialize all elements. 10373 1.1 joerg LValue Subobject = This; 10374 1.1 joerg Subobject.addArray(Info, E, CAT); 10375 1.1 joerg ImplicitValueInitExpr VIE(CAT->getElementType()); 10376 1.1 joerg return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE); 10377 1.1 joerg } 10378 1.1 joerg 10379 1.1 joerg bool VisitCallExpr(const CallExpr *E) { 10380 1.1 joerg return handleCallExpr(E, Result, &This); 10381 1.1 joerg } 10382 1.1 joerg bool VisitInitListExpr(const InitListExpr *E, 10383 1.1 joerg QualType AllocType = QualType()); 10384 1.1 joerg bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E); 10385 1.1 joerg bool VisitCXXConstructExpr(const CXXConstructExpr *E); 10386 1.1 joerg bool VisitCXXConstructExpr(const CXXConstructExpr *E, 10387 1.1 joerg const LValue &Subobject, 10388 1.1 joerg APValue *Value, QualType Type); 10389 1.1 joerg bool VisitStringLiteral(const StringLiteral *E, 10390 1.1 joerg QualType AllocType = QualType()) { 10391 1.1 joerg expandStringLiteral(Info, E, Result, AllocType); 10392 1.1 joerg return true; 10393 1.1 joerg } 10394 1.1 joerg }; 10395 1.1 joerg } // end anonymous namespace 10396 1.1 joerg 10397 1.1 joerg static bool EvaluateArray(const Expr *E, const LValue &This, 10398 1.1 joerg APValue &Result, EvalInfo &Info) { 10399 1.1.1.2 joerg assert(!E->isValueDependent()); 10400 1.1 joerg assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue"); 10401 1.1 joerg return ArrayExprEvaluator(Info, This, Result).Visit(E); 10402 1.1 joerg } 10403 1.1 joerg 10404 1.1 joerg static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, 10405 1.1 joerg APValue &Result, const InitListExpr *ILE, 10406 1.1 joerg QualType AllocType) { 10407 1.1.1.2 joerg assert(!ILE->isValueDependent()); 10408 1.1 joerg assert(ILE->isRValue() && ILE->getType()->isArrayType() && 10409 1.1 joerg "not an array rvalue"); 10410 1.1 joerg return ArrayExprEvaluator(Info, This, Result) 10411 1.1 joerg .VisitInitListExpr(ILE, AllocType); 10412 1.1 joerg } 10413 1.1 joerg 10414 1.1.1.2 joerg static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This, 10415 1.1.1.2 joerg APValue &Result, 10416 1.1.1.2 joerg const CXXConstructExpr *CCE, 10417 1.1.1.2 joerg QualType AllocType) { 10418 1.1.1.2 joerg assert(!CCE->isValueDependent()); 10419 1.1.1.2 joerg assert(CCE->isRValue() && CCE->getType()->isArrayType() && 10420 1.1.1.2 joerg "not an array rvalue"); 10421 1.1.1.2 joerg return ArrayExprEvaluator(Info, This, Result) 10422 1.1.1.2 joerg .VisitCXXConstructExpr(CCE, This, &Result, AllocType); 10423 1.1.1.2 joerg } 10424 1.1.1.2 joerg 10425 1.1 joerg // Return true iff the given array filler may depend on the element index. 10426 1.1 joerg static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) { 10427 1.1.1.2 joerg // For now, just allow non-class value-initialization and initialization 10428 1.1 joerg // lists comprised of them. 10429 1.1 joerg if (isa<ImplicitValueInitExpr>(FillerExpr)) 10430 1.1 joerg return false; 10431 1.1 joerg if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) { 10432 1.1 joerg for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) { 10433 1.1 joerg if (MaybeElementDependentArrayFiller(ILE->getInit(I))) 10434 1.1 joerg return true; 10435 1.1 joerg } 10436 1.1 joerg return false; 10437 1.1 joerg } 10438 1.1 joerg return true; 10439 1.1 joerg } 10440 1.1 joerg 10441 1.1 joerg bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E, 10442 1.1 joerg QualType AllocType) { 10443 1.1 joerg const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType( 10444 1.1 joerg AllocType.isNull() ? E->getType() : AllocType); 10445 1.1 joerg if (!CAT) 10446 1.1 joerg return Error(E); 10447 1.1 joerg 10448 1.1 joerg // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...] 10449 1.1 joerg // an appropriately-typed string literal enclosed in braces. 10450 1.1 joerg if (E->isStringLiteralInit()) { 10451 1.1 joerg auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParens()); 10452 1.1 joerg // FIXME: Support ObjCEncodeExpr here once we support it in 10453 1.1 joerg // ArrayExprEvaluator generally. 10454 1.1 joerg if (!SL) 10455 1.1 joerg return Error(E); 10456 1.1 joerg return VisitStringLiteral(SL, AllocType); 10457 1.1 joerg } 10458 1.1 joerg 10459 1.1 joerg bool Success = true; 10460 1.1 joerg 10461 1.1 joerg assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) && 10462 1.1 joerg "zero-initialized array shouldn't have any initialized elts"); 10463 1.1 joerg APValue Filler; 10464 1.1 joerg if (Result.isArray() && Result.hasArrayFiller()) 10465 1.1 joerg Filler = Result.getArrayFiller(); 10466 1.1 joerg 10467 1.1 joerg unsigned NumEltsToInit = E->getNumInits(); 10468 1.1 joerg unsigned NumElts = CAT->getSize().getZExtValue(); 10469 1.1 joerg const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr; 10470 1.1 joerg 10471 1.1 joerg // If the initializer might depend on the array index, run it for each 10472 1.1 joerg // array element. 10473 1.1 joerg if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr)) 10474 1.1 joerg NumEltsToInit = NumElts; 10475 1.1 joerg 10476 1.1 joerg LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: " 10477 1.1 joerg << NumEltsToInit << ".\n"); 10478 1.1 joerg 10479 1.1 joerg Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts); 10480 1.1 joerg 10481 1.1 joerg // If the array was previously zero-initialized, preserve the 10482 1.1 joerg // zero-initialized values. 10483 1.1 joerg if (Filler.hasValue()) { 10484 1.1 joerg for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I) 10485 1.1 joerg Result.getArrayInitializedElt(I) = Filler; 10486 1.1 joerg if (Result.hasArrayFiller()) 10487 1.1 joerg Result.getArrayFiller() = Filler; 10488 1.1 joerg } 10489 1.1 joerg 10490 1.1 joerg LValue Subobject = This; 10491 1.1 joerg Subobject.addArray(Info, E, CAT); 10492 1.1 joerg for (unsigned Index = 0; Index != NumEltsToInit; ++Index) { 10493 1.1 joerg const Expr *Init = 10494 1.1 joerg Index < E->getNumInits() ? E->getInit(Index) : FillerExpr; 10495 1.1 joerg if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 10496 1.1 joerg Info, Subobject, Init) || 10497 1.1 joerg !HandleLValueArrayAdjustment(Info, Init, Subobject, 10498 1.1 joerg CAT->getElementType(), 1)) { 10499 1.1 joerg if (!Info.noteFailure()) 10500 1.1 joerg return false; 10501 1.1 joerg Success = false; 10502 1.1 joerg } 10503 1.1 joerg } 10504 1.1 joerg 10505 1.1 joerg if (!Result.hasArrayFiller()) 10506 1.1 joerg return Success; 10507 1.1 joerg 10508 1.1 joerg // If we get here, we have a trivial filler, which we can just evaluate 10509 1.1 joerg // once and splat over the rest of the array elements. 10510 1.1 joerg assert(FillerExpr && "no array filler for incomplete init list"); 10511 1.1 joerg return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, 10512 1.1 joerg FillerExpr) && Success; 10513 1.1 joerg } 10514 1.1 joerg 10515 1.1 joerg bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) { 10516 1.1 joerg LValue CommonLV; 10517 1.1 joerg if (E->getCommonExpr() && 10518 1.1 joerg !Evaluate(Info.CurrentCall->createTemporary( 10519 1.1 joerg E->getCommonExpr(), 10520 1.1.1.2 joerg getStorageType(Info.Ctx, E->getCommonExpr()), 10521 1.1.1.2 joerg ScopeKind::FullExpression, CommonLV), 10522 1.1 joerg Info, E->getCommonExpr()->getSourceExpr())) 10523 1.1 joerg return false; 10524 1.1 joerg 10525 1.1 joerg auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe()); 10526 1.1 joerg 10527 1.1 joerg uint64_t Elements = CAT->getSize().getZExtValue(); 10528 1.1 joerg Result = APValue(APValue::UninitArray(), Elements, Elements); 10529 1.1 joerg 10530 1.1 joerg LValue Subobject = This; 10531 1.1 joerg Subobject.addArray(Info, E, CAT); 10532 1.1 joerg 10533 1.1 joerg bool Success = true; 10534 1.1 joerg for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) { 10535 1.1 joerg if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 10536 1.1 joerg Info, Subobject, E->getSubExpr()) || 10537 1.1 joerg !HandleLValueArrayAdjustment(Info, E, Subobject, 10538 1.1 joerg CAT->getElementType(), 1)) { 10539 1.1 joerg if (!Info.noteFailure()) 10540 1.1 joerg return false; 10541 1.1 joerg Success = false; 10542 1.1 joerg } 10543 1.1 joerg } 10544 1.1 joerg 10545 1.1 joerg return Success; 10546 1.1 joerg } 10547 1.1 joerg 10548 1.1 joerg bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) { 10549 1.1 joerg return VisitCXXConstructExpr(E, This, &Result, E->getType()); 10550 1.1 joerg } 10551 1.1 joerg 10552 1.1 joerg bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 10553 1.1 joerg const LValue &Subobject, 10554 1.1 joerg APValue *Value, 10555 1.1 joerg QualType Type) { 10556 1.1 joerg bool HadZeroInit = Value->hasValue(); 10557 1.1 joerg 10558 1.1 joerg if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) { 10559 1.1 joerg unsigned N = CAT->getSize().getZExtValue(); 10560 1.1 joerg 10561 1.1 joerg // Preserve the array filler if we had prior zero-initialization. 10562 1.1 joerg APValue Filler = 10563 1.1 joerg HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller() 10564 1.1 joerg : APValue(); 10565 1.1 joerg 10566 1.1 joerg *Value = APValue(APValue::UninitArray(), N, N); 10567 1.1 joerg 10568 1.1 joerg if (HadZeroInit) 10569 1.1 joerg for (unsigned I = 0; I != N; ++I) 10570 1.1 joerg Value->getArrayInitializedElt(I) = Filler; 10571 1.1 joerg 10572 1.1 joerg // Initialize the elements. 10573 1.1 joerg LValue ArrayElt = Subobject; 10574 1.1 joerg ArrayElt.addArray(Info, E, CAT); 10575 1.1 joerg for (unsigned I = 0; I != N; ++I) 10576 1.1 joerg if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I), 10577 1.1 joerg CAT->getElementType()) || 10578 1.1 joerg !HandleLValueArrayAdjustment(Info, E, ArrayElt, 10579 1.1 joerg CAT->getElementType(), 1)) 10580 1.1 joerg return false; 10581 1.1 joerg 10582 1.1 joerg return true; 10583 1.1 joerg } 10584 1.1 joerg 10585 1.1 joerg if (!Type->isRecordType()) 10586 1.1 joerg return Error(E); 10587 1.1 joerg 10588 1.1 joerg return RecordExprEvaluator(Info, Subobject, *Value) 10589 1.1 joerg .VisitCXXConstructExpr(E, Type); 10590 1.1 joerg } 10591 1.1 joerg 10592 1.1 joerg //===----------------------------------------------------------------------===// 10593 1.1 joerg // Integer Evaluation 10594 1.1 joerg // 10595 1.1 joerg // As a GNU extension, we support casting pointers to sufficiently-wide integer 10596 1.1 joerg // types and back in constant folding. Integer values are thus represented 10597 1.1 joerg // either as an integer-valued APValue, or as an lvalue-valued APValue. 10598 1.1 joerg //===----------------------------------------------------------------------===// 10599 1.1 joerg 10600 1.1 joerg namespace { 10601 1.1 joerg class IntExprEvaluator 10602 1.1 joerg : public ExprEvaluatorBase<IntExprEvaluator> { 10603 1.1 joerg APValue &Result; 10604 1.1 joerg public: 10605 1.1 joerg IntExprEvaluator(EvalInfo &info, APValue &result) 10606 1.1 joerg : ExprEvaluatorBaseTy(info), Result(result) {} 10607 1.1 joerg 10608 1.1 joerg bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) { 10609 1.1 joerg assert(E->getType()->isIntegralOrEnumerationType() && 10610 1.1 joerg "Invalid evaluation result."); 10611 1.1 joerg assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() && 10612 1.1 joerg "Invalid evaluation result."); 10613 1.1 joerg assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 10614 1.1 joerg "Invalid evaluation result."); 10615 1.1 joerg Result = APValue(SI); 10616 1.1 joerg return true; 10617 1.1 joerg } 10618 1.1 joerg bool Success(const llvm::APSInt &SI, const Expr *E) { 10619 1.1 joerg return Success(SI, E, Result); 10620 1.1 joerg } 10621 1.1 joerg 10622 1.1 joerg bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) { 10623 1.1 joerg assert(E->getType()->isIntegralOrEnumerationType() && 10624 1.1 joerg "Invalid evaluation result."); 10625 1.1 joerg assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 10626 1.1 joerg "Invalid evaluation result."); 10627 1.1 joerg Result = APValue(APSInt(I)); 10628 1.1 joerg Result.getInt().setIsUnsigned( 10629 1.1 joerg E->getType()->isUnsignedIntegerOrEnumerationType()); 10630 1.1 joerg return true; 10631 1.1 joerg } 10632 1.1 joerg bool Success(const llvm::APInt &I, const Expr *E) { 10633 1.1 joerg return Success(I, E, Result); 10634 1.1 joerg } 10635 1.1 joerg 10636 1.1 joerg bool Success(uint64_t Value, const Expr *E, APValue &Result) { 10637 1.1 joerg assert(E->getType()->isIntegralOrEnumerationType() && 10638 1.1 joerg "Invalid evaluation result."); 10639 1.1 joerg Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType())); 10640 1.1 joerg return true; 10641 1.1 joerg } 10642 1.1 joerg bool Success(uint64_t Value, const Expr *E) { 10643 1.1 joerg return Success(Value, E, Result); 10644 1.1 joerg } 10645 1.1 joerg 10646 1.1 joerg bool Success(CharUnits Size, const Expr *E) { 10647 1.1 joerg return Success(Size.getQuantity(), E); 10648 1.1 joerg } 10649 1.1 joerg 10650 1.1 joerg bool Success(const APValue &V, const Expr *E) { 10651 1.1 joerg if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) { 10652 1.1 joerg Result = V; 10653 1.1 joerg return true; 10654 1.1 joerg } 10655 1.1 joerg return Success(V.getInt(), E); 10656 1.1 joerg } 10657 1.1 joerg 10658 1.1 joerg bool ZeroInitialization(const Expr *E) { return Success(0, E); } 10659 1.1 joerg 10660 1.1 joerg //===--------------------------------------------------------------------===// 10661 1.1 joerg // Visitor Methods 10662 1.1 joerg //===--------------------------------------------------------------------===// 10663 1.1 joerg 10664 1.1 joerg bool VisitIntegerLiteral(const IntegerLiteral *E) { 10665 1.1 joerg return Success(E->getValue(), E); 10666 1.1 joerg } 10667 1.1 joerg bool VisitCharacterLiteral(const CharacterLiteral *E) { 10668 1.1 joerg return Success(E->getValue(), E); 10669 1.1 joerg } 10670 1.1 joerg 10671 1.1 joerg bool CheckReferencedDecl(const Expr *E, const Decl *D); 10672 1.1 joerg bool VisitDeclRefExpr(const DeclRefExpr *E) { 10673 1.1 joerg if (CheckReferencedDecl(E, E->getDecl())) 10674 1.1 joerg return true; 10675 1.1 joerg 10676 1.1 joerg return ExprEvaluatorBaseTy::VisitDeclRefExpr(E); 10677 1.1 joerg } 10678 1.1 joerg bool VisitMemberExpr(const MemberExpr *E) { 10679 1.1 joerg if (CheckReferencedDecl(E, E->getMemberDecl())) { 10680 1.1 joerg VisitIgnoredBaseExpression(E->getBase()); 10681 1.1 joerg return true; 10682 1.1 joerg } 10683 1.1 joerg 10684 1.1 joerg return ExprEvaluatorBaseTy::VisitMemberExpr(E); 10685 1.1 joerg } 10686 1.1 joerg 10687 1.1 joerg bool VisitCallExpr(const CallExpr *E); 10688 1.1 joerg bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); 10689 1.1 joerg bool VisitBinaryOperator(const BinaryOperator *E); 10690 1.1 joerg bool VisitOffsetOfExpr(const OffsetOfExpr *E); 10691 1.1 joerg bool VisitUnaryOperator(const UnaryOperator *E); 10692 1.1 joerg 10693 1.1 joerg bool VisitCastExpr(const CastExpr* E); 10694 1.1 joerg bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E); 10695 1.1 joerg 10696 1.1 joerg bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) { 10697 1.1 joerg return Success(E->getValue(), E); 10698 1.1 joerg } 10699 1.1 joerg 10700 1.1 joerg bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) { 10701 1.1 joerg return Success(E->getValue(), E); 10702 1.1 joerg } 10703 1.1 joerg 10704 1.1 joerg bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) { 10705 1.1 joerg if (Info.ArrayInitIndex == uint64_t(-1)) { 10706 1.1 joerg // We were asked to evaluate this subexpression independent of the 10707 1.1 joerg // enclosing ArrayInitLoopExpr. We can't do that. 10708 1.1 joerg Info.FFDiag(E); 10709 1.1 joerg return false; 10710 1.1 joerg } 10711 1.1 joerg return Success(Info.ArrayInitIndex, E); 10712 1.1 joerg } 10713 1.1 joerg 10714 1.1 joerg // Note, GNU defines __null as an integer, not a pointer. 10715 1.1 joerg bool VisitGNUNullExpr(const GNUNullExpr *E) { 10716 1.1 joerg return ZeroInitialization(E); 10717 1.1 joerg } 10718 1.1 joerg 10719 1.1 joerg bool VisitTypeTraitExpr(const TypeTraitExpr *E) { 10720 1.1 joerg return Success(E->getValue(), E); 10721 1.1 joerg } 10722 1.1 joerg 10723 1.1 joerg bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) { 10724 1.1 joerg return Success(E->getValue(), E); 10725 1.1 joerg } 10726 1.1 joerg 10727 1.1 joerg bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) { 10728 1.1 joerg return Success(E->getValue(), E); 10729 1.1 joerg } 10730 1.1 joerg 10731 1.1 joerg bool VisitUnaryReal(const UnaryOperator *E); 10732 1.1 joerg bool VisitUnaryImag(const UnaryOperator *E); 10733 1.1 joerg 10734 1.1 joerg bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E); 10735 1.1 joerg bool VisitSizeOfPackExpr(const SizeOfPackExpr *E); 10736 1.1 joerg bool VisitSourceLocExpr(const SourceLocExpr *E); 10737 1.1 joerg bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E); 10738 1.1.1.2 joerg bool VisitRequiresExpr(const RequiresExpr *E); 10739 1.1 joerg // FIXME: Missing: array subscript of vector, member of vector 10740 1.1 joerg }; 10741 1.1 joerg 10742 1.1 joerg class FixedPointExprEvaluator 10743 1.1 joerg : public ExprEvaluatorBase<FixedPointExprEvaluator> { 10744 1.1 joerg APValue &Result; 10745 1.1 joerg 10746 1.1 joerg public: 10747 1.1 joerg FixedPointExprEvaluator(EvalInfo &info, APValue &result) 10748 1.1 joerg : ExprEvaluatorBaseTy(info), Result(result) {} 10749 1.1 joerg 10750 1.1 joerg bool Success(const llvm::APInt &I, const Expr *E) { 10751 1.1 joerg return Success( 10752 1.1 joerg APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E); 10753 1.1 joerg } 10754 1.1 joerg 10755 1.1 joerg bool Success(uint64_t Value, const Expr *E) { 10756 1.1 joerg return Success( 10757 1.1 joerg APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E); 10758 1.1 joerg } 10759 1.1 joerg 10760 1.1 joerg bool Success(const APValue &V, const Expr *E) { 10761 1.1 joerg return Success(V.getFixedPoint(), E); 10762 1.1 joerg } 10763 1.1 joerg 10764 1.1 joerg bool Success(const APFixedPoint &V, const Expr *E) { 10765 1.1 joerg assert(E->getType()->isFixedPointType() && "Invalid evaluation result."); 10766 1.1 joerg assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) && 10767 1.1 joerg "Invalid evaluation result."); 10768 1.1 joerg Result = APValue(V); 10769 1.1 joerg return true; 10770 1.1 joerg } 10771 1.1 joerg 10772 1.1 joerg //===--------------------------------------------------------------------===// 10773 1.1 joerg // Visitor Methods 10774 1.1 joerg //===--------------------------------------------------------------------===// 10775 1.1 joerg 10776 1.1 joerg bool VisitFixedPointLiteral(const FixedPointLiteral *E) { 10777 1.1 joerg return Success(E->getValue(), E); 10778 1.1 joerg } 10779 1.1 joerg 10780 1.1 joerg bool VisitCastExpr(const CastExpr *E); 10781 1.1 joerg bool VisitUnaryOperator(const UnaryOperator *E); 10782 1.1 joerg bool VisitBinaryOperator(const BinaryOperator *E); 10783 1.1 joerg }; 10784 1.1 joerg } // end anonymous namespace 10785 1.1 joerg 10786 1.1 joerg /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and 10787 1.1 joerg /// produce either the integer value or a pointer. 10788 1.1 joerg /// 10789 1.1 joerg /// GCC has a heinous extension which folds casts between pointer types and 10790 1.1 joerg /// pointer-sized integral types. We support this by allowing the evaluation of 10791 1.1 joerg /// an integer rvalue to produce a pointer (represented as an lvalue) instead. 10792 1.1 joerg /// Some simple arithmetic on such values is supported (they are treated much 10793 1.1 joerg /// like char*). 10794 1.1 joerg static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, 10795 1.1 joerg EvalInfo &Info) { 10796 1.1.1.2 joerg assert(!E->isValueDependent()); 10797 1.1 joerg assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType()); 10798 1.1 joerg return IntExprEvaluator(Info, Result).Visit(E); 10799 1.1 joerg } 10800 1.1 joerg 10801 1.1 joerg static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) { 10802 1.1.1.2 joerg assert(!E->isValueDependent()); 10803 1.1 joerg APValue Val; 10804 1.1 joerg if (!EvaluateIntegerOrLValue(E, Val, Info)) 10805 1.1 joerg return false; 10806 1.1 joerg if (!Val.isInt()) { 10807 1.1 joerg // FIXME: It would be better to produce the diagnostic for casting 10808 1.1 joerg // a pointer to an integer. 10809 1.1 joerg Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 10810 1.1 joerg return false; 10811 1.1 joerg } 10812 1.1 joerg Result = Val.getInt(); 10813 1.1 joerg return true; 10814 1.1 joerg } 10815 1.1 joerg 10816 1.1 joerg bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) { 10817 1.1 joerg APValue Evaluated = E->EvaluateInContext( 10818 1.1 joerg Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr()); 10819 1.1 joerg return Success(Evaluated, E); 10820 1.1 joerg } 10821 1.1 joerg 10822 1.1 joerg static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, 10823 1.1 joerg EvalInfo &Info) { 10824 1.1.1.2 joerg assert(!E->isValueDependent()); 10825 1.1 joerg if (E->getType()->isFixedPointType()) { 10826 1.1 joerg APValue Val; 10827 1.1 joerg if (!FixedPointExprEvaluator(Info, Val).Visit(E)) 10828 1.1 joerg return false; 10829 1.1 joerg if (!Val.isFixedPoint()) 10830 1.1 joerg return false; 10831 1.1 joerg 10832 1.1 joerg Result = Val.getFixedPoint(); 10833 1.1 joerg return true; 10834 1.1 joerg } 10835 1.1 joerg return false; 10836 1.1 joerg } 10837 1.1 joerg 10838 1.1 joerg static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, 10839 1.1 joerg EvalInfo &Info) { 10840 1.1.1.2 joerg assert(!E->isValueDependent()); 10841 1.1 joerg if (E->getType()->isIntegerType()) { 10842 1.1 joerg auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType()); 10843 1.1 joerg APSInt Val; 10844 1.1 joerg if (!EvaluateInteger(E, Val, Info)) 10845 1.1 joerg return false; 10846 1.1 joerg Result = APFixedPoint(Val, FXSema); 10847 1.1 joerg return true; 10848 1.1 joerg } else if (E->getType()->isFixedPointType()) { 10849 1.1 joerg return EvaluateFixedPoint(E, Result, Info); 10850 1.1 joerg } 10851 1.1 joerg return false; 10852 1.1 joerg } 10853 1.1 joerg 10854 1.1 joerg /// Check whether the given declaration can be directly converted to an integral 10855 1.1 joerg /// rvalue. If not, no diagnostic is produced; there are other things we can 10856 1.1 joerg /// try. 10857 1.1 joerg bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) { 10858 1.1 joerg // Enums are integer constant exprs. 10859 1.1 joerg if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) { 10860 1.1 joerg // Check for signedness/width mismatches between E type and ECD value. 10861 1.1 joerg bool SameSign = (ECD->getInitVal().isSigned() 10862 1.1 joerg == E->getType()->isSignedIntegerOrEnumerationType()); 10863 1.1 joerg bool SameWidth = (ECD->getInitVal().getBitWidth() 10864 1.1 joerg == Info.Ctx.getIntWidth(E->getType())); 10865 1.1 joerg if (SameSign && SameWidth) 10866 1.1 joerg return Success(ECD->getInitVal(), E); 10867 1.1 joerg else { 10868 1.1 joerg // Get rid of mismatch (otherwise Success assertions will fail) 10869 1.1 joerg // by computing a new value matching the type of E. 10870 1.1 joerg llvm::APSInt Val = ECD->getInitVal(); 10871 1.1 joerg if (!SameSign) 10872 1.1 joerg Val.setIsSigned(!ECD->getInitVal().isSigned()); 10873 1.1 joerg if (!SameWidth) 10874 1.1 joerg Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType())); 10875 1.1 joerg return Success(Val, E); 10876 1.1 joerg } 10877 1.1 joerg } 10878 1.1 joerg return false; 10879 1.1 joerg } 10880 1.1 joerg 10881 1.1 joerg /// Values returned by __builtin_classify_type, chosen to match the values 10882 1.1 joerg /// produced by GCC's builtin. 10883 1.1 joerg enum class GCCTypeClass { 10884 1.1 joerg None = -1, 10885 1.1 joerg Void = 0, 10886 1.1 joerg Integer = 1, 10887 1.1 joerg // GCC reserves 2 for character types, but instead classifies them as 10888 1.1 joerg // integers. 10889 1.1 joerg Enum = 3, 10890 1.1 joerg Bool = 4, 10891 1.1 joerg Pointer = 5, 10892 1.1 joerg // GCC reserves 6 for references, but appears to never use it (because 10893 1.1 joerg // expressions never have reference type, presumably). 10894 1.1 joerg PointerToDataMember = 7, 10895 1.1 joerg RealFloat = 8, 10896 1.1 joerg Complex = 9, 10897 1.1 joerg // GCC reserves 10 for functions, but does not use it since GCC version 6 due 10898 1.1 joerg // to decay to pointer. (Prior to version 6 it was only used in C++ mode). 10899 1.1 joerg // GCC claims to reserve 11 for pointers to member functions, but *actually* 10900 1.1 joerg // uses 12 for that purpose, same as for a class or struct. Maybe it 10901 1.1 joerg // internally implements a pointer to member as a struct? Who knows. 10902 1.1 joerg PointerToMemberFunction = 12, // Not a bug, see above. 10903 1.1 joerg ClassOrStruct = 12, 10904 1.1 joerg Union = 13, 10905 1.1 joerg // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to 10906 1.1 joerg // decay to pointer. (Prior to version 6 it was only used in C++ mode). 10907 1.1 joerg // GCC reserves 15 for strings, but actually uses 5 (pointer) for string 10908 1.1 joerg // literals. 10909 1.1 joerg }; 10910 1.1 joerg 10911 1.1 joerg /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 10912 1.1 joerg /// as GCC. 10913 1.1 joerg static GCCTypeClass 10914 1.1 joerg EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) { 10915 1.1 joerg assert(!T->isDependentType() && "unexpected dependent type"); 10916 1.1 joerg 10917 1.1 joerg QualType CanTy = T.getCanonicalType(); 10918 1.1 joerg const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy); 10919 1.1 joerg 10920 1.1 joerg switch (CanTy->getTypeClass()) { 10921 1.1 joerg #define TYPE(ID, BASE) 10922 1.1 joerg #define DEPENDENT_TYPE(ID, BASE) case Type::ID: 10923 1.1 joerg #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID: 10924 1.1 joerg #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID: 10925 1.1 joerg #include "clang/AST/TypeNodes.inc" 10926 1.1 joerg case Type::Auto: 10927 1.1 joerg case Type::DeducedTemplateSpecialization: 10928 1.1 joerg llvm_unreachable("unexpected non-canonical or dependent type"); 10929 1.1 joerg 10930 1.1 joerg case Type::Builtin: 10931 1.1 joerg switch (BT->getKind()) { 10932 1.1 joerg #define BUILTIN_TYPE(ID, SINGLETON_ID) 10933 1.1 joerg #define SIGNED_TYPE(ID, SINGLETON_ID) \ 10934 1.1 joerg case BuiltinType::ID: return GCCTypeClass::Integer; 10935 1.1 joerg #define FLOATING_TYPE(ID, SINGLETON_ID) \ 10936 1.1 joerg case BuiltinType::ID: return GCCTypeClass::RealFloat; 10937 1.1 joerg #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \ 10938 1.1 joerg case BuiltinType::ID: break; 10939 1.1 joerg #include "clang/AST/BuiltinTypes.def" 10940 1.1 joerg case BuiltinType::Void: 10941 1.1 joerg return GCCTypeClass::Void; 10942 1.1 joerg 10943 1.1 joerg case BuiltinType::Bool: 10944 1.1 joerg return GCCTypeClass::Bool; 10945 1.1 joerg 10946 1.1 joerg case BuiltinType::Char_U: 10947 1.1 joerg case BuiltinType::UChar: 10948 1.1 joerg case BuiltinType::WChar_U: 10949 1.1 joerg case BuiltinType::Char8: 10950 1.1 joerg case BuiltinType::Char16: 10951 1.1 joerg case BuiltinType::Char32: 10952 1.1 joerg case BuiltinType::UShort: 10953 1.1 joerg case BuiltinType::UInt: 10954 1.1 joerg case BuiltinType::ULong: 10955 1.1 joerg case BuiltinType::ULongLong: 10956 1.1 joerg case BuiltinType::UInt128: 10957 1.1 joerg return GCCTypeClass::Integer; 10958 1.1 joerg 10959 1.1 joerg case BuiltinType::UShortAccum: 10960 1.1 joerg case BuiltinType::UAccum: 10961 1.1 joerg case BuiltinType::ULongAccum: 10962 1.1 joerg case BuiltinType::UShortFract: 10963 1.1 joerg case BuiltinType::UFract: 10964 1.1 joerg case BuiltinType::ULongFract: 10965 1.1 joerg case BuiltinType::SatUShortAccum: 10966 1.1 joerg case BuiltinType::SatUAccum: 10967 1.1 joerg case BuiltinType::SatULongAccum: 10968 1.1 joerg case BuiltinType::SatUShortFract: 10969 1.1 joerg case BuiltinType::SatUFract: 10970 1.1 joerg case BuiltinType::SatULongFract: 10971 1.1 joerg return GCCTypeClass::None; 10972 1.1 joerg 10973 1.1 joerg case BuiltinType::NullPtr: 10974 1.1 joerg 10975 1.1 joerg case BuiltinType::ObjCId: 10976 1.1 joerg case BuiltinType::ObjCClass: 10977 1.1 joerg case BuiltinType::ObjCSel: 10978 1.1 joerg #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 10979 1.1 joerg case BuiltinType::Id: 10980 1.1 joerg #include "clang/Basic/OpenCLImageTypes.def" 10981 1.1 joerg #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 10982 1.1 joerg case BuiltinType::Id: 10983 1.1 joerg #include "clang/Basic/OpenCLExtensionTypes.def" 10984 1.1 joerg case BuiltinType::OCLSampler: 10985 1.1 joerg case BuiltinType::OCLEvent: 10986 1.1 joerg case BuiltinType::OCLClkEvent: 10987 1.1 joerg case BuiltinType::OCLQueue: 10988 1.1 joerg case BuiltinType::OCLReserveID: 10989 1.1 joerg #define SVE_TYPE(Name, Id, SingletonId) \ 10990 1.1 joerg case BuiltinType::Id: 10991 1.1 joerg #include "clang/Basic/AArch64SVEACLETypes.def" 10992 1.1.1.2 joerg #define PPC_VECTOR_TYPE(Name, Id, Size) \ 10993 1.1.1.2 joerg case BuiltinType::Id: 10994 1.1.1.2 joerg #include "clang/Basic/PPCTypes.def" 10995 1.1.1.2 joerg #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 10996 1.1.1.2 joerg #include "clang/Basic/RISCVVTypes.def" 10997 1.1 joerg return GCCTypeClass::None; 10998 1.1 joerg 10999 1.1 joerg case BuiltinType::Dependent: 11000 1.1 joerg llvm_unreachable("unexpected dependent type"); 11001 1.1 joerg }; 11002 1.1 joerg llvm_unreachable("unexpected placeholder type"); 11003 1.1 joerg 11004 1.1 joerg case Type::Enum: 11005 1.1 joerg return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer; 11006 1.1 joerg 11007 1.1 joerg case Type::Pointer: 11008 1.1 joerg case Type::ConstantArray: 11009 1.1 joerg case Type::VariableArray: 11010 1.1 joerg case Type::IncompleteArray: 11011 1.1 joerg case Type::FunctionNoProto: 11012 1.1 joerg case Type::FunctionProto: 11013 1.1 joerg return GCCTypeClass::Pointer; 11014 1.1 joerg 11015 1.1 joerg case Type::MemberPointer: 11016 1.1 joerg return CanTy->isMemberDataPointerType() 11017 1.1 joerg ? GCCTypeClass::PointerToDataMember 11018 1.1 joerg : GCCTypeClass::PointerToMemberFunction; 11019 1.1 joerg 11020 1.1 joerg case Type::Complex: 11021 1.1 joerg return GCCTypeClass::Complex; 11022 1.1 joerg 11023 1.1 joerg case Type::Record: 11024 1.1 joerg return CanTy->isUnionType() ? GCCTypeClass::Union 11025 1.1 joerg : GCCTypeClass::ClassOrStruct; 11026 1.1 joerg 11027 1.1 joerg case Type::Atomic: 11028 1.1 joerg // GCC classifies _Atomic T the same as T. 11029 1.1 joerg return EvaluateBuiltinClassifyType( 11030 1.1 joerg CanTy->castAs<AtomicType>()->getValueType(), LangOpts); 11031 1.1 joerg 11032 1.1 joerg case Type::BlockPointer: 11033 1.1 joerg case Type::Vector: 11034 1.1 joerg case Type::ExtVector: 11035 1.1.1.2 joerg case Type::ConstantMatrix: 11036 1.1 joerg case Type::ObjCObject: 11037 1.1 joerg case Type::ObjCInterface: 11038 1.1 joerg case Type::ObjCObjectPointer: 11039 1.1 joerg case Type::Pipe: 11040 1.1.1.2 joerg case Type::ExtInt: 11041 1.1 joerg // GCC classifies vectors as None. We follow its lead and classify all 11042 1.1 joerg // other types that don't fit into the regular classification the same way. 11043 1.1 joerg return GCCTypeClass::None; 11044 1.1 joerg 11045 1.1 joerg case Type::LValueReference: 11046 1.1 joerg case Type::RValueReference: 11047 1.1 joerg llvm_unreachable("invalid type for expression"); 11048 1.1 joerg } 11049 1.1 joerg 11050 1.1 joerg llvm_unreachable("unexpected type class"); 11051 1.1 joerg } 11052 1.1 joerg 11053 1.1 joerg /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 11054 1.1 joerg /// as GCC. 11055 1.1 joerg static GCCTypeClass 11056 1.1 joerg EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) { 11057 1.1 joerg // If no argument was supplied, default to None. This isn't 11058 1.1 joerg // ideal, however it is what gcc does. 11059 1.1 joerg if (E->getNumArgs() == 0) 11060 1.1 joerg return GCCTypeClass::None; 11061 1.1 joerg 11062 1.1 joerg // FIXME: Bizarrely, GCC treats a call with more than one argument as not 11063 1.1 joerg // being an ICE, but still folds it to a constant using the type of the first 11064 1.1 joerg // argument. 11065 1.1 joerg return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts); 11066 1.1 joerg } 11067 1.1 joerg 11068 1.1 joerg /// EvaluateBuiltinConstantPForLValue - Determine the result of 11069 1.1 joerg /// __builtin_constant_p when applied to the given pointer. 11070 1.1 joerg /// 11071 1.1 joerg /// A pointer is only "constant" if it is null (or a pointer cast to integer) 11072 1.1 joerg /// or it points to the first character of a string literal. 11073 1.1 joerg static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) { 11074 1.1 joerg APValue::LValueBase Base = LV.getLValueBase(); 11075 1.1 joerg if (Base.isNull()) { 11076 1.1 joerg // A null base is acceptable. 11077 1.1 joerg return true; 11078 1.1 joerg } else if (const Expr *E = Base.dyn_cast<const Expr *>()) { 11079 1.1 joerg if (!isa<StringLiteral>(E)) 11080 1.1 joerg return false; 11081 1.1 joerg return LV.getLValueOffset().isZero(); 11082 1.1 joerg } else if (Base.is<TypeInfoLValue>()) { 11083 1.1 joerg // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to 11084 1.1 joerg // evaluate to true. 11085 1.1 joerg return true; 11086 1.1 joerg } else { 11087 1.1 joerg // Any other base is not constant enough for GCC. 11088 1.1 joerg return false; 11089 1.1 joerg } 11090 1.1 joerg } 11091 1.1 joerg 11092 1.1 joerg /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to 11093 1.1 joerg /// GCC as we can manage. 11094 1.1 joerg static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) { 11095 1.1 joerg // This evaluation is not permitted to have side-effects, so evaluate it in 11096 1.1 joerg // a speculative evaluation context. 11097 1.1 joerg SpeculativeEvaluationRAII SpeculativeEval(Info); 11098 1.1 joerg 11099 1.1 joerg // Constant-folding is always enabled for the operand of __builtin_constant_p 11100 1.1 joerg // (even when the enclosing evaluation context otherwise requires a strict 11101 1.1 joerg // language-specific constant expression). 11102 1.1 joerg FoldConstant Fold(Info, true); 11103 1.1 joerg 11104 1.1 joerg QualType ArgType = Arg->getType(); 11105 1.1 joerg 11106 1.1 joerg // __builtin_constant_p always has one operand. The rules which gcc follows 11107 1.1 joerg // are not precisely documented, but are as follows: 11108 1.1 joerg // 11109 1.1 joerg // - If the operand is of integral, floating, complex or enumeration type, 11110 1.1 joerg // and can be folded to a known value of that type, it returns 1. 11111 1.1 joerg // - If the operand can be folded to a pointer to the first character 11112 1.1 joerg // of a string literal (or such a pointer cast to an integral type) 11113 1.1 joerg // or to a null pointer or an integer cast to a pointer, it returns 1. 11114 1.1 joerg // 11115 1.1 joerg // Otherwise, it returns 0. 11116 1.1 joerg // 11117 1.1 joerg // FIXME: GCC also intends to return 1 for literals of aggregate types, but 11118 1.1 joerg // its support for this did not work prior to GCC 9 and is not yet well 11119 1.1 joerg // understood. 11120 1.1 joerg if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() || 11121 1.1 joerg ArgType->isAnyComplexType() || ArgType->isPointerType() || 11122 1.1 joerg ArgType->isNullPtrType()) { 11123 1.1 joerg APValue V; 11124 1.1.1.2 joerg if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) { 11125 1.1 joerg Fold.keepDiagnostics(); 11126 1.1 joerg return false; 11127 1.1 joerg } 11128 1.1 joerg 11129 1.1 joerg // For a pointer (possibly cast to integer), there are special rules. 11130 1.1 joerg if (V.getKind() == APValue::LValue) 11131 1.1 joerg return EvaluateBuiltinConstantPForLValue(V); 11132 1.1 joerg 11133 1.1 joerg // Otherwise, any constant value is good enough. 11134 1.1 joerg return V.hasValue(); 11135 1.1 joerg } 11136 1.1 joerg 11137 1.1 joerg // Anything else isn't considered to be sufficiently constant. 11138 1.1 joerg return false; 11139 1.1 joerg } 11140 1.1 joerg 11141 1.1 joerg /// Retrieves the "underlying object type" of the given expression, 11142 1.1 joerg /// as used by __builtin_object_size. 11143 1.1 joerg static QualType getObjectType(APValue::LValueBase B) { 11144 1.1 joerg if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 11145 1.1 joerg if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 11146 1.1 joerg return VD->getType(); 11147 1.1.1.2 joerg } else if (const Expr *E = B.dyn_cast<const Expr*>()) { 11148 1.1 joerg if (isa<CompoundLiteralExpr>(E)) 11149 1.1 joerg return E->getType(); 11150 1.1 joerg } else if (B.is<TypeInfoLValue>()) { 11151 1.1 joerg return B.getTypeInfoType(); 11152 1.1 joerg } else if (B.is<DynamicAllocLValue>()) { 11153 1.1 joerg return B.getDynamicAllocType(); 11154 1.1 joerg } 11155 1.1 joerg 11156 1.1 joerg return QualType(); 11157 1.1 joerg } 11158 1.1 joerg 11159 1.1 joerg /// A more selective version of E->IgnoreParenCasts for 11160 1.1 joerg /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only 11161 1.1 joerg /// to change the type of E. 11162 1.1 joerg /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo` 11163 1.1 joerg /// 11164 1.1 joerg /// Always returns an RValue with a pointer representation. 11165 1.1 joerg static const Expr *ignorePointerCastsAndParens(const Expr *E) { 11166 1.1 joerg assert(E->isRValue() && E->getType()->hasPointerRepresentation()); 11167 1.1 joerg 11168 1.1 joerg auto *NoParens = E->IgnoreParens(); 11169 1.1 joerg auto *Cast = dyn_cast<CastExpr>(NoParens); 11170 1.1 joerg if (Cast == nullptr) 11171 1.1 joerg return NoParens; 11172 1.1 joerg 11173 1.1 joerg // We only conservatively allow a few kinds of casts, because this code is 11174 1.1 joerg // inherently a simple solution that seeks to support the common case. 11175 1.1 joerg auto CastKind = Cast->getCastKind(); 11176 1.1 joerg if (CastKind != CK_NoOp && CastKind != CK_BitCast && 11177 1.1 joerg CastKind != CK_AddressSpaceConversion) 11178 1.1 joerg return NoParens; 11179 1.1 joerg 11180 1.1 joerg auto *SubExpr = Cast->getSubExpr(); 11181 1.1 joerg if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue()) 11182 1.1 joerg return NoParens; 11183 1.1 joerg return ignorePointerCastsAndParens(SubExpr); 11184 1.1 joerg } 11185 1.1 joerg 11186 1.1 joerg /// Checks to see if the given LValue's Designator is at the end of the LValue's 11187 1.1 joerg /// record layout. e.g. 11188 1.1 joerg /// struct { struct { int a, b; } fst, snd; } obj; 11189 1.1 joerg /// obj.fst // no 11190 1.1 joerg /// obj.snd // yes 11191 1.1 joerg /// obj.fst.a // no 11192 1.1 joerg /// obj.fst.b // no 11193 1.1 joerg /// obj.snd.a // no 11194 1.1 joerg /// obj.snd.b // yes 11195 1.1 joerg /// 11196 1.1 joerg /// Please note: this function is specialized for how __builtin_object_size 11197 1.1 joerg /// views "objects". 11198 1.1 joerg /// 11199 1.1 joerg /// If this encounters an invalid RecordDecl or otherwise cannot determine the 11200 1.1 joerg /// correct result, it will always return true. 11201 1.1 joerg static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) { 11202 1.1 joerg assert(!LVal.Designator.Invalid); 11203 1.1 joerg 11204 1.1 joerg auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) { 11205 1.1 joerg const RecordDecl *Parent = FD->getParent(); 11206 1.1 joerg Invalid = Parent->isInvalidDecl(); 11207 1.1 joerg if (Invalid || Parent->isUnion()) 11208 1.1 joerg return true; 11209 1.1 joerg const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent); 11210 1.1 joerg return FD->getFieldIndex() + 1 == Layout.getFieldCount(); 11211 1.1 joerg }; 11212 1.1 joerg 11213 1.1 joerg auto &Base = LVal.getLValueBase(); 11214 1.1 joerg if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) { 11215 1.1 joerg if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) { 11216 1.1 joerg bool Invalid; 11217 1.1 joerg if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 11218 1.1 joerg return Invalid; 11219 1.1 joerg } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) { 11220 1.1 joerg for (auto *FD : IFD->chain()) { 11221 1.1 joerg bool Invalid; 11222 1.1 joerg if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid)) 11223 1.1 joerg return Invalid; 11224 1.1 joerg } 11225 1.1 joerg } 11226 1.1 joerg } 11227 1.1 joerg 11228 1.1 joerg unsigned I = 0; 11229 1.1 joerg QualType BaseType = getType(Base); 11230 1.1 joerg if (LVal.Designator.FirstEntryIsAnUnsizedArray) { 11231 1.1 joerg // If we don't know the array bound, conservatively assume we're looking at 11232 1.1 joerg // the final array element. 11233 1.1 joerg ++I; 11234 1.1 joerg if (BaseType->isIncompleteArrayType()) 11235 1.1 joerg BaseType = Ctx.getAsArrayType(BaseType)->getElementType(); 11236 1.1 joerg else 11237 1.1 joerg BaseType = BaseType->castAs<PointerType>()->getPointeeType(); 11238 1.1 joerg } 11239 1.1 joerg 11240 1.1 joerg for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) { 11241 1.1 joerg const auto &Entry = LVal.Designator.Entries[I]; 11242 1.1 joerg if (BaseType->isArrayType()) { 11243 1.1 joerg // Because __builtin_object_size treats arrays as objects, we can ignore 11244 1.1 joerg // the index iff this is the last array in the Designator. 11245 1.1 joerg if (I + 1 == E) 11246 1.1 joerg return true; 11247 1.1 joerg const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType)); 11248 1.1 joerg uint64_t Index = Entry.getAsArrayIndex(); 11249 1.1 joerg if (Index + 1 != CAT->getSize()) 11250 1.1 joerg return false; 11251 1.1 joerg BaseType = CAT->getElementType(); 11252 1.1 joerg } else if (BaseType->isAnyComplexType()) { 11253 1.1 joerg const auto *CT = BaseType->castAs<ComplexType>(); 11254 1.1 joerg uint64_t Index = Entry.getAsArrayIndex(); 11255 1.1 joerg if (Index != 1) 11256 1.1 joerg return false; 11257 1.1 joerg BaseType = CT->getElementType(); 11258 1.1 joerg } else if (auto *FD = getAsField(Entry)) { 11259 1.1 joerg bool Invalid; 11260 1.1 joerg if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 11261 1.1 joerg return Invalid; 11262 1.1 joerg BaseType = FD->getType(); 11263 1.1 joerg } else { 11264 1.1 joerg assert(getAsBaseClass(Entry) && "Expecting cast to a base class"); 11265 1.1 joerg return false; 11266 1.1 joerg } 11267 1.1 joerg } 11268 1.1 joerg return true; 11269 1.1 joerg } 11270 1.1 joerg 11271 1.1 joerg /// Tests to see if the LValue has a user-specified designator (that isn't 11272 1.1 joerg /// necessarily valid). Note that this always returns 'true' if the LValue has 11273 1.1 joerg /// an unsized array as its first designator entry, because there's currently no 11274 1.1 joerg /// way to tell if the user typed *foo or foo[0]. 11275 1.1 joerg static bool refersToCompleteObject(const LValue &LVal) { 11276 1.1 joerg if (LVal.Designator.Invalid) 11277 1.1 joerg return false; 11278 1.1 joerg 11279 1.1 joerg if (!LVal.Designator.Entries.empty()) 11280 1.1 joerg return LVal.Designator.isMostDerivedAnUnsizedArray(); 11281 1.1 joerg 11282 1.1 joerg if (!LVal.InvalidBase) 11283 1.1 joerg return true; 11284 1.1 joerg 11285 1.1 joerg // If `E` is a MemberExpr, then the first part of the designator is hiding in 11286 1.1 joerg // the LValueBase. 11287 1.1 joerg const auto *E = LVal.Base.dyn_cast<const Expr *>(); 11288 1.1 joerg return !E || !isa<MemberExpr>(E); 11289 1.1 joerg } 11290 1.1 joerg 11291 1.1 joerg /// Attempts to detect a user writing into a piece of memory that's impossible 11292 1.1 joerg /// to figure out the size of by just using types. 11293 1.1 joerg static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) { 11294 1.1 joerg const SubobjectDesignator &Designator = LVal.Designator; 11295 1.1 joerg // Notes: 11296 1.1 joerg // - Users can only write off of the end when we have an invalid base. Invalid 11297 1.1 joerg // bases imply we don't know where the memory came from. 11298 1.1 joerg // - We used to be a bit more aggressive here; we'd only be conservative if 11299 1.1 joerg // the array at the end was flexible, or if it had 0 or 1 elements. This 11300 1.1 joerg // broke some common standard library extensions (PR30346), but was 11301 1.1 joerg // otherwise seemingly fine. It may be useful to reintroduce this behavior 11302 1.1.1.2 joerg // with some sort of list. OTOH, it seems that GCC is always 11303 1.1 joerg // conservative with the last element in structs (if it's an array), so our 11304 1.1.1.2 joerg // current behavior is more compatible than an explicit list approach would 11305 1.1 joerg // be. 11306 1.1 joerg return LVal.InvalidBase && 11307 1.1 joerg Designator.Entries.size() == Designator.MostDerivedPathLength && 11308 1.1 joerg Designator.MostDerivedIsArrayElement && 11309 1.1 joerg isDesignatorAtObjectEnd(Ctx, LVal); 11310 1.1 joerg } 11311 1.1 joerg 11312 1.1 joerg /// Converts the given APInt to CharUnits, assuming the APInt is unsigned. 11313 1.1 joerg /// Fails if the conversion would cause loss of precision. 11314 1.1 joerg static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int, 11315 1.1 joerg CharUnits &Result) { 11316 1.1 joerg auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max(); 11317 1.1 joerg if (Int.ugt(CharUnitsMax)) 11318 1.1 joerg return false; 11319 1.1 joerg Result = CharUnits::fromQuantity(Int.getZExtValue()); 11320 1.1 joerg return true; 11321 1.1 joerg } 11322 1.1 joerg 11323 1.1 joerg /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will 11324 1.1 joerg /// determine how many bytes exist from the beginning of the object to either 11325 1.1 joerg /// the end of the current subobject, or the end of the object itself, depending 11326 1.1 joerg /// on what the LValue looks like + the value of Type. 11327 1.1 joerg /// 11328 1.1 joerg /// If this returns false, the value of Result is undefined. 11329 1.1 joerg static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc, 11330 1.1 joerg unsigned Type, const LValue &LVal, 11331 1.1 joerg CharUnits &EndOffset) { 11332 1.1 joerg bool DetermineForCompleteObject = refersToCompleteObject(LVal); 11333 1.1 joerg 11334 1.1 joerg auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) { 11335 1.1 joerg if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType()) 11336 1.1 joerg return false; 11337 1.1 joerg return HandleSizeof(Info, ExprLoc, Ty, Result); 11338 1.1 joerg }; 11339 1.1 joerg 11340 1.1 joerg // We want to evaluate the size of the entire object. This is a valid fallback 11341 1.1 joerg // for when Type=1 and the designator is invalid, because we're asked for an 11342 1.1 joerg // upper-bound. 11343 1.1 joerg if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) { 11344 1.1 joerg // Type=3 wants a lower bound, so we can't fall back to this. 11345 1.1 joerg if (Type == 3 && !DetermineForCompleteObject) 11346 1.1 joerg return false; 11347 1.1 joerg 11348 1.1 joerg llvm::APInt APEndOffset; 11349 1.1 joerg if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && 11350 1.1 joerg getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) 11351 1.1 joerg return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); 11352 1.1 joerg 11353 1.1 joerg if (LVal.InvalidBase) 11354 1.1 joerg return false; 11355 1.1 joerg 11356 1.1 joerg QualType BaseTy = getObjectType(LVal.getLValueBase()); 11357 1.1 joerg return CheckedHandleSizeof(BaseTy, EndOffset); 11358 1.1 joerg } 11359 1.1 joerg 11360 1.1 joerg // We want to evaluate the size of a subobject. 11361 1.1 joerg const SubobjectDesignator &Designator = LVal.Designator; 11362 1.1 joerg 11363 1.1 joerg // The following is a moderately common idiom in C: 11364 1.1 joerg // 11365 1.1 joerg // struct Foo { int a; char c[1]; }; 11366 1.1 joerg // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar)); 11367 1.1 joerg // strcpy(&F->c[0], Bar); 11368 1.1 joerg // 11369 1.1 joerg // In order to not break too much legacy code, we need to support it. 11370 1.1 joerg if (isUserWritingOffTheEnd(Info.Ctx, LVal)) { 11371 1.1 joerg // If we can resolve this to an alloc_size call, we can hand that back, 11372 1.1 joerg // because we know for certain how many bytes there are to write to. 11373 1.1 joerg llvm::APInt APEndOffset; 11374 1.1 joerg if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && 11375 1.1 joerg getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) 11376 1.1 joerg return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); 11377 1.1 joerg 11378 1.1 joerg // If we cannot determine the size of the initial allocation, then we can't 11379 1.1 joerg // given an accurate upper-bound. However, we are still able to give 11380 1.1 joerg // conservative lower-bounds for Type=3. 11381 1.1 joerg if (Type == 1) 11382 1.1 joerg return false; 11383 1.1 joerg } 11384 1.1 joerg 11385 1.1 joerg CharUnits BytesPerElem; 11386 1.1 joerg if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem)) 11387 1.1 joerg return false; 11388 1.1 joerg 11389 1.1 joerg // According to the GCC documentation, we want the size of the subobject 11390 1.1 joerg // denoted by the pointer. But that's not quite right -- what we actually 11391 1.1 joerg // want is the size of the immediately-enclosing array, if there is one. 11392 1.1 joerg int64_t ElemsRemaining; 11393 1.1 joerg if (Designator.MostDerivedIsArrayElement && 11394 1.1 joerg Designator.Entries.size() == Designator.MostDerivedPathLength) { 11395 1.1 joerg uint64_t ArraySize = Designator.getMostDerivedArraySize(); 11396 1.1 joerg uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex(); 11397 1.1 joerg ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex; 11398 1.1 joerg } else { 11399 1.1 joerg ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1; 11400 1.1 joerg } 11401 1.1 joerg 11402 1.1 joerg EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining; 11403 1.1 joerg return true; 11404 1.1 joerg } 11405 1.1 joerg 11406 1.1 joerg /// Tries to evaluate the __builtin_object_size for @p E. If successful, 11407 1.1 joerg /// returns true and stores the result in @p Size. 11408 1.1 joerg /// 11409 1.1 joerg /// If @p WasError is non-null, this will report whether the failure to evaluate 11410 1.1 joerg /// is to be treated as an Error in IntExprEvaluator. 11411 1.1 joerg static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type, 11412 1.1 joerg EvalInfo &Info, uint64_t &Size) { 11413 1.1 joerg // Determine the denoted object. 11414 1.1 joerg LValue LVal; 11415 1.1 joerg { 11416 1.1 joerg // The operand of __builtin_object_size is never evaluated for side-effects. 11417 1.1 joerg // If there are any, but we can determine the pointed-to object anyway, then 11418 1.1 joerg // ignore the side-effects. 11419 1.1 joerg SpeculativeEvaluationRAII SpeculativeEval(Info); 11420 1.1 joerg IgnoreSideEffectsRAII Fold(Info); 11421 1.1 joerg 11422 1.1 joerg if (E->isGLValue()) { 11423 1.1 joerg // It's possible for us to be given GLValues if we're called via 11424 1.1 joerg // Expr::tryEvaluateObjectSize. 11425 1.1 joerg APValue RVal; 11426 1.1 joerg if (!EvaluateAsRValue(Info, E, RVal)) 11427 1.1 joerg return false; 11428 1.1 joerg LVal.setFrom(Info.Ctx, RVal); 11429 1.1 joerg } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info, 11430 1.1 joerg /*InvalidBaseOK=*/true)) 11431 1.1 joerg return false; 11432 1.1 joerg } 11433 1.1 joerg 11434 1.1 joerg // If we point to before the start of the object, there are no accessible 11435 1.1 joerg // bytes. 11436 1.1 joerg if (LVal.getLValueOffset().isNegative()) { 11437 1.1 joerg Size = 0; 11438 1.1 joerg return true; 11439 1.1 joerg } 11440 1.1 joerg 11441 1.1 joerg CharUnits EndOffset; 11442 1.1 joerg if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset)) 11443 1.1 joerg return false; 11444 1.1 joerg 11445 1.1 joerg // If we've fallen outside of the end offset, just pretend there's nothing to 11446 1.1 joerg // write to/read from. 11447 1.1 joerg if (EndOffset <= LVal.getLValueOffset()) 11448 1.1 joerg Size = 0; 11449 1.1 joerg else 11450 1.1 joerg Size = (EndOffset - LVal.getLValueOffset()).getQuantity(); 11451 1.1 joerg return true; 11452 1.1 joerg } 11453 1.1 joerg 11454 1.1 joerg bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) { 11455 1.1 joerg if (unsigned BuiltinOp = E->getBuiltinCallee()) 11456 1.1 joerg return VisitBuiltinCallExpr(E, BuiltinOp); 11457 1.1 joerg 11458 1.1 joerg return ExprEvaluatorBaseTy::VisitCallExpr(E); 11459 1.1 joerg } 11460 1.1 joerg 11461 1.1.1.2 joerg static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info, 11462 1.1.1.2 joerg APValue &Val, APSInt &Alignment) { 11463 1.1.1.2 joerg QualType SrcTy = E->getArg(0)->getType(); 11464 1.1.1.2 joerg if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment)) 11465 1.1.1.2 joerg return false; 11466 1.1.1.2 joerg // Even though we are evaluating integer expressions we could get a pointer 11467 1.1.1.2 joerg // argument for the __builtin_is_aligned() case. 11468 1.1.1.2 joerg if (SrcTy->isPointerType()) { 11469 1.1.1.2 joerg LValue Ptr; 11470 1.1.1.2 joerg if (!EvaluatePointer(E->getArg(0), Ptr, Info)) 11471 1.1.1.2 joerg return false; 11472 1.1.1.2 joerg Ptr.moveInto(Val); 11473 1.1.1.2 joerg } else if (!SrcTy->isIntegralOrEnumerationType()) { 11474 1.1.1.2 joerg Info.FFDiag(E->getArg(0)); 11475 1.1.1.2 joerg return false; 11476 1.1.1.2 joerg } else { 11477 1.1.1.2 joerg APSInt SrcInt; 11478 1.1.1.2 joerg if (!EvaluateInteger(E->getArg(0), SrcInt, Info)) 11479 1.1.1.2 joerg return false; 11480 1.1.1.2 joerg assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() && 11481 1.1.1.2 joerg "Bit widths must be the same"); 11482 1.1.1.2 joerg Val = APValue(SrcInt); 11483 1.1.1.2 joerg } 11484 1.1.1.2 joerg assert(Val.hasValue()); 11485 1.1.1.2 joerg return true; 11486 1.1.1.2 joerg } 11487 1.1.1.2 joerg 11488 1.1 joerg bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, 11489 1.1 joerg unsigned BuiltinOp) { 11490 1.1.1.2 joerg switch (BuiltinOp) { 11491 1.1 joerg default: 11492 1.1 joerg return ExprEvaluatorBaseTy::VisitCallExpr(E); 11493 1.1 joerg 11494 1.1 joerg case Builtin::BI__builtin_dynamic_object_size: 11495 1.1 joerg case Builtin::BI__builtin_object_size: { 11496 1.1 joerg // The type was checked when we built the expression. 11497 1.1 joerg unsigned Type = 11498 1.1 joerg E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 11499 1.1 joerg assert(Type <= 3 && "unexpected type"); 11500 1.1 joerg 11501 1.1 joerg uint64_t Size; 11502 1.1 joerg if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size)) 11503 1.1 joerg return Success(Size, E); 11504 1.1 joerg 11505 1.1 joerg if (E->getArg(0)->HasSideEffects(Info.Ctx)) 11506 1.1 joerg return Success((Type & 2) ? 0 : -1, E); 11507 1.1 joerg 11508 1.1 joerg // Expression had no side effects, but we couldn't statically determine the 11509 1.1 joerg // size of the referenced object. 11510 1.1 joerg switch (Info.EvalMode) { 11511 1.1 joerg case EvalInfo::EM_ConstantExpression: 11512 1.1 joerg case EvalInfo::EM_ConstantFold: 11513 1.1 joerg case EvalInfo::EM_IgnoreSideEffects: 11514 1.1 joerg // Leave it to IR generation. 11515 1.1 joerg return Error(E); 11516 1.1 joerg case EvalInfo::EM_ConstantExpressionUnevaluated: 11517 1.1 joerg // Reduce it to a constant now. 11518 1.1 joerg return Success((Type & 2) ? 0 : -1, E); 11519 1.1 joerg } 11520 1.1 joerg 11521 1.1 joerg llvm_unreachable("unexpected EvalMode"); 11522 1.1 joerg } 11523 1.1 joerg 11524 1.1 joerg case Builtin::BI__builtin_os_log_format_buffer_size: { 11525 1.1 joerg analyze_os_log::OSLogBufferLayout Layout; 11526 1.1 joerg analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout); 11527 1.1 joerg return Success(Layout.size().getQuantity(), E); 11528 1.1 joerg } 11529 1.1 joerg 11530 1.1.1.2 joerg case Builtin::BI__builtin_is_aligned: { 11531 1.1.1.2 joerg APValue Src; 11532 1.1.1.2 joerg APSInt Alignment; 11533 1.1.1.2 joerg if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 11534 1.1.1.2 joerg return false; 11535 1.1.1.2 joerg if (Src.isLValue()) { 11536 1.1.1.2 joerg // If we evaluated a pointer, check the minimum known alignment. 11537 1.1.1.2 joerg LValue Ptr; 11538 1.1.1.2 joerg Ptr.setFrom(Info.Ctx, Src); 11539 1.1.1.2 joerg CharUnits BaseAlignment = getBaseAlignment(Info, Ptr); 11540 1.1.1.2 joerg CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset); 11541 1.1.1.2 joerg // We can return true if the known alignment at the computed offset is 11542 1.1.1.2 joerg // greater than the requested alignment. 11543 1.1.1.2 joerg assert(PtrAlign.isPowerOfTwo()); 11544 1.1.1.2 joerg assert(Alignment.isPowerOf2()); 11545 1.1.1.2 joerg if (PtrAlign.getQuantity() >= Alignment) 11546 1.1.1.2 joerg return Success(1, E); 11547 1.1.1.2 joerg // If the alignment is not known to be sufficient, some cases could still 11548 1.1.1.2 joerg // be aligned at run time. However, if the requested alignment is less or 11549 1.1.1.2 joerg // equal to the base alignment and the offset is not aligned, we know that 11550 1.1.1.2 joerg // the run-time value can never be aligned. 11551 1.1.1.2 joerg if (BaseAlignment.getQuantity() >= Alignment && 11552 1.1.1.2 joerg PtrAlign.getQuantity() < Alignment) 11553 1.1.1.2 joerg return Success(0, E); 11554 1.1.1.2 joerg // Otherwise we can't infer whether the value is sufficiently aligned. 11555 1.1.1.2 joerg // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N) 11556 1.1.1.2 joerg // in cases where we can't fully evaluate the pointer. 11557 1.1.1.2 joerg Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute) 11558 1.1.1.2 joerg << Alignment; 11559 1.1.1.2 joerg return false; 11560 1.1.1.2 joerg } 11561 1.1.1.2 joerg assert(Src.isInt()); 11562 1.1.1.2 joerg return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E); 11563 1.1.1.2 joerg } 11564 1.1.1.2 joerg case Builtin::BI__builtin_align_up: { 11565 1.1.1.2 joerg APValue Src; 11566 1.1.1.2 joerg APSInt Alignment; 11567 1.1.1.2 joerg if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 11568 1.1.1.2 joerg return false; 11569 1.1.1.2 joerg if (!Src.isInt()) 11570 1.1.1.2 joerg return Error(E); 11571 1.1.1.2 joerg APSInt AlignedVal = 11572 1.1.1.2 joerg APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1), 11573 1.1.1.2 joerg Src.getInt().isUnsigned()); 11574 1.1.1.2 joerg assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth()); 11575 1.1.1.2 joerg return Success(AlignedVal, E); 11576 1.1.1.2 joerg } 11577 1.1.1.2 joerg case Builtin::BI__builtin_align_down: { 11578 1.1.1.2 joerg APValue Src; 11579 1.1.1.2 joerg APSInt Alignment; 11580 1.1.1.2 joerg if (!getBuiltinAlignArguments(E, Info, Src, Alignment)) 11581 1.1.1.2 joerg return false; 11582 1.1.1.2 joerg if (!Src.isInt()) 11583 1.1.1.2 joerg return Error(E); 11584 1.1.1.2 joerg APSInt AlignedVal = 11585 1.1.1.2 joerg APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned()); 11586 1.1.1.2 joerg assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth()); 11587 1.1.1.2 joerg return Success(AlignedVal, E); 11588 1.1.1.2 joerg } 11589 1.1.1.2 joerg 11590 1.1.1.2 joerg case Builtin::BI__builtin_bitreverse8: 11591 1.1.1.2 joerg case Builtin::BI__builtin_bitreverse16: 11592 1.1.1.2 joerg case Builtin::BI__builtin_bitreverse32: 11593 1.1.1.2 joerg case Builtin::BI__builtin_bitreverse64: { 11594 1.1.1.2 joerg APSInt Val; 11595 1.1.1.2 joerg if (!EvaluateInteger(E->getArg(0), Val, Info)) 11596 1.1.1.2 joerg return false; 11597 1.1.1.2 joerg 11598 1.1.1.2 joerg return Success(Val.reverseBits(), E); 11599 1.1.1.2 joerg } 11600 1.1.1.2 joerg 11601 1.1 joerg case Builtin::BI__builtin_bswap16: 11602 1.1 joerg case Builtin::BI__builtin_bswap32: 11603 1.1 joerg case Builtin::BI__builtin_bswap64: { 11604 1.1 joerg APSInt Val; 11605 1.1 joerg if (!EvaluateInteger(E->getArg(0), Val, Info)) 11606 1.1 joerg return false; 11607 1.1 joerg 11608 1.1 joerg return Success(Val.byteSwap(), E); 11609 1.1 joerg } 11610 1.1 joerg 11611 1.1 joerg case Builtin::BI__builtin_classify_type: 11612 1.1 joerg return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E); 11613 1.1 joerg 11614 1.1 joerg case Builtin::BI__builtin_clrsb: 11615 1.1 joerg case Builtin::BI__builtin_clrsbl: 11616 1.1 joerg case Builtin::BI__builtin_clrsbll: { 11617 1.1 joerg APSInt Val; 11618 1.1 joerg if (!EvaluateInteger(E->getArg(0), Val, Info)) 11619 1.1 joerg return false; 11620 1.1 joerg 11621 1.1 joerg return Success(Val.getBitWidth() - Val.getMinSignedBits(), E); 11622 1.1 joerg } 11623 1.1 joerg 11624 1.1 joerg case Builtin::BI__builtin_clz: 11625 1.1 joerg case Builtin::BI__builtin_clzl: 11626 1.1 joerg case Builtin::BI__builtin_clzll: 11627 1.1 joerg case Builtin::BI__builtin_clzs: { 11628 1.1 joerg APSInt Val; 11629 1.1 joerg if (!EvaluateInteger(E->getArg(0), Val, Info)) 11630 1.1 joerg return false; 11631 1.1 joerg if (!Val) 11632 1.1 joerg return Error(E); 11633 1.1 joerg 11634 1.1 joerg return Success(Val.countLeadingZeros(), E); 11635 1.1 joerg } 11636 1.1 joerg 11637 1.1 joerg case Builtin::BI__builtin_constant_p: { 11638 1.1 joerg const Expr *Arg = E->getArg(0); 11639 1.1 joerg if (EvaluateBuiltinConstantP(Info, Arg)) 11640 1.1 joerg return Success(true, E); 11641 1.1 joerg if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) { 11642 1.1 joerg // Outside a constant context, eagerly evaluate to false in the presence 11643 1.1 joerg // of side-effects in order to avoid -Wunsequenced false-positives in 11644 1.1 joerg // a branch on __builtin_constant_p(expr). 11645 1.1 joerg return Success(false, E); 11646 1.1 joerg } 11647 1.1 joerg Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 11648 1.1 joerg return false; 11649 1.1 joerg } 11650 1.1 joerg 11651 1.1.1.2 joerg case Builtin::BI__builtin_is_constant_evaluated: { 11652 1.1.1.2 joerg const auto *Callee = Info.CurrentCall->getCallee(); 11653 1.1.1.2 joerg if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression && 11654 1.1.1.2 joerg (Info.CallStackDepth == 1 || 11655 1.1.1.2 joerg (Info.CallStackDepth == 2 && Callee->isInStdNamespace() && 11656 1.1.1.2 joerg Callee->getIdentifier() && 11657 1.1.1.2 joerg Callee->getIdentifier()->isStr("is_constant_evaluated")))) { 11658 1.1.1.2 joerg // FIXME: Find a better way to avoid duplicated diagnostics. 11659 1.1.1.2 joerg if (Info.EvalStatus.Diag) 11660 1.1.1.2 joerg Info.report((Info.CallStackDepth == 1) ? E->getExprLoc() 11661 1.1.1.2 joerg : Info.CurrentCall->CallLoc, 11662 1.1.1.2 joerg diag::warn_is_constant_evaluated_always_true_constexpr) 11663 1.1.1.2 joerg << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated" 11664 1.1.1.2 joerg : "std::is_constant_evaluated"); 11665 1.1.1.2 joerg } 11666 1.1.1.2 joerg 11667 1.1 joerg return Success(Info.InConstantContext, E); 11668 1.1.1.2 joerg } 11669 1.1 joerg 11670 1.1 joerg case Builtin::BI__builtin_ctz: 11671 1.1 joerg case Builtin::BI__builtin_ctzl: 11672 1.1 joerg case Builtin::BI__builtin_ctzll: 11673 1.1 joerg case Builtin::BI__builtin_ctzs: { 11674 1.1 joerg APSInt Val; 11675 1.1 joerg if (!EvaluateInteger(E->getArg(0), Val, Info)) 11676 1.1 joerg return false; 11677 1.1 joerg if (!Val) 11678 1.1 joerg return Error(E); 11679 1.1 joerg 11680 1.1 joerg return Success(Val.countTrailingZeros(), E); 11681 1.1 joerg } 11682 1.1 joerg 11683 1.1 joerg case Builtin::BI__builtin_eh_return_data_regno: { 11684 1.1 joerg int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 11685 1.1 joerg Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand); 11686 1.1 joerg return Success(Operand, E); 11687 1.1 joerg } 11688 1.1 joerg 11689 1.1 joerg case Builtin::BI__builtin_expect: 11690 1.1.1.2 joerg case Builtin::BI__builtin_expect_with_probability: 11691 1.1 joerg return Visit(E->getArg(0)); 11692 1.1 joerg 11693 1.1 joerg case Builtin::BI__builtin_ffs: 11694 1.1 joerg case Builtin::BI__builtin_ffsl: 11695 1.1 joerg case Builtin::BI__builtin_ffsll: { 11696 1.1 joerg APSInt Val; 11697 1.1 joerg if (!EvaluateInteger(E->getArg(0), Val, Info)) 11698 1.1 joerg return false; 11699 1.1 joerg 11700 1.1 joerg unsigned N = Val.countTrailingZeros(); 11701 1.1 joerg return Success(N == Val.getBitWidth() ? 0 : N + 1, E); 11702 1.1 joerg } 11703 1.1 joerg 11704 1.1 joerg case Builtin::BI__builtin_fpclassify: { 11705 1.1 joerg APFloat Val(0.0); 11706 1.1 joerg if (!EvaluateFloat(E->getArg(5), Val, Info)) 11707 1.1 joerg return false; 11708 1.1 joerg unsigned Arg; 11709 1.1 joerg switch (Val.getCategory()) { 11710 1.1 joerg case APFloat::fcNaN: Arg = 0; break; 11711 1.1 joerg case APFloat::fcInfinity: Arg = 1; break; 11712 1.1 joerg case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break; 11713 1.1 joerg case APFloat::fcZero: Arg = 4; break; 11714 1.1 joerg } 11715 1.1 joerg return Visit(E->getArg(Arg)); 11716 1.1 joerg } 11717 1.1 joerg 11718 1.1 joerg case Builtin::BI__builtin_isinf_sign: { 11719 1.1 joerg APFloat Val(0.0); 11720 1.1 joerg return EvaluateFloat(E->getArg(0), Val, Info) && 11721 1.1 joerg Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E); 11722 1.1 joerg } 11723 1.1 joerg 11724 1.1 joerg case Builtin::BI__builtin_isinf: { 11725 1.1 joerg APFloat Val(0.0); 11726 1.1 joerg return EvaluateFloat(E->getArg(0), Val, Info) && 11727 1.1 joerg Success(Val.isInfinity() ? 1 : 0, E); 11728 1.1 joerg } 11729 1.1 joerg 11730 1.1 joerg case Builtin::BI__builtin_isfinite: { 11731 1.1 joerg APFloat Val(0.0); 11732 1.1 joerg return EvaluateFloat(E->getArg(0), Val, Info) && 11733 1.1 joerg Success(Val.isFinite() ? 1 : 0, E); 11734 1.1 joerg } 11735 1.1 joerg 11736 1.1 joerg case Builtin::BI__builtin_isnan: { 11737 1.1 joerg APFloat Val(0.0); 11738 1.1 joerg return EvaluateFloat(E->getArg(0), Val, Info) && 11739 1.1 joerg Success(Val.isNaN() ? 1 : 0, E); 11740 1.1 joerg } 11741 1.1 joerg 11742 1.1 joerg case Builtin::BI__builtin_isnormal: { 11743 1.1 joerg APFloat Val(0.0); 11744 1.1 joerg return EvaluateFloat(E->getArg(0), Val, Info) && 11745 1.1 joerg Success(Val.isNormal() ? 1 : 0, E); 11746 1.1 joerg } 11747 1.1 joerg 11748 1.1 joerg case Builtin::BI__builtin_parity: 11749 1.1 joerg case Builtin::BI__builtin_parityl: 11750 1.1 joerg case Builtin::BI__builtin_parityll: { 11751 1.1 joerg APSInt Val; 11752 1.1 joerg if (!EvaluateInteger(E->getArg(0), Val, Info)) 11753 1.1 joerg return false; 11754 1.1 joerg 11755 1.1 joerg return Success(Val.countPopulation() % 2, E); 11756 1.1 joerg } 11757 1.1 joerg 11758 1.1 joerg case Builtin::BI__builtin_popcount: 11759 1.1 joerg case Builtin::BI__builtin_popcountl: 11760 1.1 joerg case Builtin::BI__builtin_popcountll: { 11761 1.1 joerg APSInt Val; 11762 1.1 joerg if (!EvaluateInteger(E->getArg(0), Val, Info)) 11763 1.1 joerg return false; 11764 1.1 joerg 11765 1.1 joerg return Success(Val.countPopulation(), E); 11766 1.1 joerg } 11767 1.1 joerg 11768 1.1.1.2 joerg case Builtin::BI__builtin_rotateleft8: 11769 1.1.1.2 joerg case Builtin::BI__builtin_rotateleft16: 11770 1.1.1.2 joerg case Builtin::BI__builtin_rotateleft32: 11771 1.1.1.2 joerg case Builtin::BI__builtin_rotateleft64: 11772 1.1.1.2 joerg case Builtin::BI_rotl8: // Microsoft variants of rotate right 11773 1.1.1.2 joerg case Builtin::BI_rotl16: 11774 1.1.1.2 joerg case Builtin::BI_rotl: 11775 1.1.1.2 joerg case Builtin::BI_lrotl: 11776 1.1.1.2 joerg case Builtin::BI_rotl64: { 11777 1.1.1.2 joerg APSInt Val, Amt; 11778 1.1.1.2 joerg if (!EvaluateInteger(E->getArg(0), Val, Info) || 11779 1.1.1.2 joerg !EvaluateInteger(E->getArg(1), Amt, Info)) 11780 1.1.1.2 joerg return false; 11781 1.1.1.2 joerg 11782 1.1.1.2 joerg return Success(Val.rotl(Amt.urem(Val.getBitWidth())), E); 11783 1.1.1.2 joerg } 11784 1.1.1.2 joerg 11785 1.1.1.2 joerg case Builtin::BI__builtin_rotateright8: 11786 1.1.1.2 joerg case Builtin::BI__builtin_rotateright16: 11787 1.1.1.2 joerg case Builtin::BI__builtin_rotateright32: 11788 1.1.1.2 joerg case Builtin::BI__builtin_rotateright64: 11789 1.1.1.2 joerg case Builtin::BI_rotr8: // Microsoft variants of rotate right 11790 1.1.1.2 joerg case Builtin::BI_rotr16: 11791 1.1.1.2 joerg case Builtin::BI_rotr: 11792 1.1.1.2 joerg case Builtin::BI_lrotr: 11793 1.1.1.2 joerg case Builtin::BI_rotr64: { 11794 1.1.1.2 joerg APSInt Val, Amt; 11795 1.1.1.2 joerg if (!EvaluateInteger(E->getArg(0), Val, Info) || 11796 1.1.1.2 joerg !EvaluateInteger(E->getArg(1), Amt, Info)) 11797 1.1.1.2 joerg return false; 11798 1.1.1.2 joerg 11799 1.1.1.2 joerg return Success(Val.rotr(Amt.urem(Val.getBitWidth())), E); 11800 1.1.1.2 joerg } 11801 1.1.1.2 joerg 11802 1.1 joerg case Builtin::BIstrlen: 11803 1.1 joerg case Builtin::BIwcslen: 11804 1.1 joerg // A call to strlen is not a constant expression. 11805 1.1 joerg if (Info.getLangOpts().CPlusPlus11) 11806 1.1 joerg Info.CCEDiag(E, diag::note_constexpr_invalid_function) 11807 1.1 joerg << /*isConstexpr*/0 << /*isConstructor*/0 11808 1.1 joerg << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 11809 1.1 joerg else 11810 1.1 joerg Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 11811 1.1 joerg LLVM_FALLTHROUGH; 11812 1.1 joerg case Builtin::BI__builtin_strlen: 11813 1.1 joerg case Builtin::BI__builtin_wcslen: { 11814 1.1 joerg // As an extension, we support __builtin_strlen() as a constant expression, 11815 1.1 joerg // and support folding strlen() to a constant. 11816 1.1 joerg LValue String; 11817 1.1 joerg if (!EvaluatePointer(E->getArg(0), String, Info)) 11818 1.1 joerg return false; 11819 1.1 joerg 11820 1.1 joerg QualType CharTy = E->getArg(0)->getType()->getPointeeType(); 11821 1.1 joerg 11822 1.1 joerg // Fast path: if it's a string literal, search the string value. 11823 1.1 joerg if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>( 11824 1.1 joerg String.getLValueBase().dyn_cast<const Expr *>())) { 11825 1.1 joerg // The string literal may have embedded null characters. Find the first 11826 1.1 joerg // one and truncate there. 11827 1.1 joerg StringRef Str = S->getBytes(); 11828 1.1 joerg int64_t Off = String.Offset.getQuantity(); 11829 1.1 joerg if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() && 11830 1.1 joerg S->getCharByteWidth() == 1 && 11831 1.1 joerg // FIXME: Add fast-path for wchar_t too. 11832 1.1 joerg Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) { 11833 1.1 joerg Str = Str.substr(Off); 11834 1.1 joerg 11835 1.1 joerg StringRef::size_type Pos = Str.find(0); 11836 1.1 joerg if (Pos != StringRef::npos) 11837 1.1 joerg Str = Str.substr(0, Pos); 11838 1.1 joerg 11839 1.1 joerg return Success(Str.size(), E); 11840 1.1 joerg } 11841 1.1 joerg 11842 1.1 joerg // Fall through to slow path to issue appropriate diagnostic. 11843 1.1 joerg } 11844 1.1 joerg 11845 1.1 joerg // Slow path: scan the bytes of the string looking for the terminating 0. 11846 1.1 joerg for (uint64_t Strlen = 0; /**/; ++Strlen) { 11847 1.1 joerg APValue Char; 11848 1.1 joerg if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) || 11849 1.1 joerg !Char.isInt()) 11850 1.1 joerg return false; 11851 1.1 joerg if (!Char.getInt()) 11852 1.1 joerg return Success(Strlen, E); 11853 1.1 joerg if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1)) 11854 1.1 joerg return false; 11855 1.1 joerg } 11856 1.1 joerg } 11857 1.1 joerg 11858 1.1 joerg case Builtin::BIstrcmp: 11859 1.1 joerg case Builtin::BIwcscmp: 11860 1.1 joerg case Builtin::BIstrncmp: 11861 1.1 joerg case Builtin::BIwcsncmp: 11862 1.1 joerg case Builtin::BImemcmp: 11863 1.1 joerg case Builtin::BIbcmp: 11864 1.1 joerg case Builtin::BIwmemcmp: 11865 1.1 joerg // A call to strlen is not a constant expression. 11866 1.1 joerg if (Info.getLangOpts().CPlusPlus11) 11867 1.1 joerg Info.CCEDiag(E, diag::note_constexpr_invalid_function) 11868 1.1 joerg << /*isConstexpr*/0 << /*isConstructor*/0 11869 1.1 joerg << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 11870 1.1 joerg else 11871 1.1 joerg Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 11872 1.1 joerg LLVM_FALLTHROUGH; 11873 1.1 joerg case Builtin::BI__builtin_strcmp: 11874 1.1 joerg case Builtin::BI__builtin_wcscmp: 11875 1.1 joerg case Builtin::BI__builtin_strncmp: 11876 1.1 joerg case Builtin::BI__builtin_wcsncmp: 11877 1.1 joerg case Builtin::BI__builtin_memcmp: 11878 1.1 joerg case Builtin::BI__builtin_bcmp: 11879 1.1 joerg case Builtin::BI__builtin_wmemcmp: { 11880 1.1 joerg LValue String1, String2; 11881 1.1 joerg if (!EvaluatePointer(E->getArg(0), String1, Info) || 11882 1.1 joerg !EvaluatePointer(E->getArg(1), String2, Info)) 11883 1.1 joerg return false; 11884 1.1 joerg 11885 1.1 joerg uint64_t MaxLength = uint64_t(-1); 11886 1.1 joerg if (BuiltinOp != Builtin::BIstrcmp && 11887 1.1 joerg BuiltinOp != Builtin::BIwcscmp && 11888 1.1 joerg BuiltinOp != Builtin::BI__builtin_strcmp && 11889 1.1 joerg BuiltinOp != Builtin::BI__builtin_wcscmp) { 11890 1.1 joerg APSInt N; 11891 1.1 joerg if (!EvaluateInteger(E->getArg(2), N, Info)) 11892 1.1 joerg return false; 11893 1.1 joerg MaxLength = N.getExtValue(); 11894 1.1 joerg } 11895 1.1 joerg 11896 1.1 joerg // Empty substrings compare equal by definition. 11897 1.1 joerg if (MaxLength == 0u) 11898 1.1 joerg return Success(0, E); 11899 1.1 joerg 11900 1.1 joerg if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) || 11901 1.1 joerg !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) || 11902 1.1 joerg String1.Designator.Invalid || String2.Designator.Invalid) 11903 1.1 joerg return false; 11904 1.1 joerg 11905 1.1 joerg QualType CharTy1 = String1.Designator.getType(Info.Ctx); 11906 1.1 joerg QualType CharTy2 = String2.Designator.getType(Info.Ctx); 11907 1.1 joerg 11908 1.1 joerg bool IsRawByte = BuiltinOp == Builtin::BImemcmp || 11909 1.1 joerg BuiltinOp == Builtin::BIbcmp || 11910 1.1 joerg BuiltinOp == Builtin::BI__builtin_memcmp || 11911 1.1 joerg BuiltinOp == Builtin::BI__builtin_bcmp; 11912 1.1 joerg 11913 1.1 joerg assert(IsRawByte || 11914 1.1 joerg (Info.Ctx.hasSameUnqualifiedType( 11915 1.1 joerg CharTy1, E->getArg(0)->getType()->getPointeeType()) && 11916 1.1 joerg Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2))); 11917 1.1 joerg 11918 1.1.1.2 joerg // For memcmp, allow comparing any arrays of '[[un]signed] char' or 11919 1.1.1.2 joerg // 'char8_t', but no other types. 11920 1.1.1.2 joerg if (IsRawByte && 11921 1.1.1.2 joerg !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) { 11922 1.1.1.2 joerg // FIXME: Consider using our bit_cast implementation to support this. 11923 1.1.1.2 joerg Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported) 11924 1.1.1.2 joerg << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'") 11925 1.1.1.2 joerg << CharTy1 << CharTy2; 11926 1.1.1.2 joerg return false; 11927 1.1.1.2 joerg } 11928 1.1.1.2 joerg 11929 1.1 joerg const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) { 11930 1.1 joerg return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) && 11931 1.1 joerg handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) && 11932 1.1 joerg Char1.isInt() && Char2.isInt(); 11933 1.1 joerg }; 11934 1.1 joerg const auto &AdvanceElems = [&] { 11935 1.1 joerg return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) && 11936 1.1 joerg HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1); 11937 1.1 joerg }; 11938 1.1 joerg 11939 1.1 joerg bool StopAtNull = 11940 1.1 joerg (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp && 11941 1.1 joerg BuiltinOp != Builtin::BIwmemcmp && 11942 1.1 joerg BuiltinOp != Builtin::BI__builtin_memcmp && 11943 1.1 joerg BuiltinOp != Builtin::BI__builtin_bcmp && 11944 1.1 joerg BuiltinOp != Builtin::BI__builtin_wmemcmp); 11945 1.1 joerg bool IsWide = BuiltinOp == Builtin::BIwcscmp || 11946 1.1 joerg BuiltinOp == Builtin::BIwcsncmp || 11947 1.1 joerg BuiltinOp == Builtin::BIwmemcmp || 11948 1.1 joerg BuiltinOp == Builtin::BI__builtin_wcscmp || 11949 1.1 joerg BuiltinOp == Builtin::BI__builtin_wcsncmp || 11950 1.1 joerg BuiltinOp == Builtin::BI__builtin_wmemcmp; 11951 1.1 joerg 11952 1.1 joerg for (; MaxLength; --MaxLength) { 11953 1.1 joerg APValue Char1, Char2; 11954 1.1 joerg if (!ReadCurElems(Char1, Char2)) 11955 1.1 joerg return false; 11956 1.1.1.2 joerg if (Char1.getInt().ne(Char2.getInt())) { 11957 1.1 joerg if (IsWide) // wmemcmp compares with wchar_t signedness. 11958 1.1 joerg return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E); 11959 1.1 joerg // memcmp always compares unsigned chars. 11960 1.1 joerg return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E); 11961 1.1 joerg } 11962 1.1 joerg if (StopAtNull && !Char1.getInt()) 11963 1.1 joerg return Success(0, E); 11964 1.1 joerg assert(!(StopAtNull && !Char2.getInt())); 11965 1.1 joerg if (!AdvanceElems()) 11966 1.1 joerg return false; 11967 1.1 joerg } 11968 1.1 joerg // We hit the strncmp / memcmp limit. 11969 1.1 joerg return Success(0, E); 11970 1.1 joerg } 11971 1.1 joerg 11972 1.1 joerg case Builtin::BI__atomic_always_lock_free: 11973 1.1 joerg case Builtin::BI__atomic_is_lock_free: 11974 1.1 joerg case Builtin::BI__c11_atomic_is_lock_free: { 11975 1.1 joerg APSInt SizeVal; 11976 1.1 joerg if (!EvaluateInteger(E->getArg(0), SizeVal, Info)) 11977 1.1 joerg return false; 11978 1.1 joerg 11979 1.1 joerg // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power 11980 1.1.1.2 joerg // of two less than or equal to the maximum inline atomic width, we know it 11981 1.1.1.2 joerg // is lock-free. If the size isn't a power of two, or greater than the 11982 1.1 joerg // maximum alignment where we promote atomics, we know it is not lock-free 11983 1.1 joerg // (at least not in the sense of atomic_is_lock_free). Otherwise, 11984 1.1 joerg // the answer can only be determined at runtime; for example, 16-byte 11985 1.1 joerg // atomics have lock-free implementations on some, but not all, 11986 1.1 joerg // x86-64 processors. 11987 1.1 joerg 11988 1.1 joerg // Check power-of-two. 11989 1.1 joerg CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue()); 11990 1.1 joerg if (Size.isPowerOfTwo()) { 11991 1.1 joerg // Check against inlining width. 11992 1.1 joerg unsigned InlineWidthBits = 11993 1.1 joerg Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth(); 11994 1.1 joerg if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) { 11995 1.1 joerg if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free || 11996 1.1 joerg Size == CharUnits::One() || 11997 1.1 joerg E->getArg(1)->isNullPointerConstant(Info.Ctx, 11998 1.1 joerg Expr::NPC_NeverValueDependent)) 11999 1.1 joerg // OK, we will inline appropriately-aligned operations of this size, 12000 1.1 joerg // and _Atomic(T) is appropriately-aligned. 12001 1.1 joerg return Success(1, E); 12002 1.1 joerg 12003 1.1 joerg QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()-> 12004 1.1 joerg castAs<PointerType>()->getPointeeType(); 12005 1.1 joerg if (!PointeeType->isIncompleteType() && 12006 1.1 joerg Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) { 12007 1.1 joerg // OK, we will inline operations on this object. 12008 1.1 joerg return Success(1, E); 12009 1.1 joerg } 12010 1.1 joerg } 12011 1.1 joerg } 12012 1.1 joerg 12013 1.1 joerg return BuiltinOp == Builtin::BI__atomic_always_lock_free ? 12014 1.1 joerg Success(0, E) : Error(E); 12015 1.1 joerg } 12016 1.1 joerg case Builtin::BI__builtin_add_overflow: 12017 1.1 joerg case Builtin::BI__builtin_sub_overflow: 12018 1.1 joerg case Builtin::BI__builtin_mul_overflow: 12019 1.1 joerg case Builtin::BI__builtin_sadd_overflow: 12020 1.1 joerg case Builtin::BI__builtin_uadd_overflow: 12021 1.1 joerg case Builtin::BI__builtin_uaddl_overflow: 12022 1.1 joerg case Builtin::BI__builtin_uaddll_overflow: 12023 1.1 joerg case Builtin::BI__builtin_usub_overflow: 12024 1.1 joerg case Builtin::BI__builtin_usubl_overflow: 12025 1.1 joerg case Builtin::BI__builtin_usubll_overflow: 12026 1.1 joerg case Builtin::BI__builtin_umul_overflow: 12027 1.1 joerg case Builtin::BI__builtin_umull_overflow: 12028 1.1 joerg case Builtin::BI__builtin_umulll_overflow: 12029 1.1 joerg case Builtin::BI__builtin_saddl_overflow: 12030 1.1 joerg case Builtin::BI__builtin_saddll_overflow: 12031 1.1 joerg case Builtin::BI__builtin_ssub_overflow: 12032 1.1 joerg case Builtin::BI__builtin_ssubl_overflow: 12033 1.1 joerg case Builtin::BI__builtin_ssubll_overflow: 12034 1.1 joerg case Builtin::BI__builtin_smul_overflow: 12035 1.1 joerg case Builtin::BI__builtin_smull_overflow: 12036 1.1 joerg case Builtin::BI__builtin_smulll_overflow: { 12037 1.1 joerg LValue ResultLValue; 12038 1.1 joerg APSInt LHS, RHS; 12039 1.1 joerg 12040 1.1 joerg QualType ResultType = E->getArg(2)->getType()->getPointeeType(); 12041 1.1 joerg if (!EvaluateInteger(E->getArg(0), LHS, Info) || 12042 1.1 joerg !EvaluateInteger(E->getArg(1), RHS, Info) || 12043 1.1 joerg !EvaluatePointer(E->getArg(2), ResultLValue, Info)) 12044 1.1 joerg return false; 12045 1.1 joerg 12046 1.1 joerg APSInt Result; 12047 1.1 joerg bool DidOverflow = false; 12048 1.1 joerg 12049 1.1 joerg // If the types don't have to match, enlarge all 3 to the largest of them. 12050 1.1 joerg if (BuiltinOp == Builtin::BI__builtin_add_overflow || 12051 1.1 joerg BuiltinOp == Builtin::BI__builtin_sub_overflow || 12052 1.1 joerg BuiltinOp == Builtin::BI__builtin_mul_overflow) { 12053 1.1 joerg bool IsSigned = LHS.isSigned() || RHS.isSigned() || 12054 1.1 joerg ResultType->isSignedIntegerOrEnumerationType(); 12055 1.1 joerg bool AllSigned = LHS.isSigned() && RHS.isSigned() && 12056 1.1 joerg ResultType->isSignedIntegerOrEnumerationType(); 12057 1.1 joerg uint64_t LHSSize = LHS.getBitWidth(); 12058 1.1 joerg uint64_t RHSSize = RHS.getBitWidth(); 12059 1.1 joerg uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType); 12060 1.1 joerg uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize); 12061 1.1 joerg 12062 1.1 joerg // Add an additional bit if the signedness isn't uniformly agreed to. We 12063 1.1 joerg // could do this ONLY if there is a signed and an unsigned that both have 12064 1.1 joerg // MaxBits, but the code to check that is pretty nasty. The issue will be 12065 1.1 joerg // caught in the shrink-to-result later anyway. 12066 1.1 joerg if (IsSigned && !AllSigned) 12067 1.1 joerg ++MaxBits; 12068 1.1 joerg 12069 1.1 joerg LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned); 12070 1.1 joerg RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned); 12071 1.1 joerg Result = APSInt(MaxBits, !IsSigned); 12072 1.1 joerg } 12073 1.1 joerg 12074 1.1 joerg // Find largest int. 12075 1.1 joerg switch (BuiltinOp) { 12076 1.1 joerg default: 12077 1.1 joerg llvm_unreachable("Invalid value for BuiltinOp"); 12078 1.1 joerg case Builtin::BI__builtin_add_overflow: 12079 1.1 joerg case Builtin::BI__builtin_sadd_overflow: 12080 1.1 joerg case Builtin::BI__builtin_saddl_overflow: 12081 1.1 joerg case Builtin::BI__builtin_saddll_overflow: 12082 1.1 joerg case Builtin::BI__builtin_uadd_overflow: 12083 1.1 joerg case Builtin::BI__builtin_uaddl_overflow: 12084 1.1 joerg case Builtin::BI__builtin_uaddll_overflow: 12085 1.1 joerg Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow) 12086 1.1 joerg : LHS.uadd_ov(RHS, DidOverflow); 12087 1.1 joerg break; 12088 1.1 joerg case Builtin::BI__builtin_sub_overflow: 12089 1.1 joerg case Builtin::BI__builtin_ssub_overflow: 12090 1.1 joerg case Builtin::BI__builtin_ssubl_overflow: 12091 1.1 joerg case Builtin::BI__builtin_ssubll_overflow: 12092 1.1 joerg case Builtin::BI__builtin_usub_overflow: 12093 1.1 joerg case Builtin::BI__builtin_usubl_overflow: 12094 1.1 joerg case Builtin::BI__builtin_usubll_overflow: 12095 1.1 joerg Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow) 12096 1.1 joerg : LHS.usub_ov(RHS, DidOverflow); 12097 1.1 joerg break; 12098 1.1 joerg case Builtin::BI__builtin_mul_overflow: 12099 1.1 joerg case Builtin::BI__builtin_smul_overflow: 12100 1.1 joerg case Builtin::BI__builtin_smull_overflow: 12101 1.1 joerg case Builtin::BI__builtin_smulll_overflow: 12102 1.1 joerg case Builtin::BI__builtin_umul_overflow: 12103 1.1 joerg case Builtin::BI__builtin_umull_overflow: 12104 1.1 joerg case Builtin::BI__builtin_umulll_overflow: 12105 1.1 joerg Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow) 12106 1.1 joerg : LHS.umul_ov(RHS, DidOverflow); 12107 1.1 joerg break; 12108 1.1 joerg } 12109 1.1 joerg 12110 1.1 joerg // In the case where multiple sizes are allowed, truncate and see if 12111 1.1 joerg // the values are the same. 12112 1.1 joerg if (BuiltinOp == Builtin::BI__builtin_add_overflow || 12113 1.1 joerg BuiltinOp == Builtin::BI__builtin_sub_overflow || 12114 1.1 joerg BuiltinOp == Builtin::BI__builtin_mul_overflow) { 12115 1.1 joerg // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead, 12116 1.1 joerg // since it will give us the behavior of a TruncOrSelf in the case where 12117 1.1 joerg // its parameter <= its size. We previously set Result to be at least the 12118 1.1 joerg // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth 12119 1.1 joerg // will work exactly like TruncOrSelf. 12120 1.1 joerg APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType)); 12121 1.1 joerg Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType()); 12122 1.1 joerg 12123 1.1 joerg if (!APSInt::isSameValue(Temp, Result)) 12124 1.1 joerg DidOverflow = true; 12125 1.1 joerg Result = Temp; 12126 1.1 joerg } 12127 1.1 joerg 12128 1.1 joerg APValue APV{Result}; 12129 1.1 joerg if (!handleAssignment(Info, E, ResultLValue, ResultType, APV)) 12130 1.1 joerg return false; 12131 1.1 joerg return Success(DidOverflow, E); 12132 1.1 joerg } 12133 1.1 joerg } 12134 1.1 joerg } 12135 1.1 joerg 12136 1.1 joerg /// Determine whether this is a pointer past the end of the complete 12137 1.1 joerg /// object referred to by the lvalue. 12138 1.1 joerg static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx, 12139 1.1 joerg const LValue &LV) { 12140 1.1 joerg // A null pointer can be viewed as being "past the end" but we don't 12141 1.1 joerg // choose to look at it that way here. 12142 1.1 joerg if (!LV.getLValueBase()) 12143 1.1 joerg return false; 12144 1.1 joerg 12145 1.1 joerg // If the designator is valid and refers to a subobject, we're not pointing 12146 1.1 joerg // past the end. 12147 1.1 joerg if (!LV.getLValueDesignator().Invalid && 12148 1.1 joerg !LV.getLValueDesignator().isOnePastTheEnd()) 12149 1.1 joerg return false; 12150 1.1 joerg 12151 1.1 joerg // A pointer to an incomplete type might be past-the-end if the type's size is 12152 1.1 joerg // zero. We cannot tell because the type is incomplete. 12153 1.1 joerg QualType Ty = getType(LV.getLValueBase()); 12154 1.1 joerg if (Ty->isIncompleteType()) 12155 1.1 joerg return true; 12156 1.1 joerg 12157 1.1 joerg // We're a past-the-end pointer if we point to the byte after the object, 12158 1.1 joerg // no matter what our type or path is. 12159 1.1 joerg auto Size = Ctx.getTypeSizeInChars(Ty); 12160 1.1 joerg return LV.getLValueOffset() == Size; 12161 1.1 joerg } 12162 1.1 joerg 12163 1.1 joerg namespace { 12164 1.1 joerg 12165 1.1 joerg /// Data recursive integer evaluator of certain binary operators. 12166 1.1 joerg /// 12167 1.1 joerg /// We use a data recursive algorithm for binary operators so that we are able 12168 1.1 joerg /// to handle extreme cases of chained binary operators without causing stack 12169 1.1 joerg /// overflow. 12170 1.1 joerg class DataRecursiveIntBinOpEvaluator { 12171 1.1 joerg struct EvalResult { 12172 1.1 joerg APValue Val; 12173 1.1 joerg bool Failed; 12174 1.1 joerg 12175 1.1 joerg EvalResult() : Failed(false) { } 12176 1.1 joerg 12177 1.1 joerg void swap(EvalResult &RHS) { 12178 1.1 joerg Val.swap(RHS.Val); 12179 1.1 joerg Failed = RHS.Failed; 12180 1.1 joerg RHS.Failed = false; 12181 1.1 joerg } 12182 1.1 joerg }; 12183 1.1 joerg 12184 1.1 joerg struct Job { 12185 1.1 joerg const Expr *E; 12186 1.1 joerg EvalResult LHSResult; // meaningful only for binary operator expression. 12187 1.1 joerg enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind; 12188 1.1 joerg 12189 1.1 joerg Job() = default; 12190 1.1 joerg Job(Job &&) = default; 12191 1.1 joerg 12192 1.1 joerg void startSpeculativeEval(EvalInfo &Info) { 12193 1.1 joerg SpecEvalRAII = SpeculativeEvaluationRAII(Info); 12194 1.1 joerg } 12195 1.1 joerg 12196 1.1 joerg private: 12197 1.1 joerg SpeculativeEvaluationRAII SpecEvalRAII; 12198 1.1 joerg }; 12199 1.1 joerg 12200 1.1 joerg SmallVector<Job, 16> Queue; 12201 1.1 joerg 12202 1.1 joerg IntExprEvaluator &IntEval; 12203 1.1 joerg EvalInfo &Info; 12204 1.1 joerg APValue &FinalResult; 12205 1.1 joerg 12206 1.1 joerg public: 12207 1.1 joerg DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result) 12208 1.1 joerg : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { } 12209 1.1 joerg 12210 1.1 joerg /// True if \param E is a binary operator that we are going to handle 12211 1.1 joerg /// data recursively. 12212 1.1 joerg /// We handle binary operators that are comma, logical, or that have operands 12213 1.1 joerg /// with integral or enumeration type. 12214 1.1 joerg static bool shouldEnqueue(const BinaryOperator *E) { 12215 1.1 joerg return E->getOpcode() == BO_Comma || E->isLogicalOp() || 12216 1.1 joerg (E->isRValue() && E->getType()->isIntegralOrEnumerationType() && 12217 1.1 joerg E->getLHS()->getType()->isIntegralOrEnumerationType() && 12218 1.1 joerg E->getRHS()->getType()->isIntegralOrEnumerationType()); 12219 1.1 joerg } 12220 1.1 joerg 12221 1.1 joerg bool Traverse(const BinaryOperator *E) { 12222 1.1 joerg enqueue(E); 12223 1.1 joerg EvalResult PrevResult; 12224 1.1 joerg while (!Queue.empty()) 12225 1.1 joerg process(PrevResult); 12226 1.1 joerg 12227 1.1 joerg if (PrevResult.Failed) return false; 12228 1.1 joerg 12229 1.1 joerg FinalResult.swap(PrevResult.Val); 12230 1.1 joerg return true; 12231 1.1 joerg } 12232 1.1 joerg 12233 1.1 joerg private: 12234 1.1 joerg bool Success(uint64_t Value, const Expr *E, APValue &Result) { 12235 1.1 joerg return IntEval.Success(Value, E, Result); 12236 1.1 joerg } 12237 1.1 joerg bool Success(const APSInt &Value, const Expr *E, APValue &Result) { 12238 1.1 joerg return IntEval.Success(Value, E, Result); 12239 1.1 joerg } 12240 1.1 joerg bool Error(const Expr *E) { 12241 1.1 joerg return IntEval.Error(E); 12242 1.1 joerg } 12243 1.1 joerg bool Error(const Expr *E, diag::kind D) { 12244 1.1 joerg return IntEval.Error(E, D); 12245 1.1 joerg } 12246 1.1 joerg 12247 1.1 joerg OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 12248 1.1 joerg return Info.CCEDiag(E, D); 12249 1.1 joerg } 12250 1.1 joerg 12251 1.1 joerg // Returns true if visiting the RHS is necessary, false otherwise. 12252 1.1 joerg bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 12253 1.1 joerg bool &SuppressRHSDiags); 12254 1.1 joerg 12255 1.1 joerg bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 12256 1.1 joerg const BinaryOperator *E, APValue &Result); 12257 1.1 joerg 12258 1.1 joerg void EvaluateExpr(const Expr *E, EvalResult &Result) { 12259 1.1 joerg Result.Failed = !Evaluate(Result.Val, Info, E); 12260 1.1 joerg if (Result.Failed) 12261 1.1 joerg Result.Val = APValue(); 12262 1.1 joerg } 12263 1.1 joerg 12264 1.1 joerg void process(EvalResult &Result); 12265 1.1 joerg 12266 1.1 joerg void enqueue(const Expr *E) { 12267 1.1 joerg E = E->IgnoreParens(); 12268 1.1 joerg Queue.resize(Queue.size()+1); 12269 1.1 joerg Queue.back().E = E; 12270 1.1 joerg Queue.back().Kind = Job::AnyExprKind; 12271 1.1 joerg } 12272 1.1 joerg }; 12273 1.1 joerg 12274 1.1 joerg } 12275 1.1 joerg 12276 1.1 joerg bool DataRecursiveIntBinOpEvaluator:: 12277 1.1 joerg VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 12278 1.1 joerg bool &SuppressRHSDiags) { 12279 1.1 joerg if (E->getOpcode() == BO_Comma) { 12280 1.1 joerg // Ignore LHS but note if we could not evaluate it. 12281 1.1 joerg if (LHSResult.Failed) 12282 1.1 joerg return Info.noteSideEffect(); 12283 1.1 joerg return true; 12284 1.1 joerg } 12285 1.1 joerg 12286 1.1 joerg if (E->isLogicalOp()) { 12287 1.1 joerg bool LHSAsBool; 12288 1.1 joerg if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) { 12289 1.1 joerg // We were able to evaluate the LHS, see if we can get away with not 12290 1.1 joerg // evaluating the RHS: 0 && X -> 0, 1 || X -> 1 12291 1.1 joerg if (LHSAsBool == (E->getOpcode() == BO_LOr)) { 12292 1.1 joerg Success(LHSAsBool, E, LHSResult.Val); 12293 1.1 joerg return false; // Ignore RHS 12294 1.1 joerg } 12295 1.1 joerg } else { 12296 1.1 joerg LHSResult.Failed = true; 12297 1.1 joerg 12298 1.1 joerg // Since we weren't able to evaluate the left hand side, it 12299 1.1 joerg // might have had side effects. 12300 1.1 joerg if (!Info.noteSideEffect()) 12301 1.1 joerg return false; 12302 1.1 joerg 12303 1.1 joerg // We can't evaluate the LHS; however, sometimes the result 12304 1.1 joerg // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 12305 1.1 joerg // Don't ignore RHS and suppress diagnostics from this arm. 12306 1.1 joerg SuppressRHSDiags = true; 12307 1.1 joerg } 12308 1.1 joerg 12309 1.1 joerg return true; 12310 1.1 joerg } 12311 1.1 joerg 12312 1.1 joerg assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 12313 1.1 joerg E->getRHS()->getType()->isIntegralOrEnumerationType()); 12314 1.1 joerg 12315 1.1 joerg if (LHSResult.Failed && !Info.noteFailure()) 12316 1.1 joerg return false; // Ignore RHS; 12317 1.1 joerg 12318 1.1 joerg return true; 12319 1.1 joerg } 12320 1.1 joerg 12321 1.1 joerg static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index, 12322 1.1 joerg bool IsSub) { 12323 1.1 joerg // Compute the new offset in the appropriate width, wrapping at 64 bits. 12324 1.1 joerg // FIXME: When compiling for a 32-bit target, we should use 32-bit 12325 1.1 joerg // offsets. 12326 1.1 joerg assert(!LVal.hasLValuePath() && "have designator for integer lvalue"); 12327 1.1 joerg CharUnits &Offset = LVal.getLValueOffset(); 12328 1.1 joerg uint64_t Offset64 = Offset.getQuantity(); 12329 1.1 joerg uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); 12330 1.1 joerg Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64 12331 1.1 joerg : Offset64 + Index64); 12332 1.1 joerg } 12333 1.1 joerg 12334 1.1 joerg bool DataRecursiveIntBinOpEvaluator:: 12335 1.1 joerg VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 12336 1.1 joerg const BinaryOperator *E, APValue &Result) { 12337 1.1 joerg if (E->getOpcode() == BO_Comma) { 12338 1.1 joerg if (RHSResult.Failed) 12339 1.1 joerg return false; 12340 1.1 joerg Result = RHSResult.Val; 12341 1.1 joerg return true; 12342 1.1 joerg } 12343 1.1 joerg 12344 1.1 joerg if (E->isLogicalOp()) { 12345 1.1 joerg bool lhsResult, rhsResult; 12346 1.1 joerg bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult); 12347 1.1 joerg bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult); 12348 1.1 joerg 12349 1.1 joerg if (LHSIsOK) { 12350 1.1 joerg if (RHSIsOK) { 12351 1.1 joerg if (E->getOpcode() == BO_LOr) 12352 1.1 joerg return Success(lhsResult || rhsResult, E, Result); 12353 1.1 joerg else 12354 1.1 joerg return Success(lhsResult && rhsResult, E, Result); 12355 1.1 joerg } 12356 1.1 joerg } else { 12357 1.1 joerg if (RHSIsOK) { 12358 1.1 joerg // We can't evaluate the LHS; however, sometimes the result 12359 1.1 joerg // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 12360 1.1 joerg if (rhsResult == (E->getOpcode() == BO_LOr)) 12361 1.1 joerg return Success(rhsResult, E, Result); 12362 1.1 joerg } 12363 1.1 joerg } 12364 1.1 joerg 12365 1.1 joerg return false; 12366 1.1 joerg } 12367 1.1 joerg 12368 1.1 joerg assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 12369 1.1 joerg E->getRHS()->getType()->isIntegralOrEnumerationType()); 12370 1.1 joerg 12371 1.1 joerg if (LHSResult.Failed || RHSResult.Failed) 12372 1.1 joerg return false; 12373 1.1 joerg 12374 1.1 joerg const APValue &LHSVal = LHSResult.Val; 12375 1.1 joerg const APValue &RHSVal = RHSResult.Val; 12376 1.1 joerg 12377 1.1 joerg // Handle cases like (unsigned long)&a + 4. 12378 1.1 joerg if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) { 12379 1.1 joerg Result = LHSVal; 12380 1.1 joerg addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub); 12381 1.1 joerg return true; 12382 1.1 joerg } 12383 1.1 joerg 12384 1.1 joerg // Handle cases like 4 + (unsigned long)&a 12385 1.1 joerg if (E->getOpcode() == BO_Add && 12386 1.1 joerg RHSVal.isLValue() && LHSVal.isInt()) { 12387 1.1 joerg Result = RHSVal; 12388 1.1 joerg addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false); 12389 1.1 joerg return true; 12390 1.1 joerg } 12391 1.1 joerg 12392 1.1 joerg if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) { 12393 1.1 joerg // Handle (intptr_t)&&A - (intptr_t)&&B. 12394 1.1 joerg if (!LHSVal.getLValueOffset().isZero() || 12395 1.1 joerg !RHSVal.getLValueOffset().isZero()) 12396 1.1 joerg return false; 12397 1.1 joerg const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>(); 12398 1.1 joerg const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>(); 12399 1.1 joerg if (!LHSExpr || !RHSExpr) 12400 1.1 joerg return false; 12401 1.1 joerg const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 12402 1.1 joerg const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 12403 1.1 joerg if (!LHSAddrExpr || !RHSAddrExpr) 12404 1.1 joerg return false; 12405 1.1 joerg // Make sure both labels come from the same function. 12406 1.1 joerg if (LHSAddrExpr->getLabel()->getDeclContext() != 12407 1.1 joerg RHSAddrExpr->getLabel()->getDeclContext()) 12408 1.1 joerg return false; 12409 1.1 joerg Result = APValue(LHSAddrExpr, RHSAddrExpr); 12410 1.1 joerg return true; 12411 1.1 joerg } 12412 1.1 joerg 12413 1.1 joerg // All the remaining cases expect both operands to be an integer 12414 1.1 joerg if (!LHSVal.isInt() || !RHSVal.isInt()) 12415 1.1 joerg return Error(E); 12416 1.1 joerg 12417 1.1 joerg // Set up the width and signedness manually, in case it can't be deduced 12418 1.1 joerg // from the operation we're performing. 12419 1.1 joerg // FIXME: Don't do this in the cases where we can deduce it. 12420 1.1 joerg APSInt Value(Info.Ctx.getIntWidth(E->getType()), 12421 1.1 joerg E->getType()->isUnsignedIntegerOrEnumerationType()); 12422 1.1 joerg if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(), 12423 1.1 joerg RHSVal.getInt(), Value)) 12424 1.1 joerg return false; 12425 1.1 joerg return Success(Value, E, Result); 12426 1.1 joerg } 12427 1.1 joerg 12428 1.1 joerg void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) { 12429 1.1 joerg Job &job = Queue.back(); 12430 1.1 joerg 12431 1.1 joerg switch (job.Kind) { 12432 1.1 joerg case Job::AnyExprKind: { 12433 1.1 joerg if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) { 12434 1.1 joerg if (shouldEnqueue(Bop)) { 12435 1.1 joerg job.Kind = Job::BinOpKind; 12436 1.1 joerg enqueue(Bop->getLHS()); 12437 1.1 joerg return; 12438 1.1 joerg } 12439 1.1 joerg } 12440 1.1 joerg 12441 1.1 joerg EvaluateExpr(job.E, Result); 12442 1.1 joerg Queue.pop_back(); 12443 1.1 joerg return; 12444 1.1 joerg } 12445 1.1 joerg 12446 1.1 joerg case Job::BinOpKind: { 12447 1.1 joerg const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 12448 1.1 joerg bool SuppressRHSDiags = false; 12449 1.1 joerg if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) { 12450 1.1 joerg Queue.pop_back(); 12451 1.1 joerg return; 12452 1.1 joerg } 12453 1.1 joerg if (SuppressRHSDiags) 12454 1.1 joerg job.startSpeculativeEval(Info); 12455 1.1 joerg job.LHSResult.swap(Result); 12456 1.1 joerg job.Kind = Job::BinOpVisitedLHSKind; 12457 1.1 joerg enqueue(Bop->getRHS()); 12458 1.1 joerg return; 12459 1.1 joerg } 12460 1.1 joerg 12461 1.1 joerg case Job::BinOpVisitedLHSKind: { 12462 1.1 joerg const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 12463 1.1 joerg EvalResult RHS; 12464 1.1 joerg RHS.swap(Result); 12465 1.1 joerg Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val); 12466 1.1 joerg Queue.pop_back(); 12467 1.1 joerg return; 12468 1.1 joerg } 12469 1.1 joerg } 12470 1.1 joerg 12471 1.1 joerg llvm_unreachable("Invalid Job::Kind!"); 12472 1.1 joerg } 12473 1.1 joerg 12474 1.1 joerg namespace { 12475 1.1.1.2 joerg enum class CmpResult { 12476 1.1.1.2 joerg Unequal, 12477 1.1.1.2 joerg Less, 12478 1.1.1.2 joerg Equal, 12479 1.1.1.2 joerg Greater, 12480 1.1.1.2 joerg Unordered, 12481 1.1 joerg }; 12482 1.1 joerg } 12483 1.1 joerg 12484 1.1 joerg template <class SuccessCB, class AfterCB> 12485 1.1 joerg static bool 12486 1.1 joerg EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E, 12487 1.1 joerg SuccessCB &&Success, AfterCB &&DoAfter) { 12488 1.1.1.2 joerg assert(!E->isValueDependent()); 12489 1.1 joerg assert(E->isComparisonOp() && "expected comparison operator"); 12490 1.1 joerg assert((E->getOpcode() == BO_Cmp || 12491 1.1 joerg E->getType()->isIntegralOrEnumerationType()) && 12492 1.1 joerg "unsupported binary expression evaluation"); 12493 1.1 joerg auto Error = [&](const Expr *E) { 12494 1.1 joerg Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 12495 1.1 joerg return false; 12496 1.1 joerg }; 12497 1.1 joerg 12498 1.1.1.2 joerg bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp; 12499 1.1 joerg bool IsEquality = E->isEqualityOp(); 12500 1.1 joerg 12501 1.1 joerg QualType LHSTy = E->getLHS()->getType(); 12502 1.1 joerg QualType RHSTy = E->getRHS()->getType(); 12503 1.1 joerg 12504 1.1 joerg if (LHSTy->isIntegralOrEnumerationType() && 12505 1.1 joerg RHSTy->isIntegralOrEnumerationType()) { 12506 1.1 joerg APSInt LHS, RHS; 12507 1.1 joerg bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info); 12508 1.1 joerg if (!LHSOK && !Info.noteFailure()) 12509 1.1 joerg return false; 12510 1.1 joerg if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK) 12511 1.1 joerg return false; 12512 1.1 joerg if (LHS < RHS) 12513 1.1.1.2 joerg return Success(CmpResult::Less, E); 12514 1.1 joerg if (LHS > RHS) 12515 1.1.1.2 joerg return Success(CmpResult::Greater, E); 12516 1.1.1.2 joerg return Success(CmpResult::Equal, E); 12517 1.1 joerg } 12518 1.1 joerg 12519 1.1 joerg if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) { 12520 1.1 joerg APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy)); 12521 1.1 joerg APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy)); 12522 1.1 joerg 12523 1.1 joerg bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info); 12524 1.1 joerg if (!LHSOK && !Info.noteFailure()) 12525 1.1 joerg return false; 12526 1.1 joerg if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK) 12527 1.1 joerg return false; 12528 1.1 joerg if (LHSFX < RHSFX) 12529 1.1.1.2 joerg return Success(CmpResult::Less, E); 12530 1.1 joerg if (LHSFX > RHSFX) 12531 1.1.1.2 joerg return Success(CmpResult::Greater, E); 12532 1.1.1.2 joerg return Success(CmpResult::Equal, E); 12533 1.1 joerg } 12534 1.1 joerg 12535 1.1 joerg if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) { 12536 1.1 joerg ComplexValue LHS, RHS; 12537 1.1 joerg bool LHSOK; 12538 1.1 joerg if (E->isAssignmentOp()) { 12539 1.1 joerg LValue LV; 12540 1.1 joerg EvaluateLValue(E->getLHS(), LV, Info); 12541 1.1 joerg LHSOK = false; 12542 1.1 joerg } else if (LHSTy->isRealFloatingType()) { 12543 1.1 joerg LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info); 12544 1.1 joerg if (LHSOK) { 12545 1.1 joerg LHS.makeComplexFloat(); 12546 1.1 joerg LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics()); 12547 1.1 joerg } 12548 1.1 joerg } else { 12549 1.1 joerg LHSOK = EvaluateComplex(E->getLHS(), LHS, Info); 12550 1.1 joerg } 12551 1.1 joerg if (!LHSOK && !Info.noteFailure()) 12552 1.1 joerg return false; 12553 1.1 joerg 12554 1.1 joerg if (E->getRHS()->getType()->isRealFloatingType()) { 12555 1.1 joerg if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK) 12556 1.1 joerg return false; 12557 1.1 joerg RHS.makeComplexFloat(); 12558 1.1 joerg RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics()); 12559 1.1 joerg } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 12560 1.1 joerg return false; 12561 1.1 joerg 12562 1.1 joerg if (LHS.isComplexFloat()) { 12563 1.1 joerg APFloat::cmpResult CR_r = 12564 1.1 joerg LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal()); 12565 1.1 joerg APFloat::cmpResult CR_i = 12566 1.1 joerg LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag()); 12567 1.1 joerg bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual; 12568 1.1.1.2 joerg return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E); 12569 1.1 joerg } else { 12570 1.1 joerg assert(IsEquality && "invalid complex comparison"); 12571 1.1 joerg bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() && 12572 1.1 joerg LHS.getComplexIntImag() == RHS.getComplexIntImag(); 12573 1.1.1.2 joerg return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E); 12574 1.1 joerg } 12575 1.1 joerg } 12576 1.1 joerg 12577 1.1 joerg if (LHSTy->isRealFloatingType() && 12578 1.1 joerg RHSTy->isRealFloatingType()) { 12579 1.1 joerg APFloat RHS(0.0), LHS(0.0); 12580 1.1 joerg 12581 1.1 joerg bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info); 12582 1.1 joerg if (!LHSOK && !Info.noteFailure()) 12583 1.1 joerg return false; 12584 1.1 joerg 12585 1.1 joerg if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK) 12586 1.1 joerg return false; 12587 1.1 joerg 12588 1.1 joerg assert(E->isComparisonOp() && "Invalid binary operator!"); 12589 1.1.1.2 joerg llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS); 12590 1.1.1.2 joerg if (!Info.InConstantContext && 12591 1.1.1.2 joerg APFloatCmpResult == APFloat::cmpUnordered && 12592 1.1.1.2 joerg E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained()) { 12593 1.1.1.2 joerg // Note: Compares may raise invalid in some cases involving NaN or sNaN. 12594 1.1.1.2 joerg Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict); 12595 1.1.1.2 joerg return false; 12596 1.1.1.2 joerg } 12597 1.1 joerg auto GetCmpRes = [&]() { 12598 1.1.1.2 joerg switch (APFloatCmpResult) { 12599 1.1 joerg case APFloat::cmpEqual: 12600 1.1.1.2 joerg return CmpResult::Equal; 12601 1.1 joerg case APFloat::cmpLessThan: 12602 1.1.1.2 joerg return CmpResult::Less; 12603 1.1 joerg case APFloat::cmpGreaterThan: 12604 1.1.1.2 joerg return CmpResult::Greater; 12605 1.1 joerg case APFloat::cmpUnordered: 12606 1.1.1.2 joerg return CmpResult::Unordered; 12607 1.1 joerg } 12608 1.1 joerg llvm_unreachable("Unrecognised APFloat::cmpResult enum"); 12609 1.1 joerg }; 12610 1.1 joerg return Success(GetCmpRes(), E); 12611 1.1 joerg } 12612 1.1 joerg 12613 1.1 joerg if (LHSTy->isPointerType() && RHSTy->isPointerType()) { 12614 1.1 joerg LValue LHSValue, RHSValue; 12615 1.1 joerg 12616 1.1 joerg bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); 12617 1.1 joerg if (!LHSOK && !Info.noteFailure()) 12618 1.1 joerg return false; 12619 1.1 joerg 12620 1.1 joerg if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) 12621 1.1 joerg return false; 12622 1.1 joerg 12623 1.1 joerg // Reject differing bases from the normal codepath; we special-case 12624 1.1 joerg // comparisons to null. 12625 1.1 joerg if (!HasSameBase(LHSValue, RHSValue)) { 12626 1.1 joerg // Inequalities and subtractions between unrelated pointers have 12627 1.1 joerg // unspecified or undefined behavior. 12628 1.1.1.2 joerg if (!IsEquality) { 12629 1.1.1.2 joerg Info.FFDiag(E, diag::note_constexpr_pointer_comparison_unspecified); 12630 1.1.1.2 joerg return false; 12631 1.1.1.2 joerg } 12632 1.1 joerg // A constant address may compare equal to the address of a symbol. 12633 1.1 joerg // The one exception is that address of an object cannot compare equal 12634 1.1 joerg // to a null pointer constant. 12635 1.1 joerg if ((!LHSValue.Base && !LHSValue.Offset.isZero()) || 12636 1.1 joerg (!RHSValue.Base && !RHSValue.Offset.isZero())) 12637 1.1 joerg return Error(E); 12638 1.1 joerg // It's implementation-defined whether distinct literals will have 12639 1.1 joerg // distinct addresses. In clang, the result of such a comparison is 12640 1.1 joerg // unspecified, so it is not a constant expression. However, we do know 12641 1.1 joerg // that the address of a literal will be non-null. 12642 1.1 joerg if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) && 12643 1.1 joerg LHSValue.Base && RHSValue.Base) 12644 1.1 joerg return Error(E); 12645 1.1 joerg // We can't tell whether weak symbols will end up pointing to the same 12646 1.1 joerg // object. 12647 1.1 joerg if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue)) 12648 1.1 joerg return Error(E); 12649 1.1 joerg // We can't compare the address of the start of one object with the 12650 1.1 joerg // past-the-end address of another object, per C++ DR1652. 12651 1.1 joerg if ((LHSValue.Base && LHSValue.Offset.isZero() && 12652 1.1 joerg isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) || 12653 1.1 joerg (RHSValue.Base && RHSValue.Offset.isZero() && 12654 1.1 joerg isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))) 12655 1.1 joerg return Error(E); 12656 1.1 joerg // We can't tell whether an object is at the same address as another 12657 1.1 joerg // zero sized object. 12658 1.1 joerg if ((RHSValue.Base && isZeroSized(LHSValue)) || 12659 1.1 joerg (LHSValue.Base && isZeroSized(RHSValue))) 12660 1.1 joerg return Error(E); 12661 1.1.1.2 joerg return Success(CmpResult::Unequal, E); 12662 1.1 joerg } 12663 1.1 joerg 12664 1.1 joerg const CharUnits &LHSOffset = LHSValue.getLValueOffset(); 12665 1.1 joerg const CharUnits &RHSOffset = RHSValue.getLValueOffset(); 12666 1.1 joerg 12667 1.1 joerg SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); 12668 1.1 joerg SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); 12669 1.1 joerg 12670 1.1 joerg // C++11 [expr.rel]p3: 12671 1.1 joerg // Pointers to void (after pointer conversions) can be compared, with a 12672 1.1 joerg // result defined as follows: If both pointers represent the same 12673 1.1 joerg // address or are both the null pointer value, the result is true if the 12674 1.1 joerg // operator is <= or >= and false otherwise; otherwise the result is 12675 1.1 joerg // unspecified. 12676 1.1 joerg // We interpret this as applying to pointers to *cv* void. 12677 1.1 joerg if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational) 12678 1.1 joerg Info.CCEDiag(E, diag::note_constexpr_void_comparison); 12679 1.1 joerg 12680 1.1 joerg // C++11 [expr.rel]p2: 12681 1.1 joerg // - If two pointers point to non-static data members of the same object, 12682 1.1 joerg // or to subobjects or array elements fo such members, recursively, the 12683 1.1 joerg // pointer to the later declared member compares greater provided the 12684 1.1 joerg // two members have the same access control and provided their class is 12685 1.1 joerg // not a union. 12686 1.1 joerg // [...] 12687 1.1 joerg // - Otherwise pointer comparisons are unspecified. 12688 1.1 joerg if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) { 12689 1.1 joerg bool WasArrayIndex; 12690 1.1 joerg unsigned Mismatch = FindDesignatorMismatch( 12691 1.1 joerg getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex); 12692 1.1 joerg // At the point where the designators diverge, the comparison has a 12693 1.1 joerg // specified value if: 12694 1.1 joerg // - we are comparing array indices 12695 1.1 joerg // - we are comparing fields of a union, or fields with the same access 12696 1.1 joerg // Otherwise, the result is unspecified and thus the comparison is not a 12697 1.1 joerg // constant expression. 12698 1.1 joerg if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() && 12699 1.1 joerg Mismatch < RHSDesignator.Entries.size()) { 12700 1.1 joerg const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]); 12701 1.1 joerg const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]); 12702 1.1 joerg if (!LF && !RF) 12703 1.1 joerg Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes); 12704 1.1 joerg else if (!LF) 12705 1.1 joerg Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 12706 1.1 joerg << getAsBaseClass(LHSDesignator.Entries[Mismatch]) 12707 1.1 joerg << RF->getParent() << RF; 12708 1.1 joerg else if (!RF) 12709 1.1 joerg Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 12710 1.1 joerg << getAsBaseClass(RHSDesignator.Entries[Mismatch]) 12711 1.1 joerg << LF->getParent() << LF; 12712 1.1 joerg else if (!LF->getParent()->isUnion() && 12713 1.1 joerg LF->getAccess() != RF->getAccess()) 12714 1.1 joerg Info.CCEDiag(E, 12715 1.1 joerg diag::note_constexpr_pointer_comparison_differing_access) 12716 1.1 joerg << LF << LF->getAccess() << RF << RF->getAccess() 12717 1.1 joerg << LF->getParent(); 12718 1.1 joerg } 12719 1.1 joerg } 12720 1.1 joerg 12721 1.1 joerg // The comparison here must be unsigned, and performed with the same 12722 1.1 joerg // width as the pointer. 12723 1.1 joerg unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy); 12724 1.1 joerg uint64_t CompareLHS = LHSOffset.getQuantity(); 12725 1.1 joerg uint64_t CompareRHS = RHSOffset.getQuantity(); 12726 1.1 joerg assert(PtrSize <= 64 && "Unexpected pointer width"); 12727 1.1 joerg uint64_t Mask = ~0ULL >> (64 - PtrSize); 12728 1.1 joerg CompareLHS &= Mask; 12729 1.1 joerg CompareRHS &= Mask; 12730 1.1 joerg 12731 1.1 joerg // If there is a base and this is a relational operator, we can only 12732 1.1 joerg // compare pointers within the object in question; otherwise, the result 12733 1.1 joerg // depends on where the object is located in memory. 12734 1.1 joerg if (!LHSValue.Base.isNull() && IsRelational) { 12735 1.1 joerg QualType BaseTy = getType(LHSValue.Base); 12736 1.1 joerg if (BaseTy->isIncompleteType()) 12737 1.1 joerg return Error(E); 12738 1.1 joerg CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy); 12739 1.1 joerg uint64_t OffsetLimit = Size.getQuantity(); 12740 1.1 joerg if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit) 12741 1.1 joerg return Error(E); 12742 1.1 joerg } 12743 1.1 joerg 12744 1.1 joerg if (CompareLHS < CompareRHS) 12745 1.1.1.2 joerg return Success(CmpResult::Less, E); 12746 1.1 joerg if (CompareLHS > CompareRHS) 12747 1.1.1.2 joerg return Success(CmpResult::Greater, E); 12748 1.1.1.2 joerg return Success(CmpResult::Equal, E); 12749 1.1 joerg } 12750 1.1 joerg 12751 1.1 joerg if (LHSTy->isMemberPointerType()) { 12752 1.1 joerg assert(IsEquality && "unexpected member pointer operation"); 12753 1.1 joerg assert(RHSTy->isMemberPointerType() && "invalid comparison"); 12754 1.1 joerg 12755 1.1 joerg MemberPtr LHSValue, RHSValue; 12756 1.1 joerg 12757 1.1 joerg bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info); 12758 1.1 joerg if (!LHSOK && !Info.noteFailure()) 12759 1.1 joerg return false; 12760 1.1 joerg 12761 1.1 joerg if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK) 12762 1.1 joerg return false; 12763 1.1 joerg 12764 1.1 joerg // C++11 [expr.eq]p2: 12765 1.1 joerg // If both operands are null, they compare equal. Otherwise if only one is 12766 1.1 joerg // null, they compare unequal. 12767 1.1 joerg if (!LHSValue.getDecl() || !RHSValue.getDecl()) { 12768 1.1 joerg bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl(); 12769 1.1.1.2 joerg return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E); 12770 1.1 joerg } 12771 1.1 joerg 12772 1.1 joerg // Otherwise if either is a pointer to a virtual member function, the 12773 1.1 joerg // result is unspecified. 12774 1.1 joerg if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl())) 12775 1.1 joerg if (MD->isVirtual()) 12776 1.1 joerg Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 12777 1.1 joerg if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl())) 12778 1.1 joerg if (MD->isVirtual()) 12779 1.1 joerg Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 12780 1.1 joerg 12781 1.1 joerg // Otherwise they compare equal if and only if they would refer to the 12782 1.1 joerg // same member of the same most derived object or the same subobject if 12783 1.1 joerg // they were dereferenced with a hypothetical object of the associated 12784 1.1 joerg // class type. 12785 1.1 joerg bool Equal = LHSValue == RHSValue; 12786 1.1.1.2 joerg return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E); 12787 1.1 joerg } 12788 1.1 joerg 12789 1.1 joerg if (LHSTy->isNullPtrType()) { 12790 1.1 joerg assert(E->isComparisonOp() && "unexpected nullptr operation"); 12791 1.1 joerg assert(RHSTy->isNullPtrType() && "missing pointer conversion"); 12792 1.1 joerg // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t 12793 1.1 joerg // are compared, the result is true of the operator is <=, >= or ==, and 12794 1.1 joerg // false otherwise. 12795 1.1.1.2 joerg return Success(CmpResult::Equal, E); 12796 1.1 joerg } 12797 1.1 joerg 12798 1.1 joerg return DoAfter(); 12799 1.1 joerg } 12800 1.1 joerg 12801 1.1 joerg bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) { 12802 1.1 joerg if (!CheckLiteralType(Info, E)) 12803 1.1 joerg return false; 12804 1.1 joerg 12805 1.1.1.2 joerg auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) { 12806 1.1.1.2 joerg ComparisonCategoryResult CCR; 12807 1.1.1.2 joerg switch (CR) { 12808 1.1.1.2 joerg case CmpResult::Unequal: 12809 1.1.1.2 joerg llvm_unreachable("should never produce Unequal for three-way comparison"); 12810 1.1.1.2 joerg case CmpResult::Less: 12811 1.1.1.2 joerg CCR = ComparisonCategoryResult::Less; 12812 1.1.1.2 joerg break; 12813 1.1.1.2 joerg case CmpResult::Equal: 12814 1.1.1.2 joerg CCR = ComparisonCategoryResult::Equal; 12815 1.1.1.2 joerg break; 12816 1.1.1.2 joerg case CmpResult::Greater: 12817 1.1.1.2 joerg CCR = ComparisonCategoryResult::Greater; 12818 1.1.1.2 joerg break; 12819 1.1.1.2 joerg case CmpResult::Unordered: 12820 1.1.1.2 joerg CCR = ComparisonCategoryResult::Unordered; 12821 1.1.1.2 joerg break; 12822 1.1.1.2 joerg } 12823 1.1 joerg // Evaluation succeeded. Lookup the information for the comparison category 12824 1.1 joerg // type and fetch the VarDecl for the result. 12825 1.1 joerg const ComparisonCategoryInfo &CmpInfo = 12826 1.1 joerg Info.Ctx.CompCategories.getInfoForType(E->getType()); 12827 1.1.1.2 joerg const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD; 12828 1.1 joerg // Check and evaluate the result as a constant expression. 12829 1.1 joerg LValue LV; 12830 1.1 joerg LV.set(VD); 12831 1.1 joerg if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) 12832 1.1 joerg return false; 12833 1.1.1.2 joerg return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result, 12834 1.1.1.2 joerg ConstantExprKind::Normal); 12835 1.1 joerg }; 12836 1.1 joerg return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { 12837 1.1 joerg return ExprEvaluatorBaseTy::VisitBinCmp(E); 12838 1.1 joerg }); 12839 1.1 joerg } 12840 1.1 joerg 12841 1.1 joerg bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 12842 1.1.1.2 joerg // We don't support assignment in C. C++ assignments don't get here because 12843 1.1.1.2 joerg // assignment is an lvalue in C++. 12844 1.1.1.2 joerg if (E->isAssignmentOp()) { 12845 1.1.1.2 joerg Error(E); 12846 1.1.1.2 joerg if (!Info.noteFailure()) 12847 1.1.1.2 joerg return false; 12848 1.1.1.2 joerg } 12849 1.1 joerg 12850 1.1 joerg if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E)) 12851 1.1 joerg return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E); 12852 1.1 joerg 12853 1.1 joerg assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() || 12854 1.1 joerg !E->getRHS()->getType()->isIntegralOrEnumerationType()) && 12855 1.1 joerg "DataRecursiveIntBinOpEvaluator should have handled integral types"); 12856 1.1 joerg 12857 1.1 joerg if (E->isComparisonOp()) { 12858 1.1.1.2 joerg // Evaluate builtin binary comparisons by evaluating them as three-way 12859 1.1 joerg // comparisons and then translating the result. 12860 1.1.1.2 joerg auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) { 12861 1.1.1.2 joerg assert((CR != CmpResult::Unequal || E->isEqualityOp()) && 12862 1.1.1.2 joerg "should only produce Unequal for equality comparisons"); 12863 1.1.1.2 joerg bool IsEqual = CR == CmpResult::Equal, 12864 1.1.1.2 joerg IsLess = CR == CmpResult::Less, 12865 1.1.1.2 joerg IsGreater = CR == CmpResult::Greater; 12866 1.1 joerg auto Op = E->getOpcode(); 12867 1.1 joerg switch (Op) { 12868 1.1 joerg default: 12869 1.1 joerg llvm_unreachable("unsupported binary operator"); 12870 1.1 joerg case BO_EQ: 12871 1.1 joerg case BO_NE: 12872 1.1 joerg return Success(IsEqual == (Op == BO_EQ), E); 12873 1.1.1.2 joerg case BO_LT: 12874 1.1.1.2 joerg return Success(IsLess, E); 12875 1.1.1.2 joerg case BO_GT: 12876 1.1.1.2 joerg return Success(IsGreater, E); 12877 1.1.1.2 joerg case BO_LE: 12878 1.1.1.2 joerg return Success(IsEqual || IsLess, E); 12879 1.1.1.2 joerg case BO_GE: 12880 1.1.1.2 joerg return Success(IsEqual || IsGreater, E); 12881 1.1 joerg } 12882 1.1 joerg }; 12883 1.1 joerg return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { 12884 1.1 joerg return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 12885 1.1 joerg }); 12886 1.1 joerg } 12887 1.1 joerg 12888 1.1 joerg QualType LHSTy = E->getLHS()->getType(); 12889 1.1 joerg QualType RHSTy = E->getRHS()->getType(); 12890 1.1 joerg 12891 1.1 joerg if (LHSTy->isPointerType() && RHSTy->isPointerType() && 12892 1.1 joerg E->getOpcode() == BO_Sub) { 12893 1.1 joerg LValue LHSValue, RHSValue; 12894 1.1 joerg 12895 1.1 joerg bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); 12896 1.1 joerg if (!LHSOK && !Info.noteFailure()) 12897 1.1 joerg return false; 12898 1.1 joerg 12899 1.1 joerg if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) 12900 1.1 joerg return false; 12901 1.1 joerg 12902 1.1 joerg // Reject differing bases from the normal codepath; we special-case 12903 1.1 joerg // comparisons to null. 12904 1.1 joerg if (!HasSameBase(LHSValue, RHSValue)) { 12905 1.1 joerg // Handle &&A - &&B. 12906 1.1 joerg if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero()) 12907 1.1 joerg return Error(E); 12908 1.1 joerg const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>(); 12909 1.1 joerg const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>(); 12910 1.1 joerg if (!LHSExpr || !RHSExpr) 12911 1.1 joerg return Error(E); 12912 1.1 joerg const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 12913 1.1 joerg const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 12914 1.1 joerg if (!LHSAddrExpr || !RHSAddrExpr) 12915 1.1 joerg return Error(E); 12916 1.1 joerg // Make sure both labels come from the same function. 12917 1.1 joerg if (LHSAddrExpr->getLabel()->getDeclContext() != 12918 1.1 joerg RHSAddrExpr->getLabel()->getDeclContext()) 12919 1.1 joerg return Error(E); 12920 1.1 joerg return Success(APValue(LHSAddrExpr, RHSAddrExpr), E); 12921 1.1 joerg } 12922 1.1 joerg const CharUnits &LHSOffset = LHSValue.getLValueOffset(); 12923 1.1 joerg const CharUnits &RHSOffset = RHSValue.getLValueOffset(); 12924 1.1 joerg 12925 1.1 joerg SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); 12926 1.1 joerg SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); 12927 1.1 joerg 12928 1.1 joerg // C++11 [expr.add]p6: 12929 1.1 joerg // Unless both pointers point to elements of the same array object, or 12930 1.1 joerg // one past the last element of the array object, the behavior is 12931 1.1 joerg // undefined. 12932 1.1 joerg if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && 12933 1.1 joerg !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator, 12934 1.1 joerg RHSDesignator)) 12935 1.1 joerg Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array); 12936 1.1 joerg 12937 1.1 joerg QualType Type = E->getLHS()->getType(); 12938 1.1 joerg QualType ElementType = Type->castAs<PointerType>()->getPointeeType(); 12939 1.1 joerg 12940 1.1 joerg CharUnits ElementSize; 12941 1.1 joerg if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize)) 12942 1.1 joerg return false; 12943 1.1 joerg 12944 1.1 joerg // As an extension, a type may have zero size (empty struct or union in 12945 1.1 joerg // C, array of zero length). Pointer subtraction in such cases has 12946 1.1 joerg // undefined behavior, so is not constant. 12947 1.1 joerg if (ElementSize.isZero()) { 12948 1.1 joerg Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size) 12949 1.1 joerg << ElementType; 12950 1.1 joerg return false; 12951 1.1 joerg } 12952 1.1 joerg 12953 1.1 joerg // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime, 12954 1.1 joerg // and produce incorrect results when it overflows. Such behavior 12955 1.1 joerg // appears to be non-conforming, but is common, so perhaps we should 12956 1.1 joerg // assume the standard intended for such cases to be undefined behavior 12957 1.1 joerg // and check for them. 12958 1.1 joerg 12959 1.1 joerg // Compute (LHSOffset - RHSOffset) / Size carefully, checking for 12960 1.1 joerg // overflow in the final conversion to ptrdiff_t. 12961 1.1 joerg APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false); 12962 1.1 joerg APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false); 12963 1.1 joerg APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), 12964 1.1 joerg false); 12965 1.1 joerg APSInt TrueResult = (LHS - RHS) / ElemSize; 12966 1.1 joerg APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType())); 12967 1.1 joerg 12968 1.1 joerg if (Result.extend(65) != TrueResult && 12969 1.1 joerg !HandleOverflow(Info, E, TrueResult, E->getType())) 12970 1.1 joerg return false; 12971 1.1 joerg return Success(Result, E); 12972 1.1 joerg } 12973 1.1 joerg 12974 1.1 joerg return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 12975 1.1 joerg } 12976 1.1 joerg 12977 1.1 joerg /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with 12978 1.1 joerg /// a result as the expression's type. 12979 1.1 joerg bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr( 12980 1.1 joerg const UnaryExprOrTypeTraitExpr *E) { 12981 1.1 joerg switch(E->getKind()) { 12982 1.1 joerg case UETT_PreferredAlignOf: 12983 1.1 joerg case UETT_AlignOf: { 12984 1.1 joerg if (E->isArgumentType()) 12985 1.1 joerg return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()), 12986 1.1 joerg E); 12987 1.1 joerg else 12988 1.1 joerg return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()), 12989 1.1 joerg E); 12990 1.1 joerg } 12991 1.1 joerg 12992 1.1 joerg case UETT_VecStep: { 12993 1.1 joerg QualType Ty = E->getTypeOfArgument(); 12994 1.1 joerg 12995 1.1 joerg if (Ty->isVectorType()) { 12996 1.1 joerg unsigned n = Ty->castAs<VectorType>()->getNumElements(); 12997 1.1 joerg 12998 1.1 joerg // The vec_step built-in functions that take a 3-component 12999 1.1 joerg // vector return 4. (OpenCL 1.1 spec 6.11.12) 13000 1.1 joerg if (n == 3) 13001 1.1 joerg n = 4; 13002 1.1 joerg 13003 1.1 joerg return Success(n, E); 13004 1.1 joerg } else 13005 1.1 joerg return Success(1, E); 13006 1.1 joerg } 13007 1.1 joerg 13008 1.1 joerg case UETT_SizeOf: { 13009 1.1 joerg QualType SrcTy = E->getTypeOfArgument(); 13010 1.1 joerg // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 13011 1.1 joerg // the result is the size of the referenced type." 13012 1.1 joerg if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>()) 13013 1.1 joerg SrcTy = Ref->getPointeeType(); 13014 1.1 joerg 13015 1.1 joerg CharUnits Sizeof; 13016 1.1 joerg if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof)) 13017 1.1 joerg return false; 13018 1.1 joerg return Success(Sizeof, E); 13019 1.1 joerg } 13020 1.1 joerg case UETT_OpenMPRequiredSimdAlign: 13021 1.1 joerg assert(E->isArgumentType()); 13022 1.1 joerg return Success( 13023 1.1 joerg Info.Ctx.toCharUnitsFromBits( 13024 1.1 joerg Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType())) 13025 1.1 joerg .getQuantity(), 13026 1.1 joerg E); 13027 1.1 joerg } 13028 1.1 joerg 13029 1.1 joerg llvm_unreachable("unknown expr/type trait"); 13030 1.1 joerg } 13031 1.1 joerg 13032 1.1 joerg bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) { 13033 1.1 joerg CharUnits Result; 13034 1.1 joerg unsigned n = OOE->getNumComponents(); 13035 1.1 joerg if (n == 0) 13036 1.1 joerg return Error(OOE); 13037 1.1 joerg QualType CurrentType = OOE->getTypeSourceInfo()->getType(); 13038 1.1 joerg for (unsigned i = 0; i != n; ++i) { 13039 1.1 joerg OffsetOfNode ON = OOE->getComponent(i); 13040 1.1 joerg switch (ON.getKind()) { 13041 1.1 joerg case OffsetOfNode::Array: { 13042 1.1 joerg const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex()); 13043 1.1 joerg APSInt IdxResult; 13044 1.1 joerg if (!EvaluateInteger(Idx, IdxResult, Info)) 13045 1.1 joerg return false; 13046 1.1 joerg const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType); 13047 1.1 joerg if (!AT) 13048 1.1 joerg return Error(OOE); 13049 1.1 joerg CurrentType = AT->getElementType(); 13050 1.1 joerg CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType); 13051 1.1 joerg Result += IdxResult.getSExtValue() * ElementSize; 13052 1.1 joerg break; 13053 1.1 joerg } 13054 1.1 joerg 13055 1.1 joerg case OffsetOfNode::Field: { 13056 1.1 joerg FieldDecl *MemberDecl = ON.getField(); 13057 1.1 joerg const RecordType *RT = CurrentType->getAs<RecordType>(); 13058 1.1 joerg if (!RT) 13059 1.1 joerg return Error(OOE); 13060 1.1 joerg RecordDecl *RD = RT->getDecl(); 13061 1.1 joerg if (RD->isInvalidDecl()) return false; 13062 1.1 joerg const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 13063 1.1 joerg unsigned i = MemberDecl->getFieldIndex(); 13064 1.1 joerg assert(i < RL.getFieldCount() && "offsetof field in wrong type"); 13065 1.1 joerg Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i)); 13066 1.1 joerg CurrentType = MemberDecl->getType().getNonReferenceType(); 13067 1.1 joerg break; 13068 1.1 joerg } 13069 1.1 joerg 13070 1.1 joerg case OffsetOfNode::Identifier: 13071 1.1 joerg llvm_unreachable("dependent __builtin_offsetof"); 13072 1.1 joerg 13073 1.1 joerg case OffsetOfNode::Base: { 13074 1.1 joerg CXXBaseSpecifier *BaseSpec = ON.getBase(); 13075 1.1 joerg if (BaseSpec->isVirtual()) 13076 1.1 joerg return Error(OOE); 13077 1.1 joerg 13078 1.1 joerg // Find the layout of the class whose base we are looking into. 13079 1.1 joerg const RecordType *RT = CurrentType->getAs<RecordType>(); 13080 1.1 joerg if (!RT) 13081 1.1 joerg return Error(OOE); 13082 1.1 joerg RecordDecl *RD = RT->getDecl(); 13083 1.1 joerg if (RD->isInvalidDecl()) return false; 13084 1.1 joerg const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 13085 1.1 joerg 13086 1.1 joerg // Find the base class itself. 13087 1.1 joerg CurrentType = BaseSpec->getType(); 13088 1.1 joerg const RecordType *BaseRT = CurrentType->getAs<RecordType>(); 13089 1.1 joerg if (!BaseRT) 13090 1.1 joerg return Error(OOE); 13091 1.1 joerg 13092 1.1 joerg // Add the offset to the base. 13093 1.1 joerg Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl())); 13094 1.1 joerg break; 13095 1.1 joerg } 13096 1.1 joerg } 13097 1.1 joerg } 13098 1.1 joerg return Success(Result, OOE); 13099 1.1 joerg } 13100 1.1 joerg 13101 1.1 joerg bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 13102 1.1 joerg switch (E->getOpcode()) { 13103 1.1 joerg default: 13104 1.1 joerg // Address, indirect, pre/post inc/dec, etc are not valid constant exprs. 13105 1.1 joerg // See C99 6.6p3. 13106 1.1 joerg return Error(E); 13107 1.1 joerg case UO_Extension: 13108 1.1 joerg // FIXME: Should extension allow i-c-e extension expressions in its scope? 13109 1.1 joerg // If so, we could clear the diagnostic ID. 13110 1.1 joerg return Visit(E->getSubExpr()); 13111 1.1 joerg case UO_Plus: 13112 1.1 joerg // The result is just the value. 13113 1.1 joerg return Visit(E->getSubExpr()); 13114 1.1 joerg case UO_Minus: { 13115 1.1 joerg if (!Visit(E->getSubExpr())) 13116 1.1 joerg return false; 13117 1.1 joerg if (!Result.isInt()) return Error(E); 13118 1.1 joerg const APSInt &Value = Result.getInt(); 13119 1.1 joerg if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() && 13120 1.1 joerg !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1), 13121 1.1 joerg E->getType())) 13122 1.1 joerg return false; 13123 1.1 joerg return Success(-Value, E); 13124 1.1 joerg } 13125 1.1 joerg case UO_Not: { 13126 1.1 joerg if (!Visit(E->getSubExpr())) 13127 1.1 joerg return false; 13128 1.1 joerg if (!Result.isInt()) return Error(E); 13129 1.1 joerg return Success(~Result.getInt(), E); 13130 1.1 joerg } 13131 1.1 joerg case UO_LNot: { 13132 1.1 joerg bool bres; 13133 1.1 joerg if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) 13134 1.1 joerg return false; 13135 1.1 joerg return Success(!bres, E); 13136 1.1 joerg } 13137 1.1 joerg } 13138 1.1 joerg } 13139 1.1 joerg 13140 1.1 joerg /// HandleCast - This is used to evaluate implicit or explicit casts where the 13141 1.1 joerg /// result type is integer. 13142 1.1 joerg bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) { 13143 1.1 joerg const Expr *SubExpr = E->getSubExpr(); 13144 1.1 joerg QualType DestType = E->getType(); 13145 1.1 joerg QualType SrcType = SubExpr->getType(); 13146 1.1 joerg 13147 1.1 joerg switch (E->getCastKind()) { 13148 1.1 joerg case CK_BaseToDerived: 13149 1.1 joerg case CK_DerivedToBase: 13150 1.1 joerg case CK_UncheckedDerivedToBase: 13151 1.1 joerg case CK_Dynamic: 13152 1.1 joerg case CK_ToUnion: 13153 1.1 joerg case CK_ArrayToPointerDecay: 13154 1.1 joerg case CK_FunctionToPointerDecay: 13155 1.1 joerg case CK_NullToPointer: 13156 1.1 joerg case CK_NullToMemberPointer: 13157 1.1 joerg case CK_BaseToDerivedMemberPointer: 13158 1.1 joerg case CK_DerivedToBaseMemberPointer: 13159 1.1 joerg case CK_ReinterpretMemberPointer: 13160 1.1 joerg case CK_ConstructorConversion: 13161 1.1 joerg case CK_IntegralToPointer: 13162 1.1 joerg case CK_ToVoid: 13163 1.1 joerg case CK_VectorSplat: 13164 1.1 joerg case CK_IntegralToFloating: 13165 1.1 joerg case CK_FloatingCast: 13166 1.1 joerg case CK_CPointerToObjCPointerCast: 13167 1.1 joerg case CK_BlockPointerToObjCPointerCast: 13168 1.1 joerg case CK_AnyPointerToBlockPointerCast: 13169 1.1 joerg case CK_ObjCObjectLValueCast: 13170 1.1 joerg case CK_FloatingRealToComplex: 13171 1.1 joerg case CK_FloatingComplexToReal: 13172 1.1 joerg case CK_FloatingComplexCast: 13173 1.1 joerg case CK_FloatingComplexToIntegralComplex: 13174 1.1 joerg case CK_IntegralRealToComplex: 13175 1.1 joerg case CK_IntegralComplexCast: 13176 1.1 joerg case CK_IntegralComplexToFloatingComplex: 13177 1.1 joerg case CK_BuiltinFnToFnPtr: 13178 1.1 joerg case CK_ZeroToOCLOpaqueType: 13179 1.1 joerg case CK_NonAtomicToAtomic: 13180 1.1 joerg case CK_AddressSpaceConversion: 13181 1.1 joerg case CK_IntToOCLSampler: 13182 1.1.1.2 joerg case CK_FloatingToFixedPoint: 13183 1.1.1.2 joerg case CK_FixedPointToFloating: 13184 1.1 joerg case CK_FixedPointCast: 13185 1.1 joerg case CK_IntegralToFixedPoint: 13186 1.1.1.2 joerg case CK_MatrixCast: 13187 1.1 joerg llvm_unreachable("invalid cast kind for integral value"); 13188 1.1 joerg 13189 1.1 joerg case CK_BitCast: 13190 1.1 joerg case CK_Dependent: 13191 1.1 joerg case CK_LValueBitCast: 13192 1.1 joerg case CK_ARCProduceObject: 13193 1.1 joerg case CK_ARCConsumeObject: 13194 1.1 joerg case CK_ARCReclaimReturnedObject: 13195 1.1 joerg case CK_ARCExtendBlockObject: 13196 1.1 joerg case CK_CopyAndAutoreleaseBlockObject: 13197 1.1 joerg return Error(E); 13198 1.1 joerg 13199 1.1 joerg case CK_UserDefinedConversion: 13200 1.1 joerg case CK_LValueToRValue: 13201 1.1 joerg case CK_AtomicToNonAtomic: 13202 1.1 joerg case CK_NoOp: 13203 1.1 joerg case CK_LValueToRValueBitCast: 13204 1.1 joerg return ExprEvaluatorBaseTy::VisitCastExpr(E); 13205 1.1 joerg 13206 1.1 joerg case CK_MemberPointerToBoolean: 13207 1.1 joerg case CK_PointerToBoolean: 13208 1.1 joerg case CK_IntegralToBoolean: 13209 1.1 joerg case CK_FloatingToBoolean: 13210 1.1 joerg case CK_BooleanToSignedIntegral: 13211 1.1 joerg case CK_FloatingComplexToBoolean: 13212 1.1 joerg case CK_IntegralComplexToBoolean: { 13213 1.1 joerg bool BoolResult; 13214 1.1 joerg if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info)) 13215 1.1 joerg return false; 13216 1.1 joerg uint64_t IntResult = BoolResult; 13217 1.1 joerg if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral) 13218 1.1 joerg IntResult = (uint64_t)-1; 13219 1.1 joerg return Success(IntResult, E); 13220 1.1 joerg } 13221 1.1 joerg 13222 1.1 joerg case CK_FixedPointToIntegral: { 13223 1.1 joerg APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType)); 13224 1.1 joerg if (!EvaluateFixedPoint(SubExpr, Src, Info)) 13225 1.1 joerg return false; 13226 1.1 joerg bool Overflowed; 13227 1.1 joerg llvm::APSInt Result = Src.convertToInt( 13228 1.1 joerg Info.Ctx.getIntWidth(DestType), 13229 1.1 joerg DestType->isSignedIntegerOrEnumerationType(), &Overflowed); 13230 1.1 joerg if (Overflowed && !HandleOverflow(Info, E, Result, DestType)) 13231 1.1 joerg return false; 13232 1.1 joerg return Success(Result, E); 13233 1.1 joerg } 13234 1.1 joerg 13235 1.1 joerg case CK_FixedPointToBoolean: { 13236 1.1 joerg // Unsigned padding does not affect this. 13237 1.1 joerg APValue Val; 13238 1.1 joerg if (!Evaluate(Val, Info, SubExpr)) 13239 1.1 joerg return false; 13240 1.1 joerg return Success(Val.getFixedPoint().getBoolValue(), E); 13241 1.1 joerg } 13242 1.1 joerg 13243 1.1 joerg case CK_IntegralCast: { 13244 1.1 joerg if (!Visit(SubExpr)) 13245 1.1 joerg return false; 13246 1.1 joerg 13247 1.1 joerg if (!Result.isInt()) { 13248 1.1 joerg // Allow casts of address-of-label differences if they are no-ops 13249 1.1 joerg // or narrowing. (The narrowing case isn't actually guaranteed to 13250 1.1 joerg // be constant-evaluatable except in some narrow cases which are hard 13251 1.1 joerg // to detect here. We let it through on the assumption the user knows 13252 1.1 joerg // what they are doing.) 13253 1.1 joerg if (Result.isAddrLabelDiff()) 13254 1.1 joerg return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType); 13255 1.1 joerg // Only allow casts of lvalues if they are lossless. 13256 1.1 joerg return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType); 13257 1.1 joerg } 13258 1.1 joerg 13259 1.1 joerg return Success(HandleIntToIntCast(Info, E, DestType, SrcType, 13260 1.1 joerg Result.getInt()), E); 13261 1.1 joerg } 13262 1.1 joerg 13263 1.1 joerg case CK_PointerToIntegral: { 13264 1.1 joerg CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 13265 1.1 joerg 13266 1.1 joerg LValue LV; 13267 1.1 joerg if (!EvaluatePointer(SubExpr, LV, Info)) 13268 1.1 joerg return false; 13269 1.1 joerg 13270 1.1 joerg if (LV.getLValueBase()) { 13271 1.1 joerg // Only allow based lvalue casts if they are lossless. 13272 1.1 joerg // FIXME: Allow a larger integer size than the pointer size, and allow 13273 1.1 joerg // narrowing back down to pointer width in subsequent integral casts. 13274 1.1 joerg // FIXME: Check integer type's active bits, not its type size. 13275 1.1 joerg if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType)) 13276 1.1 joerg return Error(E); 13277 1.1 joerg 13278 1.1 joerg LV.Designator.setInvalid(); 13279 1.1 joerg LV.moveInto(Result); 13280 1.1 joerg return true; 13281 1.1 joerg } 13282 1.1 joerg 13283 1.1 joerg APSInt AsInt; 13284 1.1 joerg APValue V; 13285 1.1 joerg LV.moveInto(V); 13286 1.1 joerg if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx)) 13287 1.1 joerg llvm_unreachable("Can't cast this!"); 13288 1.1 joerg 13289 1.1 joerg return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E); 13290 1.1 joerg } 13291 1.1 joerg 13292 1.1 joerg case CK_IntegralComplexToReal: { 13293 1.1 joerg ComplexValue C; 13294 1.1 joerg if (!EvaluateComplex(SubExpr, C, Info)) 13295 1.1 joerg return false; 13296 1.1 joerg return Success(C.getComplexIntReal(), E); 13297 1.1 joerg } 13298 1.1 joerg 13299 1.1 joerg case CK_FloatingToIntegral: { 13300 1.1 joerg APFloat F(0.0); 13301 1.1 joerg if (!EvaluateFloat(SubExpr, F, Info)) 13302 1.1 joerg return false; 13303 1.1 joerg 13304 1.1 joerg APSInt Value; 13305 1.1 joerg if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value)) 13306 1.1 joerg return false; 13307 1.1 joerg return Success(Value, E); 13308 1.1 joerg } 13309 1.1 joerg } 13310 1.1 joerg 13311 1.1 joerg llvm_unreachable("unknown cast resulting in integral value"); 13312 1.1 joerg } 13313 1.1 joerg 13314 1.1 joerg bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 13315 1.1 joerg if (E->getSubExpr()->getType()->isAnyComplexType()) { 13316 1.1 joerg ComplexValue LV; 13317 1.1 joerg if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 13318 1.1 joerg return false; 13319 1.1 joerg if (!LV.isComplexInt()) 13320 1.1 joerg return Error(E); 13321 1.1 joerg return Success(LV.getComplexIntReal(), E); 13322 1.1 joerg } 13323 1.1 joerg 13324 1.1 joerg return Visit(E->getSubExpr()); 13325 1.1 joerg } 13326 1.1 joerg 13327 1.1 joerg bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 13328 1.1 joerg if (E->getSubExpr()->getType()->isComplexIntegerType()) { 13329 1.1 joerg ComplexValue LV; 13330 1.1 joerg if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 13331 1.1 joerg return false; 13332 1.1 joerg if (!LV.isComplexInt()) 13333 1.1 joerg return Error(E); 13334 1.1 joerg return Success(LV.getComplexIntImag(), E); 13335 1.1 joerg } 13336 1.1 joerg 13337 1.1 joerg VisitIgnoredValue(E->getSubExpr()); 13338 1.1 joerg return Success(0, E); 13339 1.1 joerg } 13340 1.1 joerg 13341 1.1 joerg bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) { 13342 1.1 joerg return Success(E->getPackLength(), E); 13343 1.1 joerg } 13344 1.1 joerg 13345 1.1 joerg bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) { 13346 1.1 joerg return Success(E->getValue(), E); 13347 1.1 joerg } 13348 1.1 joerg 13349 1.1 joerg bool IntExprEvaluator::VisitConceptSpecializationExpr( 13350 1.1 joerg const ConceptSpecializationExpr *E) { 13351 1.1 joerg return Success(E->isSatisfied(), E); 13352 1.1 joerg } 13353 1.1 joerg 13354 1.1.1.2 joerg bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) { 13355 1.1.1.2 joerg return Success(E->isSatisfied(), E); 13356 1.1.1.2 joerg } 13357 1.1 joerg 13358 1.1 joerg bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 13359 1.1 joerg switch (E->getOpcode()) { 13360 1.1 joerg default: 13361 1.1 joerg // Invalid unary operators 13362 1.1 joerg return Error(E); 13363 1.1 joerg case UO_Plus: 13364 1.1 joerg // The result is just the value. 13365 1.1 joerg return Visit(E->getSubExpr()); 13366 1.1 joerg case UO_Minus: { 13367 1.1 joerg if (!Visit(E->getSubExpr())) return false; 13368 1.1 joerg if (!Result.isFixedPoint()) 13369 1.1 joerg return Error(E); 13370 1.1 joerg bool Overflowed; 13371 1.1 joerg APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed); 13372 1.1 joerg if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType())) 13373 1.1 joerg return false; 13374 1.1 joerg return Success(Negated, E); 13375 1.1 joerg } 13376 1.1 joerg case UO_LNot: { 13377 1.1 joerg bool bres; 13378 1.1 joerg if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) 13379 1.1 joerg return false; 13380 1.1 joerg return Success(!bres, E); 13381 1.1 joerg } 13382 1.1 joerg } 13383 1.1 joerg } 13384 1.1 joerg 13385 1.1 joerg bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) { 13386 1.1 joerg const Expr *SubExpr = E->getSubExpr(); 13387 1.1 joerg QualType DestType = E->getType(); 13388 1.1 joerg assert(DestType->isFixedPointType() && 13389 1.1 joerg "Expected destination type to be a fixed point type"); 13390 1.1 joerg auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType); 13391 1.1 joerg 13392 1.1 joerg switch (E->getCastKind()) { 13393 1.1 joerg case CK_FixedPointCast: { 13394 1.1 joerg APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType())); 13395 1.1 joerg if (!EvaluateFixedPoint(SubExpr, Src, Info)) 13396 1.1 joerg return false; 13397 1.1 joerg bool Overflowed; 13398 1.1 joerg APFixedPoint Result = Src.convert(DestFXSema, &Overflowed); 13399 1.1.1.2 joerg if (Overflowed) { 13400 1.1.1.2 joerg if (Info.checkingForUndefinedBehavior()) 13401 1.1.1.2 joerg Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13402 1.1.1.2 joerg diag::warn_fixedpoint_constant_overflow) 13403 1.1.1.2 joerg << Result.toString() << E->getType(); 13404 1.1.1.2 joerg if (!HandleOverflow(Info, E, Result, E->getType())) 13405 1.1.1.2 joerg return false; 13406 1.1.1.2 joerg } 13407 1.1 joerg return Success(Result, E); 13408 1.1 joerg } 13409 1.1 joerg case CK_IntegralToFixedPoint: { 13410 1.1 joerg APSInt Src; 13411 1.1 joerg if (!EvaluateInteger(SubExpr, Src, Info)) 13412 1.1 joerg return false; 13413 1.1 joerg 13414 1.1 joerg bool Overflowed; 13415 1.1 joerg APFixedPoint IntResult = APFixedPoint::getFromIntValue( 13416 1.1 joerg Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed); 13417 1.1 joerg 13418 1.1.1.2 joerg if (Overflowed) { 13419 1.1.1.2 joerg if (Info.checkingForUndefinedBehavior()) 13420 1.1.1.2 joerg Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13421 1.1.1.2 joerg diag::warn_fixedpoint_constant_overflow) 13422 1.1.1.2 joerg << IntResult.toString() << E->getType(); 13423 1.1.1.2 joerg if (!HandleOverflow(Info, E, IntResult, E->getType())) 13424 1.1.1.2 joerg return false; 13425 1.1.1.2 joerg } 13426 1.1 joerg 13427 1.1 joerg return Success(IntResult, E); 13428 1.1 joerg } 13429 1.1.1.2 joerg case CK_FloatingToFixedPoint: { 13430 1.1.1.2 joerg APFloat Src(0.0); 13431 1.1.1.2 joerg if (!EvaluateFloat(SubExpr, Src, Info)) 13432 1.1.1.2 joerg return false; 13433 1.1.1.2 joerg 13434 1.1.1.2 joerg bool Overflowed; 13435 1.1.1.2 joerg APFixedPoint Result = APFixedPoint::getFromFloatValue( 13436 1.1.1.2 joerg Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed); 13437 1.1.1.2 joerg 13438 1.1.1.2 joerg if (Overflowed) { 13439 1.1.1.2 joerg if (Info.checkingForUndefinedBehavior()) 13440 1.1.1.2 joerg Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13441 1.1.1.2 joerg diag::warn_fixedpoint_constant_overflow) 13442 1.1.1.2 joerg << Result.toString() << E->getType(); 13443 1.1.1.2 joerg if (!HandleOverflow(Info, E, Result, E->getType())) 13444 1.1.1.2 joerg return false; 13445 1.1.1.2 joerg } 13446 1.1.1.2 joerg 13447 1.1.1.2 joerg return Success(Result, E); 13448 1.1.1.2 joerg } 13449 1.1 joerg case CK_NoOp: 13450 1.1 joerg case CK_LValueToRValue: 13451 1.1 joerg return ExprEvaluatorBaseTy::VisitCastExpr(E); 13452 1.1 joerg default: 13453 1.1 joerg return Error(E); 13454 1.1 joerg } 13455 1.1 joerg } 13456 1.1 joerg 13457 1.1 joerg bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 13458 1.1.1.2 joerg if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 13459 1.1.1.2 joerg return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 13460 1.1.1.2 joerg 13461 1.1 joerg const Expr *LHS = E->getLHS(); 13462 1.1 joerg const Expr *RHS = E->getRHS(); 13463 1.1 joerg FixedPointSemantics ResultFXSema = 13464 1.1 joerg Info.Ctx.getFixedPointSemantics(E->getType()); 13465 1.1 joerg 13466 1.1 joerg APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType())); 13467 1.1 joerg if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info)) 13468 1.1 joerg return false; 13469 1.1 joerg APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType())); 13470 1.1 joerg if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info)) 13471 1.1 joerg return false; 13472 1.1 joerg 13473 1.1.1.2 joerg bool OpOverflow = false, ConversionOverflow = false; 13474 1.1.1.2 joerg APFixedPoint Result(LHSFX.getSemantics()); 13475 1.1 joerg switch (E->getOpcode()) { 13476 1.1 joerg case BO_Add: { 13477 1.1.1.2 joerg Result = LHSFX.add(RHSFX, &OpOverflow) 13478 1.1.1.2 joerg .convert(ResultFXSema, &ConversionOverflow); 13479 1.1.1.2 joerg break; 13480 1.1.1.2 joerg } 13481 1.1.1.2 joerg case BO_Sub: { 13482 1.1.1.2 joerg Result = LHSFX.sub(RHSFX, &OpOverflow) 13483 1.1.1.2 joerg .convert(ResultFXSema, &ConversionOverflow); 13484 1.1.1.2 joerg break; 13485 1.1.1.2 joerg } 13486 1.1.1.2 joerg case BO_Mul: { 13487 1.1.1.2 joerg Result = LHSFX.mul(RHSFX, &OpOverflow) 13488 1.1.1.2 joerg .convert(ResultFXSema, &ConversionOverflow); 13489 1.1.1.2 joerg break; 13490 1.1.1.2 joerg } 13491 1.1.1.2 joerg case BO_Div: { 13492 1.1.1.2 joerg if (RHSFX.getValue() == 0) { 13493 1.1.1.2 joerg Info.FFDiag(E, diag::note_expr_divide_by_zero); 13494 1.1 joerg return false; 13495 1.1.1.2 joerg } 13496 1.1.1.2 joerg Result = LHSFX.div(RHSFX, &OpOverflow) 13497 1.1.1.2 joerg .convert(ResultFXSema, &ConversionOverflow); 13498 1.1.1.2 joerg break; 13499 1.1.1.2 joerg } 13500 1.1.1.2 joerg case BO_Shl: 13501 1.1.1.2 joerg case BO_Shr: { 13502 1.1.1.2 joerg FixedPointSemantics LHSSema = LHSFX.getSemantics(); 13503 1.1.1.2 joerg llvm::APSInt RHSVal = RHSFX.getValue(); 13504 1.1.1.2 joerg 13505 1.1.1.2 joerg unsigned ShiftBW = 13506 1.1.1.2 joerg LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding(); 13507 1.1.1.2 joerg unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1); 13508 1.1.1.2 joerg // Embedded-C 4.1.6.2.2: 13509 1.1.1.2 joerg // The right operand must be nonnegative and less than the total number 13510 1.1.1.2 joerg // of (nonpadding) bits of the fixed-point operand ... 13511 1.1.1.2 joerg if (RHSVal.isNegative()) 13512 1.1.1.2 joerg Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal; 13513 1.1.1.2 joerg else if (Amt != RHSVal) 13514 1.1.1.2 joerg Info.CCEDiag(E, diag::note_constexpr_large_shift) 13515 1.1.1.2 joerg << RHSVal << E->getType() << ShiftBW; 13516 1.1.1.2 joerg 13517 1.1.1.2 joerg if (E->getOpcode() == BO_Shl) 13518 1.1.1.2 joerg Result = LHSFX.shl(Amt, &OpOverflow); 13519 1.1.1.2 joerg else 13520 1.1.1.2 joerg Result = LHSFX.shr(Amt, &OpOverflow); 13521 1.1.1.2 joerg break; 13522 1.1 joerg } 13523 1.1 joerg default: 13524 1.1 joerg return false; 13525 1.1 joerg } 13526 1.1.1.2 joerg if (OpOverflow || ConversionOverflow) { 13527 1.1.1.2 joerg if (Info.checkingForUndefinedBehavior()) 13528 1.1.1.2 joerg Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 13529 1.1.1.2 joerg diag::warn_fixedpoint_constant_overflow) 13530 1.1.1.2 joerg << Result.toString() << E->getType(); 13531 1.1.1.2 joerg if (!HandleOverflow(Info, E, Result, E->getType())) 13532 1.1.1.2 joerg return false; 13533 1.1.1.2 joerg } 13534 1.1.1.2 joerg return Success(Result, E); 13535 1.1 joerg } 13536 1.1 joerg 13537 1.1 joerg //===----------------------------------------------------------------------===// 13538 1.1 joerg // Float Evaluation 13539 1.1 joerg //===----------------------------------------------------------------------===// 13540 1.1 joerg 13541 1.1 joerg namespace { 13542 1.1 joerg class FloatExprEvaluator 13543 1.1 joerg : public ExprEvaluatorBase<FloatExprEvaluator> { 13544 1.1 joerg APFloat &Result; 13545 1.1 joerg public: 13546 1.1 joerg FloatExprEvaluator(EvalInfo &info, APFloat &result) 13547 1.1 joerg : ExprEvaluatorBaseTy(info), Result(result) {} 13548 1.1 joerg 13549 1.1 joerg bool Success(const APValue &V, const Expr *e) { 13550 1.1 joerg Result = V.getFloat(); 13551 1.1 joerg return true; 13552 1.1 joerg } 13553 1.1 joerg 13554 1.1 joerg bool ZeroInitialization(const Expr *E) { 13555 1.1 joerg Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType())); 13556 1.1 joerg return true; 13557 1.1 joerg } 13558 1.1 joerg 13559 1.1 joerg bool VisitCallExpr(const CallExpr *E); 13560 1.1 joerg 13561 1.1 joerg bool VisitUnaryOperator(const UnaryOperator *E); 13562 1.1 joerg bool VisitBinaryOperator(const BinaryOperator *E); 13563 1.1 joerg bool VisitFloatingLiteral(const FloatingLiteral *E); 13564 1.1 joerg bool VisitCastExpr(const CastExpr *E); 13565 1.1 joerg 13566 1.1 joerg bool VisitUnaryReal(const UnaryOperator *E); 13567 1.1 joerg bool VisitUnaryImag(const UnaryOperator *E); 13568 1.1 joerg 13569 1.1 joerg // FIXME: Missing: array subscript of vector, member of vector 13570 1.1 joerg }; 13571 1.1 joerg } // end anonymous namespace 13572 1.1 joerg 13573 1.1 joerg static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) { 13574 1.1.1.2 joerg assert(!E->isValueDependent()); 13575 1.1 joerg assert(E->isRValue() && E->getType()->isRealFloatingType()); 13576 1.1 joerg return FloatExprEvaluator(Info, Result).Visit(E); 13577 1.1 joerg } 13578 1.1 joerg 13579 1.1 joerg static bool TryEvaluateBuiltinNaN(const ASTContext &Context, 13580 1.1 joerg QualType ResultTy, 13581 1.1 joerg const Expr *Arg, 13582 1.1 joerg bool SNaN, 13583 1.1 joerg llvm::APFloat &Result) { 13584 1.1 joerg const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 13585 1.1 joerg if (!S) return false; 13586 1.1 joerg 13587 1.1 joerg const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy); 13588 1.1 joerg 13589 1.1 joerg llvm::APInt fill; 13590 1.1 joerg 13591 1.1 joerg // Treat empty strings as if they were zero. 13592 1.1 joerg if (S->getString().empty()) 13593 1.1 joerg fill = llvm::APInt(32, 0); 13594 1.1 joerg else if (S->getString().getAsInteger(0, fill)) 13595 1.1 joerg return false; 13596 1.1 joerg 13597 1.1 joerg if (Context.getTargetInfo().isNan2008()) { 13598 1.1 joerg if (SNaN) 13599 1.1 joerg Result = llvm::APFloat::getSNaN(Sem, false, &fill); 13600 1.1 joerg else 13601 1.1 joerg Result = llvm::APFloat::getQNaN(Sem, false, &fill); 13602 1.1 joerg } else { 13603 1.1 joerg // Prior to IEEE 754-2008, architectures were allowed to choose whether 13604 1.1 joerg // the first bit of their significand was set for qNaN or sNaN. MIPS chose 13605 1.1 joerg // a different encoding to what became a standard in 2008, and for pre- 13606 1.1 joerg // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as 13607 1.1 joerg // sNaN. This is now known as "legacy NaN" encoding. 13608 1.1 joerg if (SNaN) 13609 1.1 joerg Result = llvm::APFloat::getQNaN(Sem, false, &fill); 13610 1.1 joerg else 13611 1.1 joerg Result = llvm::APFloat::getSNaN(Sem, false, &fill); 13612 1.1 joerg } 13613 1.1 joerg 13614 1.1 joerg return true; 13615 1.1 joerg } 13616 1.1 joerg 13617 1.1 joerg bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) { 13618 1.1 joerg switch (E->getBuiltinCallee()) { 13619 1.1 joerg default: 13620 1.1 joerg return ExprEvaluatorBaseTy::VisitCallExpr(E); 13621 1.1 joerg 13622 1.1 joerg case Builtin::BI__builtin_huge_val: 13623 1.1 joerg case Builtin::BI__builtin_huge_valf: 13624 1.1 joerg case Builtin::BI__builtin_huge_vall: 13625 1.1 joerg case Builtin::BI__builtin_huge_valf128: 13626 1.1 joerg case Builtin::BI__builtin_inf: 13627 1.1 joerg case Builtin::BI__builtin_inff: 13628 1.1 joerg case Builtin::BI__builtin_infl: 13629 1.1 joerg case Builtin::BI__builtin_inff128: { 13630 1.1 joerg const llvm::fltSemantics &Sem = 13631 1.1 joerg Info.Ctx.getFloatTypeSemantics(E->getType()); 13632 1.1 joerg Result = llvm::APFloat::getInf(Sem); 13633 1.1 joerg return true; 13634 1.1 joerg } 13635 1.1 joerg 13636 1.1 joerg case Builtin::BI__builtin_nans: 13637 1.1 joerg case Builtin::BI__builtin_nansf: 13638 1.1 joerg case Builtin::BI__builtin_nansl: 13639 1.1 joerg case Builtin::BI__builtin_nansf128: 13640 1.1 joerg if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 13641 1.1 joerg true, Result)) 13642 1.1 joerg return Error(E); 13643 1.1 joerg return true; 13644 1.1 joerg 13645 1.1 joerg case Builtin::BI__builtin_nan: 13646 1.1 joerg case Builtin::BI__builtin_nanf: 13647 1.1 joerg case Builtin::BI__builtin_nanl: 13648 1.1 joerg case Builtin::BI__builtin_nanf128: 13649 1.1 joerg // If this is __builtin_nan() turn this into a nan, otherwise we 13650 1.1 joerg // can't constant fold it. 13651 1.1 joerg if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 13652 1.1 joerg false, Result)) 13653 1.1 joerg return Error(E); 13654 1.1 joerg return true; 13655 1.1 joerg 13656 1.1 joerg case Builtin::BI__builtin_fabs: 13657 1.1 joerg case Builtin::BI__builtin_fabsf: 13658 1.1 joerg case Builtin::BI__builtin_fabsl: 13659 1.1 joerg case Builtin::BI__builtin_fabsf128: 13660 1.1.1.2 joerg // The C standard says "fabs raises no floating-point exceptions, 13661 1.1.1.2 joerg // even if x is a signaling NaN. The returned value is independent of 13662 1.1.1.2 joerg // the current rounding direction mode." Therefore constant folding can 13663 1.1.1.2 joerg // proceed without regard to the floating point settings. 13664 1.1.1.2 joerg // Reference, WG14 N2478 F.10.4.3 13665 1.1 joerg if (!EvaluateFloat(E->getArg(0), Result, Info)) 13666 1.1 joerg return false; 13667 1.1 joerg 13668 1.1 joerg if (Result.isNegative()) 13669 1.1 joerg Result.changeSign(); 13670 1.1 joerg return true; 13671 1.1 joerg 13672 1.1 joerg // FIXME: Builtin::BI__builtin_powi 13673 1.1 joerg // FIXME: Builtin::BI__builtin_powif 13674 1.1 joerg // FIXME: Builtin::BI__builtin_powil 13675 1.1 joerg 13676 1.1 joerg case Builtin::BI__builtin_copysign: 13677 1.1 joerg case Builtin::BI__builtin_copysignf: 13678 1.1 joerg case Builtin::BI__builtin_copysignl: 13679 1.1 joerg case Builtin::BI__builtin_copysignf128: { 13680 1.1 joerg APFloat RHS(0.); 13681 1.1 joerg if (!EvaluateFloat(E->getArg(0), Result, Info) || 13682 1.1 joerg !EvaluateFloat(E->getArg(1), RHS, Info)) 13683 1.1 joerg return false; 13684 1.1 joerg Result.copySign(RHS); 13685 1.1 joerg return true; 13686 1.1 joerg } 13687 1.1 joerg } 13688 1.1 joerg } 13689 1.1 joerg 13690 1.1 joerg bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 13691 1.1 joerg if (E->getSubExpr()->getType()->isAnyComplexType()) { 13692 1.1 joerg ComplexValue CV; 13693 1.1 joerg if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 13694 1.1 joerg return false; 13695 1.1 joerg Result = CV.FloatReal; 13696 1.1 joerg return true; 13697 1.1 joerg } 13698 1.1 joerg 13699 1.1 joerg return Visit(E->getSubExpr()); 13700 1.1 joerg } 13701 1.1 joerg 13702 1.1 joerg bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 13703 1.1 joerg if (E->getSubExpr()->getType()->isAnyComplexType()) { 13704 1.1 joerg ComplexValue CV; 13705 1.1 joerg if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 13706 1.1 joerg return false; 13707 1.1 joerg Result = CV.FloatImag; 13708 1.1 joerg return true; 13709 1.1 joerg } 13710 1.1 joerg 13711 1.1 joerg VisitIgnoredValue(E->getSubExpr()); 13712 1.1 joerg const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType()); 13713 1.1 joerg Result = llvm::APFloat::getZero(Sem); 13714 1.1 joerg return true; 13715 1.1 joerg } 13716 1.1 joerg 13717 1.1 joerg bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 13718 1.1 joerg switch (E->getOpcode()) { 13719 1.1 joerg default: return Error(E); 13720 1.1 joerg case UO_Plus: 13721 1.1 joerg return EvaluateFloat(E->getSubExpr(), Result, Info); 13722 1.1 joerg case UO_Minus: 13723 1.1.1.2 joerg // In C standard, WG14 N2478 F.3 p4 13724 1.1.1.2 joerg // "the unary - raises no floating point exceptions, 13725 1.1.1.2 joerg // even if the operand is signalling." 13726 1.1 joerg if (!EvaluateFloat(E->getSubExpr(), Result, Info)) 13727 1.1 joerg return false; 13728 1.1 joerg Result.changeSign(); 13729 1.1 joerg return true; 13730 1.1 joerg } 13731 1.1 joerg } 13732 1.1 joerg 13733 1.1 joerg bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 13734 1.1 joerg if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 13735 1.1 joerg return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 13736 1.1 joerg 13737 1.1 joerg APFloat RHS(0.0); 13738 1.1 joerg bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info); 13739 1.1 joerg if (!LHSOK && !Info.noteFailure()) 13740 1.1 joerg return false; 13741 1.1 joerg return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK && 13742 1.1 joerg handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS); 13743 1.1 joerg } 13744 1.1 joerg 13745 1.1 joerg bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) { 13746 1.1 joerg Result = E->getValue(); 13747 1.1 joerg return true; 13748 1.1 joerg } 13749 1.1 joerg 13750 1.1 joerg bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) { 13751 1.1 joerg const Expr* SubExpr = E->getSubExpr(); 13752 1.1 joerg 13753 1.1 joerg switch (E->getCastKind()) { 13754 1.1 joerg default: 13755 1.1 joerg return ExprEvaluatorBaseTy::VisitCastExpr(E); 13756 1.1 joerg 13757 1.1 joerg case CK_IntegralToFloating: { 13758 1.1 joerg APSInt IntResult; 13759 1.1.1.2 joerg const FPOptions FPO = E->getFPFeaturesInEffect( 13760 1.1.1.2 joerg Info.Ctx.getLangOpts()); 13761 1.1 joerg return EvaluateInteger(SubExpr, IntResult, Info) && 13762 1.1.1.2 joerg HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(), 13763 1.1.1.2 joerg IntResult, E->getType(), Result); 13764 1.1.1.2 joerg } 13765 1.1.1.2 joerg 13766 1.1.1.2 joerg case CK_FixedPointToFloating: { 13767 1.1.1.2 joerg APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType())); 13768 1.1.1.2 joerg if (!EvaluateFixedPoint(SubExpr, FixResult, Info)) 13769 1.1.1.2 joerg return false; 13770 1.1.1.2 joerg Result = 13771 1.1.1.2 joerg FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType())); 13772 1.1.1.2 joerg return true; 13773 1.1 joerg } 13774 1.1 joerg 13775 1.1 joerg case CK_FloatingCast: { 13776 1.1 joerg if (!Visit(SubExpr)) 13777 1.1 joerg return false; 13778 1.1 joerg return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(), 13779 1.1 joerg Result); 13780 1.1 joerg } 13781 1.1 joerg 13782 1.1 joerg case CK_FloatingComplexToReal: { 13783 1.1 joerg ComplexValue V; 13784 1.1 joerg if (!EvaluateComplex(SubExpr, V, Info)) 13785 1.1 joerg return false; 13786 1.1 joerg Result = V.getComplexFloatReal(); 13787 1.1 joerg return true; 13788 1.1 joerg } 13789 1.1 joerg } 13790 1.1 joerg } 13791 1.1 joerg 13792 1.1 joerg //===----------------------------------------------------------------------===// 13793 1.1 joerg // Complex Evaluation (for float and integer) 13794 1.1 joerg //===----------------------------------------------------------------------===// 13795 1.1 joerg 13796 1.1 joerg namespace { 13797 1.1 joerg class ComplexExprEvaluator 13798 1.1 joerg : public ExprEvaluatorBase<ComplexExprEvaluator> { 13799 1.1 joerg ComplexValue &Result; 13800 1.1 joerg 13801 1.1 joerg public: 13802 1.1 joerg ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result) 13803 1.1 joerg : ExprEvaluatorBaseTy(info), Result(Result) {} 13804 1.1 joerg 13805 1.1 joerg bool Success(const APValue &V, const Expr *e) { 13806 1.1 joerg Result.setFrom(V); 13807 1.1 joerg return true; 13808 1.1 joerg } 13809 1.1 joerg 13810 1.1 joerg bool ZeroInitialization(const Expr *E); 13811 1.1 joerg 13812 1.1 joerg //===--------------------------------------------------------------------===// 13813 1.1 joerg // Visitor Methods 13814 1.1 joerg //===--------------------------------------------------------------------===// 13815 1.1 joerg 13816 1.1 joerg bool VisitImaginaryLiteral(const ImaginaryLiteral *E); 13817 1.1 joerg bool VisitCastExpr(const CastExpr *E); 13818 1.1 joerg bool VisitBinaryOperator(const BinaryOperator *E); 13819 1.1 joerg bool VisitUnaryOperator(const UnaryOperator *E); 13820 1.1 joerg bool VisitInitListExpr(const InitListExpr *E); 13821 1.1.1.2 joerg bool VisitCallExpr(const CallExpr *E); 13822 1.1 joerg }; 13823 1.1 joerg } // end anonymous namespace 13824 1.1 joerg 13825 1.1 joerg static bool EvaluateComplex(const Expr *E, ComplexValue &Result, 13826 1.1 joerg EvalInfo &Info) { 13827 1.1.1.2 joerg assert(!E->isValueDependent()); 13828 1.1 joerg assert(E->isRValue() && E->getType()->isAnyComplexType()); 13829 1.1 joerg return ComplexExprEvaluator(Info, Result).Visit(E); 13830 1.1 joerg } 13831 1.1 joerg 13832 1.1 joerg bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) { 13833 1.1 joerg QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType(); 13834 1.1 joerg if (ElemTy->isRealFloatingType()) { 13835 1.1 joerg Result.makeComplexFloat(); 13836 1.1 joerg APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy)); 13837 1.1 joerg Result.FloatReal = Zero; 13838 1.1 joerg Result.FloatImag = Zero; 13839 1.1 joerg } else { 13840 1.1 joerg Result.makeComplexInt(); 13841 1.1 joerg APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy); 13842 1.1 joerg Result.IntReal = Zero; 13843 1.1 joerg Result.IntImag = Zero; 13844 1.1 joerg } 13845 1.1 joerg return true; 13846 1.1 joerg } 13847 1.1 joerg 13848 1.1 joerg bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) { 13849 1.1 joerg const Expr* SubExpr = E->getSubExpr(); 13850 1.1 joerg 13851 1.1 joerg if (SubExpr->getType()->isRealFloatingType()) { 13852 1.1 joerg Result.makeComplexFloat(); 13853 1.1 joerg APFloat &Imag = Result.FloatImag; 13854 1.1 joerg if (!EvaluateFloat(SubExpr, Imag, Info)) 13855 1.1 joerg return false; 13856 1.1 joerg 13857 1.1 joerg Result.FloatReal = APFloat(Imag.getSemantics()); 13858 1.1 joerg return true; 13859 1.1 joerg } else { 13860 1.1 joerg assert(SubExpr->getType()->isIntegerType() && 13861 1.1 joerg "Unexpected imaginary literal."); 13862 1.1 joerg 13863 1.1 joerg Result.makeComplexInt(); 13864 1.1 joerg APSInt &Imag = Result.IntImag; 13865 1.1 joerg if (!EvaluateInteger(SubExpr, Imag, Info)) 13866 1.1 joerg return false; 13867 1.1 joerg 13868 1.1 joerg Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned()); 13869 1.1 joerg return true; 13870 1.1 joerg } 13871 1.1 joerg } 13872 1.1 joerg 13873 1.1 joerg bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) { 13874 1.1 joerg 13875 1.1 joerg switch (E->getCastKind()) { 13876 1.1 joerg case CK_BitCast: 13877 1.1 joerg case CK_BaseToDerived: 13878 1.1 joerg case CK_DerivedToBase: 13879 1.1 joerg case CK_UncheckedDerivedToBase: 13880 1.1 joerg case CK_Dynamic: 13881 1.1 joerg case CK_ToUnion: 13882 1.1 joerg case CK_ArrayToPointerDecay: 13883 1.1 joerg case CK_FunctionToPointerDecay: 13884 1.1 joerg case CK_NullToPointer: 13885 1.1 joerg case CK_NullToMemberPointer: 13886 1.1 joerg case CK_BaseToDerivedMemberPointer: 13887 1.1 joerg case CK_DerivedToBaseMemberPointer: 13888 1.1 joerg case CK_MemberPointerToBoolean: 13889 1.1 joerg case CK_ReinterpretMemberPointer: 13890 1.1 joerg case CK_ConstructorConversion: 13891 1.1 joerg case CK_IntegralToPointer: 13892 1.1 joerg case CK_PointerToIntegral: 13893 1.1 joerg case CK_PointerToBoolean: 13894 1.1 joerg case CK_ToVoid: 13895 1.1 joerg case CK_VectorSplat: 13896 1.1 joerg case CK_IntegralCast: 13897 1.1 joerg case CK_BooleanToSignedIntegral: 13898 1.1 joerg case CK_IntegralToBoolean: 13899 1.1 joerg case CK_IntegralToFloating: 13900 1.1 joerg case CK_FloatingToIntegral: 13901 1.1 joerg case CK_FloatingToBoolean: 13902 1.1 joerg case CK_FloatingCast: 13903 1.1 joerg case CK_CPointerToObjCPointerCast: 13904 1.1 joerg case CK_BlockPointerToObjCPointerCast: 13905 1.1 joerg case CK_AnyPointerToBlockPointerCast: 13906 1.1 joerg case CK_ObjCObjectLValueCast: 13907 1.1 joerg case CK_FloatingComplexToReal: 13908 1.1 joerg case CK_FloatingComplexToBoolean: 13909 1.1 joerg case CK_IntegralComplexToReal: 13910 1.1 joerg case CK_IntegralComplexToBoolean: 13911 1.1 joerg case CK_ARCProduceObject: 13912 1.1 joerg case CK_ARCConsumeObject: 13913 1.1 joerg case CK_ARCReclaimReturnedObject: 13914 1.1 joerg case CK_ARCExtendBlockObject: 13915 1.1 joerg case CK_CopyAndAutoreleaseBlockObject: 13916 1.1 joerg case CK_BuiltinFnToFnPtr: 13917 1.1 joerg case CK_ZeroToOCLOpaqueType: 13918 1.1 joerg case CK_NonAtomicToAtomic: 13919 1.1 joerg case CK_AddressSpaceConversion: 13920 1.1 joerg case CK_IntToOCLSampler: 13921 1.1.1.2 joerg case CK_FloatingToFixedPoint: 13922 1.1.1.2 joerg case CK_FixedPointToFloating: 13923 1.1 joerg case CK_FixedPointCast: 13924 1.1 joerg case CK_FixedPointToBoolean: 13925 1.1 joerg case CK_FixedPointToIntegral: 13926 1.1 joerg case CK_IntegralToFixedPoint: 13927 1.1.1.2 joerg case CK_MatrixCast: 13928 1.1 joerg llvm_unreachable("invalid cast kind for complex value"); 13929 1.1 joerg 13930 1.1 joerg case CK_LValueToRValue: 13931 1.1 joerg case CK_AtomicToNonAtomic: 13932 1.1 joerg case CK_NoOp: 13933 1.1 joerg case CK_LValueToRValueBitCast: 13934 1.1 joerg return ExprEvaluatorBaseTy::VisitCastExpr(E); 13935 1.1 joerg 13936 1.1 joerg case CK_Dependent: 13937 1.1 joerg case CK_LValueBitCast: 13938 1.1 joerg case CK_UserDefinedConversion: 13939 1.1 joerg return Error(E); 13940 1.1 joerg 13941 1.1 joerg case CK_FloatingRealToComplex: { 13942 1.1 joerg APFloat &Real = Result.FloatReal; 13943 1.1 joerg if (!EvaluateFloat(E->getSubExpr(), Real, Info)) 13944 1.1 joerg return false; 13945 1.1 joerg 13946 1.1 joerg Result.makeComplexFloat(); 13947 1.1 joerg Result.FloatImag = APFloat(Real.getSemantics()); 13948 1.1 joerg return true; 13949 1.1 joerg } 13950 1.1 joerg 13951 1.1 joerg case CK_FloatingComplexCast: { 13952 1.1 joerg if (!Visit(E->getSubExpr())) 13953 1.1 joerg return false; 13954 1.1 joerg 13955 1.1 joerg QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 13956 1.1 joerg QualType From 13957 1.1 joerg = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 13958 1.1 joerg 13959 1.1 joerg return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) && 13960 1.1 joerg HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag); 13961 1.1 joerg } 13962 1.1 joerg 13963 1.1 joerg case CK_FloatingComplexToIntegralComplex: { 13964 1.1 joerg if (!Visit(E->getSubExpr())) 13965 1.1 joerg return false; 13966 1.1 joerg 13967 1.1 joerg QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 13968 1.1 joerg QualType From 13969 1.1 joerg = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 13970 1.1 joerg Result.makeComplexInt(); 13971 1.1 joerg return HandleFloatToIntCast(Info, E, From, Result.FloatReal, 13972 1.1 joerg To, Result.IntReal) && 13973 1.1 joerg HandleFloatToIntCast(Info, E, From, Result.FloatImag, 13974 1.1 joerg To, Result.IntImag); 13975 1.1 joerg } 13976 1.1 joerg 13977 1.1 joerg case CK_IntegralRealToComplex: { 13978 1.1 joerg APSInt &Real = Result.IntReal; 13979 1.1 joerg if (!EvaluateInteger(E->getSubExpr(), Real, Info)) 13980 1.1 joerg return false; 13981 1.1 joerg 13982 1.1 joerg Result.makeComplexInt(); 13983 1.1 joerg Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned()); 13984 1.1 joerg return true; 13985 1.1 joerg } 13986 1.1 joerg 13987 1.1 joerg case CK_IntegralComplexCast: { 13988 1.1 joerg if (!Visit(E->getSubExpr())) 13989 1.1 joerg return false; 13990 1.1 joerg 13991 1.1 joerg QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 13992 1.1 joerg QualType From 13993 1.1 joerg = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 13994 1.1 joerg 13995 1.1 joerg Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal); 13996 1.1 joerg Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag); 13997 1.1 joerg return true; 13998 1.1 joerg } 13999 1.1 joerg 14000 1.1 joerg case CK_IntegralComplexToFloatingComplex: { 14001 1.1 joerg if (!Visit(E->getSubExpr())) 14002 1.1 joerg return false; 14003 1.1 joerg 14004 1.1.1.2 joerg const FPOptions FPO = E->getFPFeaturesInEffect( 14005 1.1.1.2 joerg Info.Ctx.getLangOpts()); 14006 1.1 joerg QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 14007 1.1 joerg QualType From 14008 1.1 joerg = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 14009 1.1 joerg Result.makeComplexFloat(); 14010 1.1.1.2 joerg return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal, 14011 1.1 joerg To, Result.FloatReal) && 14012 1.1.1.2 joerg HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag, 14013 1.1 joerg To, Result.FloatImag); 14014 1.1 joerg } 14015 1.1 joerg } 14016 1.1 joerg 14017 1.1 joerg llvm_unreachable("unknown cast resulting in complex value"); 14018 1.1 joerg } 14019 1.1 joerg 14020 1.1 joerg bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 14021 1.1 joerg if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 14022 1.1 joerg return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 14023 1.1 joerg 14024 1.1 joerg // Track whether the LHS or RHS is real at the type system level. When this is 14025 1.1 joerg // the case we can simplify our evaluation strategy. 14026 1.1 joerg bool LHSReal = false, RHSReal = false; 14027 1.1 joerg 14028 1.1 joerg bool LHSOK; 14029 1.1 joerg if (E->getLHS()->getType()->isRealFloatingType()) { 14030 1.1 joerg LHSReal = true; 14031 1.1 joerg APFloat &Real = Result.FloatReal; 14032 1.1 joerg LHSOK = EvaluateFloat(E->getLHS(), Real, Info); 14033 1.1 joerg if (LHSOK) { 14034 1.1 joerg Result.makeComplexFloat(); 14035 1.1 joerg Result.FloatImag = APFloat(Real.getSemantics()); 14036 1.1 joerg } 14037 1.1 joerg } else { 14038 1.1 joerg LHSOK = Visit(E->getLHS()); 14039 1.1 joerg } 14040 1.1 joerg if (!LHSOK && !Info.noteFailure()) 14041 1.1 joerg return false; 14042 1.1 joerg 14043 1.1 joerg ComplexValue RHS; 14044 1.1 joerg if (E->getRHS()->getType()->isRealFloatingType()) { 14045 1.1 joerg RHSReal = true; 14046 1.1 joerg APFloat &Real = RHS.FloatReal; 14047 1.1 joerg if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK) 14048 1.1 joerg return false; 14049 1.1 joerg RHS.makeComplexFloat(); 14050 1.1 joerg RHS.FloatImag = APFloat(Real.getSemantics()); 14051 1.1 joerg } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 14052 1.1 joerg return false; 14053 1.1 joerg 14054 1.1 joerg assert(!(LHSReal && RHSReal) && 14055 1.1 joerg "Cannot have both operands of a complex operation be real."); 14056 1.1 joerg switch (E->getOpcode()) { 14057 1.1 joerg default: return Error(E); 14058 1.1 joerg case BO_Add: 14059 1.1 joerg if (Result.isComplexFloat()) { 14060 1.1 joerg Result.getComplexFloatReal().add(RHS.getComplexFloatReal(), 14061 1.1 joerg APFloat::rmNearestTiesToEven); 14062 1.1 joerg if (LHSReal) 14063 1.1 joerg Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 14064 1.1 joerg else if (!RHSReal) 14065 1.1 joerg Result.getComplexFloatImag().add(RHS.getComplexFloatImag(), 14066 1.1 joerg APFloat::rmNearestTiesToEven); 14067 1.1 joerg } else { 14068 1.1 joerg Result.getComplexIntReal() += RHS.getComplexIntReal(); 14069 1.1 joerg Result.getComplexIntImag() += RHS.getComplexIntImag(); 14070 1.1 joerg } 14071 1.1 joerg break; 14072 1.1 joerg case BO_Sub: 14073 1.1 joerg if (Result.isComplexFloat()) { 14074 1.1 joerg Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(), 14075 1.1 joerg APFloat::rmNearestTiesToEven); 14076 1.1 joerg if (LHSReal) { 14077 1.1 joerg Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 14078 1.1 joerg Result.getComplexFloatImag().changeSign(); 14079 1.1 joerg } else if (!RHSReal) { 14080 1.1 joerg Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(), 14081 1.1 joerg APFloat::rmNearestTiesToEven); 14082 1.1 joerg } 14083 1.1 joerg } else { 14084 1.1 joerg Result.getComplexIntReal() -= RHS.getComplexIntReal(); 14085 1.1 joerg Result.getComplexIntImag() -= RHS.getComplexIntImag(); 14086 1.1 joerg } 14087 1.1 joerg break; 14088 1.1 joerg case BO_Mul: 14089 1.1 joerg if (Result.isComplexFloat()) { 14090 1.1 joerg // This is an implementation of complex multiplication according to the 14091 1.1 joerg // constraints laid out in C11 Annex G. The implementation uses the 14092 1.1 joerg // following naming scheme: 14093 1.1 joerg // (a + ib) * (c + id) 14094 1.1 joerg ComplexValue LHS = Result; 14095 1.1 joerg APFloat &A = LHS.getComplexFloatReal(); 14096 1.1 joerg APFloat &B = LHS.getComplexFloatImag(); 14097 1.1 joerg APFloat &C = RHS.getComplexFloatReal(); 14098 1.1 joerg APFloat &D = RHS.getComplexFloatImag(); 14099 1.1 joerg APFloat &ResR = Result.getComplexFloatReal(); 14100 1.1 joerg APFloat &ResI = Result.getComplexFloatImag(); 14101 1.1 joerg if (LHSReal) { 14102 1.1 joerg assert(!RHSReal && "Cannot have two real operands for a complex op!"); 14103 1.1 joerg ResR = A * C; 14104 1.1 joerg ResI = A * D; 14105 1.1 joerg } else if (RHSReal) { 14106 1.1 joerg ResR = C * A; 14107 1.1 joerg ResI = C * B; 14108 1.1 joerg } else { 14109 1.1 joerg // In the fully general case, we need to handle NaNs and infinities 14110 1.1 joerg // robustly. 14111 1.1 joerg APFloat AC = A * C; 14112 1.1 joerg APFloat BD = B * D; 14113 1.1 joerg APFloat AD = A * D; 14114 1.1 joerg APFloat BC = B * C; 14115 1.1 joerg ResR = AC - BD; 14116 1.1 joerg ResI = AD + BC; 14117 1.1 joerg if (ResR.isNaN() && ResI.isNaN()) { 14118 1.1 joerg bool Recalc = false; 14119 1.1 joerg if (A.isInfinity() || B.isInfinity()) { 14120 1.1 joerg A = APFloat::copySign( 14121 1.1 joerg APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 14122 1.1 joerg B = APFloat::copySign( 14123 1.1 joerg APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 14124 1.1 joerg if (C.isNaN()) 14125 1.1 joerg C = APFloat::copySign(APFloat(C.getSemantics()), C); 14126 1.1 joerg if (D.isNaN()) 14127 1.1 joerg D = APFloat::copySign(APFloat(D.getSemantics()), D); 14128 1.1 joerg Recalc = true; 14129 1.1 joerg } 14130 1.1 joerg if (C.isInfinity() || D.isInfinity()) { 14131 1.1 joerg C = APFloat::copySign( 14132 1.1 joerg APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 14133 1.1 joerg D = APFloat::copySign( 14134 1.1 joerg APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 14135 1.1 joerg if (A.isNaN()) 14136 1.1 joerg A = APFloat::copySign(APFloat(A.getSemantics()), A); 14137 1.1 joerg if (B.isNaN()) 14138 1.1 joerg B = APFloat::copySign(APFloat(B.getSemantics()), B); 14139 1.1 joerg Recalc = true; 14140 1.1 joerg } 14141 1.1 joerg if (!Recalc && (AC.isInfinity() || BD.isInfinity() || 14142 1.1 joerg AD.isInfinity() || BC.isInfinity())) { 14143 1.1 joerg if (A.isNaN()) 14144 1.1 joerg A = APFloat::copySign(APFloat(A.getSemantics()), A); 14145 1.1 joerg if (B.isNaN()) 14146 1.1 joerg B = APFloat::copySign(APFloat(B.getSemantics()), B); 14147 1.1 joerg if (C.isNaN()) 14148 1.1 joerg C = APFloat::copySign(APFloat(C.getSemantics()), C); 14149 1.1 joerg if (D.isNaN()) 14150 1.1 joerg D = APFloat::copySign(APFloat(D.getSemantics()), D); 14151 1.1 joerg Recalc = true; 14152 1.1 joerg } 14153 1.1 joerg if (Recalc) { 14154 1.1 joerg ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D); 14155 1.1 joerg ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C); 14156 1.1 joerg } 14157 1.1 joerg } 14158 1.1 joerg } 14159 1.1 joerg } else { 14160 1.1 joerg ComplexValue LHS = Result; 14161 1.1 joerg Result.getComplexIntReal() = 14162 1.1 joerg (LHS.getComplexIntReal() * RHS.getComplexIntReal() - 14163 1.1 joerg LHS.getComplexIntImag() * RHS.getComplexIntImag()); 14164 1.1 joerg Result.getComplexIntImag() = 14165 1.1 joerg (LHS.getComplexIntReal() * RHS.getComplexIntImag() + 14166 1.1 joerg LHS.getComplexIntImag() * RHS.getComplexIntReal()); 14167 1.1 joerg } 14168 1.1 joerg break; 14169 1.1 joerg case BO_Div: 14170 1.1 joerg if (Result.isComplexFloat()) { 14171 1.1 joerg // This is an implementation of complex division according to the 14172 1.1 joerg // constraints laid out in C11 Annex G. The implementation uses the 14173 1.1 joerg // following naming scheme: 14174 1.1 joerg // (a + ib) / (c + id) 14175 1.1 joerg ComplexValue LHS = Result; 14176 1.1 joerg APFloat &A = LHS.getComplexFloatReal(); 14177 1.1 joerg APFloat &B = LHS.getComplexFloatImag(); 14178 1.1 joerg APFloat &C = RHS.getComplexFloatReal(); 14179 1.1 joerg APFloat &D = RHS.getComplexFloatImag(); 14180 1.1 joerg APFloat &ResR = Result.getComplexFloatReal(); 14181 1.1 joerg APFloat &ResI = Result.getComplexFloatImag(); 14182 1.1 joerg if (RHSReal) { 14183 1.1 joerg ResR = A / C; 14184 1.1 joerg ResI = B / C; 14185 1.1 joerg } else { 14186 1.1 joerg if (LHSReal) { 14187 1.1 joerg // No real optimizations we can do here, stub out with zero. 14188 1.1 joerg B = APFloat::getZero(A.getSemantics()); 14189 1.1 joerg } 14190 1.1 joerg int DenomLogB = 0; 14191 1.1 joerg APFloat MaxCD = maxnum(abs(C), abs(D)); 14192 1.1 joerg if (MaxCD.isFinite()) { 14193 1.1 joerg DenomLogB = ilogb(MaxCD); 14194 1.1 joerg C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven); 14195 1.1 joerg D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven); 14196 1.1 joerg } 14197 1.1 joerg APFloat Denom = C * C + D * D; 14198 1.1 joerg ResR = scalbn((A * C + B * D) / Denom, -DenomLogB, 14199 1.1 joerg APFloat::rmNearestTiesToEven); 14200 1.1 joerg ResI = scalbn((B * C - A * D) / Denom, -DenomLogB, 14201 1.1 joerg APFloat::rmNearestTiesToEven); 14202 1.1 joerg if (ResR.isNaN() && ResI.isNaN()) { 14203 1.1 joerg if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) { 14204 1.1 joerg ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A; 14205 1.1 joerg ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B; 14206 1.1 joerg } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() && 14207 1.1 joerg D.isFinite()) { 14208 1.1 joerg A = APFloat::copySign( 14209 1.1 joerg APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 14210 1.1 joerg B = APFloat::copySign( 14211 1.1 joerg APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 14212 1.1 joerg ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D); 14213 1.1 joerg ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D); 14214 1.1 joerg } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) { 14215 1.1 joerg C = APFloat::copySign( 14216 1.1 joerg APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 14217 1.1 joerg D = APFloat::copySign( 14218 1.1 joerg APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 14219 1.1 joerg ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D); 14220 1.1 joerg ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D); 14221 1.1 joerg } 14222 1.1 joerg } 14223 1.1 joerg } 14224 1.1 joerg } else { 14225 1.1 joerg if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) 14226 1.1 joerg return Error(E, diag::note_expr_divide_by_zero); 14227 1.1 joerg 14228 1.1 joerg ComplexValue LHS = Result; 14229 1.1 joerg APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() + 14230 1.1 joerg RHS.getComplexIntImag() * RHS.getComplexIntImag(); 14231 1.1 joerg Result.getComplexIntReal() = 14232 1.1 joerg (LHS.getComplexIntReal() * RHS.getComplexIntReal() + 14233 1.1 joerg LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den; 14234 1.1 joerg Result.getComplexIntImag() = 14235 1.1 joerg (LHS.getComplexIntImag() * RHS.getComplexIntReal() - 14236 1.1 joerg LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den; 14237 1.1 joerg } 14238 1.1 joerg break; 14239 1.1 joerg } 14240 1.1 joerg 14241 1.1 joerg return true; 14242 1.1 joerg } 14243 1.1 joerg 14244 1.1 joerg bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 14245 1.1 joerg // Get the operand value into 'Result'. 14246 1.1 joerg if (!Visit(E->getSubExpr())) 14247 1.1 joerg return false; 14248 1.1 joerg 14249 1.1 joerg switch (E->getOpcode()) { 14250 1.1 joerg default: 14251 1.1 joerg return Error(E); 14252 1.1 joerg case UO_Extension: 14253 1.1 joerg return true; 14254 1.1 joerg case UO_Plus: 14255 1.1 joerg // The result is always just the subexpr. 14256 1.1 joerg return true; 14257 1.1 joerg case UO_Minus: 14258 1.1 joerg if (Result.isComplexFloat()) { 14259 1.1 joerg Result.getComplexFloatReal().changeSign(); 14260 1.1 joerg Result.getComplexFloatImag().changeSign(); 14261 1.1 joerg } 14262 1.1 joerg else { 14263 1.1 joerg Result.getComplexIntReal() = -Result.getComplexIntReal(); 14264 1.1 joerg Result.getComplexIntImag() = -Result.getComplexIntImag(); 14265 1.1 joerg } 14266 1.1 joerg return true; 14267 1.1 joerg case UO_Not: 14268 1.1 joerg if (Result.isComplexFloat()) 14269 1.1 joerg Result.getComplexFloatImag().changeSign(); 14270 1.1 joerg else 14271 1.1 joerg Result.getComplexIntImag() = -Result.getComplexIntImag(); 14272 1.1 joerg return true; 14273 1.1 joerg } 14274 1.1 joerg } 14275 1.1 joerg 14276 1.1 joerg bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 14277 1.1 joerg if (E->getNumInits() == 2) { 14278 1.1 joerg if (E->getType()->isComplexType()) { 14279 1.1 joerg Result.makeComplexFloat(); 14280 1.1 joerg if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info)) 14281 1.1 joerg return false; 14282 1.1 joerg if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info)) 14283 1.1 joerg return false; 14284 1.1 joerg } else { 14285 1.1 joerg Result.makeComplexInt(); 14286 1.1 joerg if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info)) 14287 1.1 joerg return false; 14288 1.1 joerg if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info)) 14289 1.1 joerg return false; 14290 1.1 joerg } 14291 1.1 joerg return true; 14292 1.1 joerg } 14293 1.1 joerg return ExprEvaluatorBaseTy::VisitInitListExpr(E); 14294 1.1 joerg } 14295 1.1 joerg 14296 1.1.1.2 joerg bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) { 14297 1.1.1.2 joerg switch (E->getBuiltinCallee()) { 14298 1.1.1.2 joerg case Builtin::BI__builtin_complex: 14299 1.1.1.2 joerg Result.makeComplexFloat(); 14300 1.1.1.2 joerg if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info)) 14301 1.1.1.2 joerg return false; 14302 1.1.1.2 joerg if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info)) 14303 1.1.1.2 joerg return false; 14304 1.1.1.2 joerg return true; 14305 1.1.1.2 joerg 14306 1.1.1.2 joerg default: 14307 1.1.1.2 joerg break; 14308 1.1.1.2 joerg } 14309 1.1.1.2 joerg 14310 1.1.1.2 joerg return ExprEvaluatorBaseTy::VisitCallExpr(E); 14311 1.1.1.2 joerg } 14312 1.1.1.2 joerg 14313 1.1 joerg //===----------------------------------------------------------------------===// 14314 1.1 joerg // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic 14315 1.1 joerg // implicit conversion. 14316 1.1 joerg //===----------------------------------------------------------------------===// 14317 1.1 joerg 14318 1.1 joerg namespace { 14319 1.1 joerg class AtomicExprEvaluator : 14320 1.1 joerg public ExprEvaluatorBase<AtomicExprEvaluator> { 14321 1.1 joerg const LValue *This; 14322 1.1 joerg APValue &Result; 14323 1.1 joerg public: 14324 1.1 joerg AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result) 14325 1.1 joerg : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 14326 1.1 joerg 14327 1.1 joerg bool Success(const APValue &V, const Expr *E) { 14328 1.1 joerg Result = V; 14329 1.1 joerg return true; 14330 1.1 joerg } 14331 1.1 joerg 14332 1.1 joerg bool ZeroInitialization(const Expr *E) { 14333 1.1 joerg ImplicitValueInitExpr VIE( 14334 1.1 joerg E->getType()->castAs<AtomicType>()->getValueType()); 14335 1.1 joerg // For atomic-qualified class (and array) types in C++, initialize the 14336 1.1 joerg // _Atomic-wrapped subobject directly, in-place. 14337 1.1 joerg return This ? EvaluateInPlace(Result, Info, *This, &VIE) 14338 1.1 joerg : Evaluate(Result, Info, &VIE); 14339 1.1 joerg } 14340 1.1 joerg 14341 1.1 joerg bool VisitCastExpr(const CastExpr *E) { 14342 1.1 joerg switch (E->getCastKind()) { 14343 1.1 joerg default: 14344 1.1 joerg return ExprEvaluatorBaseTy::VisitCastExpr(E); 14345 1.1 joerg case CK_NonAtomicToAtomic: 14346 1.1 joerg return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr()) 14347 1.1 joerg : Evaluate(Result, Info, E->getSubExpr()); 14348 1.1 joerg } 14349 1.1 joerg } 14350 1.1 joerg }; 14351 1.1 joerg } // end anonymous namespace 14352 1.1 joerg 14353 1.1 joerg static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, 14354 1.1 joerg EvalInfo &Info) { 14355 1.1.1.2 joerg assert(!E->isValueDependent()); 14356 1.1 joerg assert(E->isRValue() && E->getType()->isAtomicType()); 14357 1.1 joerg return AtomicExprEvaluator(Info, This, Result).Visit(E); 14358 1.1 joerg } 14359 1.1 joerg 14360 1.1 joerg //===----------------------------------------------------------------------===// 14361 1.1 joerg // Void expression evaluation, primarily for a cast to void on the LHS of a 14362 1.1 joerg // comma operator 14363 1.1 joerg //===----------------------------------------------------------------------===// 14364 1.1 joerg 14365 1.1 joerg namespace { 14366 1.1 joerg class VoidExprEvaluator 14367 1.1 joerg : public ExprEvaluatorBase<VoidExprEvaluator> { 14368 1.1 joerg public: 14369 1.1 joerg VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {} 14370 1.1 joerg 14371 1.1 joerg bool Success(const APValue &V, const Expr *e) { return true; } 14372 1.1 joerg 14373 1.1 joerg bool ZeroInitialization(const Expr *E) { return true; } 14374 1.1 joerg 14375 1.1 joerg bool VisitCastExpr(const CastExpr *E) { 14376 1.1 joerg switch (E->getCastKind()) { 14377 1.1 joerg default: 14378 1.1 joerg return ExprEvaluatorBaseTy::VisitCastExpr(E); 14379 1.1 joerg case CK_ToVoid: 14380 1.1 joerg VisitIgnoredValue(E->getSubExpr()); 14381 1.1 joerg return true; 14382 1.1 joerg } 14383 1.1 joerg } 14384 1.1 joerg 14385 1.1 joerg bool VisitCallExpr(const CallExpr *E) { 14386 1.1 joerg switch (E->getBuiltinCallee()) { 14387 1.1 joerg case Builtin::BI__assume: 14388 1.1 joerg case Builtin::BI__builtin_assume: 14389 1.1 joerg // The argument is not evaluated! 14390 1.1 joerg return true; 14391 1.1 joerg 14392 1.1 joerg case Builtin::BI__builtin_operator_delete: 14393 1.1 joerg return HandleOperatorDeleteCall(Info, E); 14394 1.1 joerg 14395 1.1 joerg default: 14396 1.1 joerg break; 14397 1.1 joerg } 14398 1.1 joerg 14399 1.1 joerg return ExprEvaluatorBaseTy::VisitCallExpr(E); 14400 1.1 joerg } 14401 1.1 joerg 14402 1.1 joerg bool VisitCXXDeleteExpr(const CXXDeleteExpr *E); 14403 1.1 joerg }; 14404 1.1 joerg } // end anonymous namespace 14405 1.1 joerg 14406 1.1 joerg bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) { 14407 1.1 joerg // We cannot speculatively evaluate a delete expression. 14408 1.1 joerg if (Info.SpeculativeEvaluationDepth) 14409 1.1 joerg return false; 14410 1.1 joerg 14411 1.1 joerg FunctionDecl *OperatorDelete = E->getOperatorDelete(); 14412 1.1 joerg if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) { 14413 1.1 joerg Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 14414 1.1 joerg << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete; 14415 1.1 joerg return false; 14416 1.1 joerg } 14417 1.1 joerg 14418 1.1 joerg const Expr *Arg = E->getArgument(); 14419 1.1 joerg 14420 1.1 joerg LValue Pointer; 14421 1.1 joerg if (!EvaluatePointer(Arg, Pointer, Info)) 14422 1.1 joerg return false; 14423 1.1 joerg if (Pointer.Designator.Invalid) 14424 1.1 joerg return false; 14425 1.1 joerg 14426 1.1 joerg // Deleting a null pointer has no effect. 14427 1.1 joerg if (Pointer.isNullPointer()) { 14428 1.1 joerg // This is the only case where we need to produce an extension warning: 14429 1.1 joerg // the only other way we can succeed is if we find a dynamic allocation, 14430 1.1 joerg // and we will have warned when we allocated it in that case. 14431 1.1.1.2 joerg if (!Info.getLangOpts().CPlusPlus20) 14432 1.1 joerg Info.CCEDiag(E, diag::note_constexpr_new); 14433 1.1 joerg return true; 14434 1.1 joerg } 14435 1.1 joerg 14436 1.1 joerg Optional<DynAlloc *> Alloc = CheckDeleteKind( 14437 1.1 joerg Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New); 14438 1.1 joerg if (!Alloc) 14439 1.1 joerg return false; 14440 1.1 joerg QualType AllocType = Pointer.Base.getDynamicAllocType(); 14441 1.1 joerg 14442 1.1 joerg // For the non-array case, the designator must be empty if the static type 14443 1.1 joerg // does not have a virtual destructor. 14444 1.1 joerg if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 && 14445 1.1 joerg !hasVirtualDestructor(Arg->getType()->getPointeeType())) { 14446 1.1 joerg Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor) 14447 1.1 joerg << Arg->getType()->getPointeeType() << AllocType; 14448 1.1 joerg return false; 14449 1.1 joerg } 14450 1.1 joerg 14451 1.1 joerg // For a class type with a virtual destructor, the selected operator delete 14452 1.1 joerg // is the one looked up when building the destructor. 14453 1.1 joerg if (!E->isArrayForm() && !E->isGlobalDelete()) { 14454 1.1 joerg const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType); 14455 1.1 joerg if (VirtualDelete && 14456 1.1 joerg !VirtualDelete->isReplaceableGlobalAllocationFunction()) { 14457 1.1 joerg Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 14458 1.1 joerg << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete; 14459 1.1 joerg return false; 14460 1.1 joerg } 14461 1.1 joerg } 14462 1.1 joerg 14463 1.1 joerg if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(), 14464 1.1 joerg (*Alloc)->Value, AllocType)) 14465 1.1 joerg return false; 14466 1.1 joerg 14467 1.1 joerg if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) { 14468 1.1 joerg // The element was already erased. This means the destructor call also 14469 1.1 joerg // deleted the object. 14470 1.1 joerg // FIXME: This probably results in undefined behavior before we get this 14471 1.1 joerg // far, and should be diagnosed elsewhere first. 14472 1.1 joerg Info.FFDiag(E, diag::note_constexpr_double_delete); 14473 1.1 joerg return false; 14474 1.1 joerg } 14475 1.1 joerg 14476 1.1 joerg return true; 14477 1.1 joerg } 14478 1.1 joerg 14479 1.1 joerg static bool EvaluateVoid(const Expr *E, EvalInfo &Info) { 14480 1.1.1.2 joerg assert(!E->isValueDependent()); 14481 1.1 joerg assert(E->isRValue() && E->getType()->isVoidType()); 14482 1.1 joerg return VoidExprEvaluator(Info).Visit(E); 14483 1.1 joerg } 14484 1.1 joerg 14485 1.1 joerg //===----------------------------------------------------------------------===// 14486 1.1 joerg // Top level Expr::EvaluateAsRValue method. 14487 1.1 joerg //===----------------------------------------------------------------------===// 14488 1.1 joerg 14489 1.1 joerg static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) { 14490 1.1.1.2 joerg assert(!E->isValueDependent()); 14491 1.1 joerg // In C, function designators are not lvalues, but we evaluate them as if they 14492 1.1 joerg // are. 14493 1.1 joerg QualType T = E->getType(); 14494 1.1 joerg if (E->isGLValue() || T->isFunctionType()) { 14495 1.1 joerg LValue LV; 14496 1.1 joerg if (!EvaluateLValue(E, LV, Info)) 14497 1.1 joerg return false; 14498 1.1 joerg LV.moveInto(Result); 14499 1.1 joerg } else if (T->isVectorType()) { 14500 1.1 joerg if (!EvaluateVector(E, Result, Info)) 14501 1.1 joerg return false; 14502 1.1 joerg } else if (T->isIntegralOrEnumerationType()) { 14503 1.1 joerg if (!IntExprEvaluator(Info, Result).Visit(E)) 14504 1.1 joerg return false; 14505 1.1 joerg } else if (T->hasPointerRepresentation()) { 14506 1.1 joerg LValue LV; 14507 1.1 joerg if (!EvaluatePointer(E, LV, Info)) 14508 1.1 joerg return false; 14509 1.1 joerg LV.moveInto(Result); 14510 1.1 joerg } else if (T->isRealFloatingType()) { 14511 1.1 joerg llvm::APFloat F(0.0); 14512 1.1 joerg if (!EvaluateFloat(E, F, Info)) 14513 1.1 joerg return false; 14514 1.1 joerg Result = APValue(F); 14515 1.1 joerg } else if (T->isAnyComplexType()) { 14516 1.1 joerg ComplexValue C; 14517 1.1 joerg if (!EvaluateComplex(E, C, Info)) 14518 1.1 joerg return false; 14519 1.1 joerg C.moveInto(Result); 14520 1.1 joerg } else if (T->isFixedPointType()) { 14521 1.1 joerg if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false; 14522 1.1 joerg } else if (T->isMemberPointerType()) { 14523 1.1 joerg MemberPtr P; 14524 1.1 joerg if (!EvaluateMemberPointer(E, P, Info)) 14525 1.1 joerg return false; 14526 1.1 joerg P.moveInto(Result); 14527 1.1 joerg return true; 14528 1.1 joerg } else if (T->isArrayType()) { 14529 1.1 joerg LValue LV; 14530 1.1 joerg APValue &Value = 14531 1.1.1.2 joerg Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV); 14532 1.1 joerg if (!EvaluateArray(E, LV, Value, Info)) 14533 1.1 joerg return false; 14534 1.1 joerg Result = Value; 14535 1.1 joerg } else if (T->isRecordType()) { 14536 1.1 joerg LValue LV; 14537 1.1.1.2 joerg APValue &Value = 14538 1.1.1.2 joerg Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV); 14539 1.1 joerg if (!EvaluateRecord(E, LV, Value, Info)) 14540 1.1 joerg return false; 14541 1.1 joerg Result = Value; 14542 1.1 joerg } else if (T->isVoidType()) { 14543 1.1 joerg if (!Info.getLangOpts().CPlusPlus11) 14544 1.1 joerg Info.CCEDiag(E, diag::note_constexpr_nonliteral) 14545 1.1 joerg << E->getType(); 14546 1.1 joerg if (!EvaluateVoid(E, Info)) 14547 1.1 joerg return false; 14548 1.1 joerg } else if (T->isAtomicType()) { 14549 1.1 joerg QualType Unqual = T.getAtomicUnqualifiedType(); 14550 1.1 joerg if (Unqual->isArrayType() || Unqual->isRecordType()) { 14551 1.1 joerg LValue LV; 14552 1.1.1.2 joerg APValue &Value = Info.CurrentCall->createTemporary( 14553 1.1.1.2 joerg E, Unqual, ScopeKind::FullExpression, LV); 14554 1.1 joerg if (!EvaluateAtomic(E, &LV, Value, Info)) 14555 1.1 joerg return false; 14556 1.1 joerg } else { 14557 1.1 joerg if (!EvaluateAtomic(E, nullptr, Result, Info)) 14558 1.1 joerg return false; 14559 1.1 joerg } 14560 1.1 joerg } else if (Info.getLangOpts().CPlusPlus11) { 14561 1.1 joerg Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType(); 14562 1.1 joerg return false; 14563 1.1 joerg } else { 14564 1.1 joerg Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 14565 1.1 joerg return false; 14566 1.1 joerg } 14567 1.1 joerg 14568 1.1 joerg return true; 14569 1.1 joerg } 14570 1.1 joerg 14571 1.1 joerg /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some 14572 1.1 joerg /// cases, the in-place evaluation is essential, since later initializers for 14573 1.1 joerg /// an object can indirectly refer to subobjects which were initialized earlier. 14574 1.1 joerg static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This, 14575 1.1 joerg const Expr *E, bool AllowNonLiteralTypes) { 14576 1.1 joerg assert(!E->isValueDependent()); 14577 1.1 joerg 14578 1.1 joerg if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This)) 14579 1.1 joerg return false; 14580 1.1 joerg 14581 1.1 joerg if (E->isRValue()) { 14582 1.1 joerg // Evaluate arrays and record types in-place, so that later initializers can 14583 1.1 joerg // refer to earlier-initialized members of the object. 14584 1.1 joerg QualType T = E->getType(); 14585 1.1 joerg if (T->isArrayType()) 14586 1.1 joerg return EvaluateArray(E, This, Result, Info); 14587 1.1 joerg else if (T->isRecordType()) 14588 1.1 joerg return EvaluateRecord(E, This, Result, Info); 14589 1.1 joerg else if (T->isAtomicType()) { 14590 1.1 joerg QualType Unqual = T.getAtomicUnqualifiedType(); 14591 1.1 joerg if (Unqual->isArrayType() || Unqual->isRecordType()) 14592 1.1 joerg return EvaluateAtomic(E, &This, Result, Info); 14593 1.1 joerg } 14594 1.1 joerg } 14595 1.1 joerg 14596 1.1 joerg // For any other type, in-place evaluation is unimportant. 14597 1.1 joerg return Evaluate(Result, Info, E); 14598 1.1 joerg } 14599 1.1 joerg 14600 1.1 joerg /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit 14601 1.1 joerg /// lvalue-to-rvalue cast if it is an lvalue. 14602 1.1 joerg static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) { 14603 1.1.1.2 joerg assert(!E->isValueDependent()); 14604 1.1.1.2 joerg if (Info.EnableNewConstInterp) { 14605 1.1.1.2 joerg if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result)) 14606 1.1.1.2 joerg return false; 14607 1.1.1.2 joerg } else { 14608 1.1.1.2 joerg if (E->getType().isNull()) 14609 1.1 joerg return false; 14610 1.1 joerg 14611 1.1.1.2 joerg if (!CheckLiteralType(Info, E)) 14612 1.1.1.2 joerg return false; 14613 1.1 joerg 14614 1.1.1.2 joerg if (!::Evaluate(Result, Info, E)) 14615 1.1 joerg return false; 14616 1.1.1.2 joerg 14617 1.1.1.2 joerg if (E->isGLValue()) { 14618 1.1.1.2 joerg LValue LV; 14619 1.1.1.2 joerg LV.setFrom(Info.Ctx, Result); 14620 1.1.1.2 joerg if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) 14621 1.1.1.2 joerg return false; 14622 1.1.1.2 joerg } 14623 1.1 joerg } 14624 1.1 joerg 14625 1.1 joerg // Check this core constant expression is a constant expression. 14626 1.1.1.2 joerg return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result, 14627 1.1.1.2 joerg ConstantExprKind::Normal) && 14628 1.1 joerg CheckMemoryLeaks(Info); 14629 1.1 joerg } 14630 1.1 joerg 14631 1.1 joerg static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result, 14632 1.1 joerg const ASTContext &Ctx, bool &IsConst) { 14633 1.1 joerg // Fast-path evaluations of integer literals, since we sometimes see files 14634 1.1 joerg // containing vast quantities of these. 14635 1.1 joerg if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) { 14636 1.1 joerg Result.Val = APValue(APSInt(L->getValue(), 14637 1.1 joerg L->getType()->isUnsignedIntegerType())); 14638 1.1 joerg IsConst = true; 14639 1.1 joerg return true; 14640 1.1 joerg } 14641 1.1 joerg 14642 1.1 joerg // This case should be rare, but we need to check it before we check on 14643 1.1 joerg // the type below. 14644 1.1 joerg if (Exp->getType().isNull()) { 14645 1.1 joerg IsConst = false; 14646 1.1 joerg return true; 14647 1.1 joerg } 14648 1.1 joerg 14649 1.1 joerg // FIXME: Evaluating values of large array and record types can cause 14650 1.1 joerg // performance problems. Only do so in C++11 for now. 14651 1.1 joerg if (Exp->isRValue() && (Exp->getType()->isArrayType() || 14652 1.1 joerg Exp->getType()->isRecordType()) && 14653 1.1 joerg !Ctx.getLangOpts().CPlusPlus11) { 14654 1.1 joerg IsConst = false; 14655 1.1 joerg return true; 14656 1.1 joerg } 14657 1.1 joerg return false; 14658 1.1 joerg } 14659 1.1 joerg 14660 1.1 joerg static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result, 14661 1.1 joerg Expr::SideEffectsKind SEK) { 14662 1.1 joerg return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) || 14663 1.1 joerg (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior); 14664 1.1 joerg } 14665 1.1 joerg 14666 1.1 joerg static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result, 14667 1.1 joerg const ASTContext &Ctx, EvalInfo &Info) { 14668 1.1.1.2 joerg assert(!E->isValueDependent()); 14669 1.1 joerg bool IsConst; 14670 1.1 joerg if (FastEvaluateAsRValue(E, Result, Ctx, IsConst)) 14671 1.1 joerg return IsConst; 14672 1.1 joerg 14673 1.1 joerg return EvaluateAsRValue(Info, E, Result.Val); 14674 1.1 joerg } 14675 1.1 joerg 14676 1.1 joerg static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult, 14677 1.1 joerg const ASTContext &Ctx, 14678 1.1 joerg Expr::SideEffectsKind AllowSideEffects, 14679 1.1 joerg EvalInfo &Info) { 14680 1.1.1.2 joerg assert(!E->isValueDependent()); 14681 1.1 joerg if (!E->getType()->isIntegralOrEnumerationType()) 14682 1.1 joerg return false; 14683 1.1 joerg 14684 1.1 joerg if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) || 14685 1.1 joerg !ExprResult.Val.isInt() || 14686 1.1 joerg hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 14687 1.1 joerg return false; 14688 1.1 joerg 14689 1.1 joerg return true; 14690 1.1 joerg } 14691 1.1 joerg 14692 1.1 joerg static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult, 14693 1.1 joerg const ASTContext &Ctx, 14694 1.1 joerg Expr::SideEffectsKind AllowSideEffects, 14695 1.1 joerg EvalInfo &Info) { 14696 1.1.1.2 joerg assert(!E->isValueDependent()); 14697 1.1 joerg if (!E->getType()->isFixedPointType()) 14698 1.1 joerg return false; 14699 1.1 joerg 14700 1.1 joerg if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info)) 14701 1.1 joerg return false; 14702 1.1 joerg 14703 1.1 joerg if (!ExprResult.Val.isFixedPoint() || 14704 1.1 joerg hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 14705 1.1 joerg return false; 14706 1.1 joerg 14707 1.1 joerg return true; 14708 1.1 joerg } 14709 1.1 joerg 14710 1.1 joerg /// EvaluateAsRValue - Return true if this is a constant which we can fold using 14711 1.1 joerg /// any crazy technique (that has nothing to do with language standards) that 14712 1.1 joerg /// we want to. If this function returns true, it returns the folded constant 14713 1.1 joerg /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion 14714 1.1 joerg /// will be applied to the result. 14715 1.1 joerg bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, 14716 1.1 joerg bool InConstantContext) const { 14717 1.1 joerg assert(!isValueDependent() && 14718 1.1 joerg "Expression evaluator can't be called on a dependent expression."); 14719 1.1 joerg EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 14720 1.1 joerg Info.InConstantContext = InConstantContext; 14721 1.1 joerg return ::EvaluateAsRValue(this, Result, Ctx, Info); 14722 1.1 joerg } 14723 1.1 joerg 14724 1.1 joerg bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx, 14725 1.1 joerg bool InConstantContext) const { 14726 1.1 joerg assert(!isValueDependent() && 14727 1.1 joerg "Expression evaluator can't be called on a dependent expression."); 14728 1.1 joerg EvalResult Scratch; 14729 1.1 joerg return EvaluateAsRValue(Scratch, Ctx, InConstantContext) && 14730 1.1 joerg HandleConversionToBool(Scratch.Val, Result); 14731 1.1 joerg } 14732 1.1 joerg 14733 1.1 joerg bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, 14734 1.1 joerg SideEffectsKind AllowSideEffects, 14735 1.1 joerg bool InConstantContext) const { 14736 1.1 joerg assert(!isValueDependent() && 14737 1.1 joerg "Expression evaluator can't be called on a dependent expression."); 14738 1.1 joerg EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 14739 1.1 joerg Info.InConstantContext = InConstantContext; 14740 1.1 joerg return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info); 14741 1.1 joerg } 14742 1.1 joerg 14743 1.1 joerg bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx, 14744 1.1 joerg SideEffectsKind AllowSideEffects, 14745 1.1 joerg bool InConstantContext) const { 14746 1.1 joerg assert(!isValueDependent() && 14747 1.1 joerg "Expression evaluator can't be called on a dependent expression."); 14748 1.1 joerg EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 14749 1.1 joerg Info.InConstantContext = InConstantContext; 14750 1.1 joerg return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info); 14751 1.1 joerg } 14752 1.1 joerg 14753 1.1 joerg bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx, 14754 1.1 joerg SideEffectsKind AllowSideEffects, 14755 1.1 joerg bool InConstantContext) const { 14756 1.1 joerg assert(!isValueDependent() && 14757 1.1 joerg "Expression evaluator can't be called on a dependent expression."); 14758 1.1 joerg 14759 1.1 joerg if (!getType()->isRealFloatingType()) 14760 1.1 joerg return false; 14761 1.1 joerg 14762 1.1 joerg EvalResult ExprResult; 14763 1.1 joerg if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) || 14764 1.1 joerg !ExprResult.Val.isFloat() || 14765 1.1 joerg hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 14766 1.1 joerg return false; 14767 1.1 joerg 14768 1.1 joerg Result = ExprResult.Val.getFloat(); 14769 1.1 joerg return true; 14770 1.1 joerg } 14771 1.1 joerg 14772 1.1 joerg bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx, 14773 1.1 joerg bool InConstantContext) const { 14774 1.1 joerg assert(!isValueDependent() && 14775 1.1 joerg "Expression evaluator can't be called on a dependent expression."); 14776 1.1 joerg 14777 1.1 joerg EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold); 14778 1.1 joerg Info.InConstantContext = InConstantContext; 14779 1.1 joerg LValue LV; 14780 1.1 joerg CheckedTemporaries CheckedTemps; 14781 1.1 joerg if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() || 14782 1.1 joerg Result.HasSideEffects || 14783 1.1 joerg !CheckLValueConstantExpression(Info, getExprLoc(), 14784 1.1 joerg Ctx.getLValueReferenceType(getType()), LV, 14785 1.1.1.2 joerg ConstantExprKind::Normal, CheckedTemps)) 14786 1.1 joerg return false; 14787 1.1 joerg 14788 1.1 joerg LV.moveInto(Result.Val); 14789 1.1 joerg return true; 14790 1.1 joerg } 14791 1.1 joerg 14792 1.1.1.2 joerg static bool EvaluateDestruction(const ASTContext &Ctx, APValue::LValueBase Base, 14793 1.1.1.2 joerg APValue DestroyedValue, QualType Type, 14794 1.1.1.2 joerg SourceLocation Loc, Expr::EvalStatus &EStatus, 14795 1.1.1.2 joerg bool IsConstantDestruction) { 14796 1.1.1.2 joerg EvalInfo Info(Ctx, EStatus, 14797 1.1.1.2 joerg IsConstantDestruction ? EvalInfo::EM_ConstantExpression 14798 1.1.1.2 joerg : EvalInfo::EM_ConstantFold); 14799 1.1.1.2 joerg Info.setEvaluatingDecl(Base, DestroyedValue, 14800 1.1.1.2 joerg EvalInfo::EvaluatingDeclKind::Dtor); 14801 1.1.1.2 joerg Info.InConstantContext = IsConstantDestruction; 14802 1.1.1.2 joerg 14803 1.1.1.2 joerg LValue LVal; 14804 1.1.1.2 joerg LVal.set(Base); 14805 1.1.1.2 joerg 14806 1.1.1.2 joerg if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) || 14807 1.1.1.2 joerg EStatus.HasSideEffects) 14808 1.1.1.2 joerg return false; 14809 1.1.1.2 joerg 14810 1.1.1.2 joerg if (!Info.discardCleanups()) 14811 1.1.1.2 joerg llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 14812 1.1.1.2 joerg 14813 1.1.1.2 joerg return true; 14814 1.1.1.2 joerg } 14815 1.1.1.2 joerg 14816 1.1.1.2 joerg bool Expr::EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx, 14817 1.1.1.2 joerg ConstantExprKind Kind) const { 14818 1.1 joerg assert(!isValueDependent() && 14819 1.1 joerg "Expression evaluator can't be called on a dependent expression."); 14820 1.1 joerg 14821 1.1 joerg EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression; 14822 1.1 joerg EvalInfo Info(Ctx, Result, EM); 14823 1.1 joerg Info.InConstantContext = true; 14824 1.1 joerg 14825 1.1.1.2 joerg // The type of the object we're initializing is 'const T' for a class NTTP. 14826 1.1.1.2 joerg QualType T = getType(); 14827 1.1.1.2 joerg if (Kind == ConstantExprKind::ClassTemplateArgument) 14828 1.1.1.2 joerg T.addConst(); 14829 1.1.1.2 joerg 14830 1.1.1.2 joerg // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to 14831 1.1.1.2 joerg // represent the result of the evaluation. CheckConstantExpression ensures 14832 1.1.1.2 joerg // this doesn't escape. 14833 1.1.1.2 joerg MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true); 14834 1.1.1.2 joerg APValue::LValueBase Base(&BaseMTE); 14835 1.1.1.2 joerg 14836 1.1.1.2 joerg Info.setEvaluatingDecl(Base, Result.Val); 14837 1.1.1.2 joerg LValue LVal; 14838 1.1.1.2 joerg LVal.set(Base); 14839 1.1.1.2 joerg 14840 1.1.1.2 joerg if (!::EvaluateInPlace(Result.Val, Info, LVal, this) || Result.HasSideEffects) 14841 1.1 joerg return false; 14842 1.1 joerg 14843 1.1 joerg if (!Info.discardCleanups()) 14844 1.1 joerg llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 14845 1.1 joerg 14846 1.1.1.2 joerg if (!CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this), 14847 1.1.1.2 joerg Result.Val, Kind)) 14848 1.1.1.2 joerg return false; 14849 1.1.1.2 joerg if (!CheckMemoryLeaks(Info)) 14850 1.1.1.2 joerg return false; 14851 1.1.1.2 joerg 14852 1.1.1.2 joerg // If this is a class template argument, it's required to have constant 14853 1.1.1.2 joerg // destruction too. 14854 1.1.1.2 joerg if (Kind == ConstantExprKind::ClassTemplateArgument && 14855 1.1.1.2 joerg (!EvaluateDestruction(Ctx, Base, Result.Val, T, getBeginLoc(), Result, 14856 1.1.1.2 joerg true) || 14857 1.1.1.2 joerg Result.HasSideEffects)) { 14858 1.1.1.2 joerg // FIXME: Prefix a note to indicate that the problem is lack of constant 14859 1.1.1.2 joerg // destruction. 14860 1.1.1.2 joerg return false; 14861 1.1.1.2 joerg } 14862 1.1.1.2 joerg 14863 1.1.1.2 joerg return true; 14864 1.1 joerg } 14865 1.1 joerg 14866 1.1 joerg bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx, 14867 1.1 joerg const VarDecl *VD, 14868 1.1.1.2 joerg SmallVectorImpl<PartialDiagnosticAt> &Notes, 14869 1.1.1.2 joerg bool IsConstantInitialization) const { 14870 1.1 joerg assert(!isValueDependent() && 14871 1.1 joerg "Expression evaluator can't be called on a dependent expression."); 14872 1.1 joerg 14873 1.1 joerg // FIXME: Evaluating initializers for large array and record types can cause 14874 1.1 joerg // performance problems. Only do so in C++11 for now. 14875 1.1 joerg if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) && 14876 1.1 joerg !Ctx.getLangOpts().CPlusPlus11) 14877 1.1 joerg return false; 14878 1.1 joerg 14879 1.1 joerg Expr::EvalStatus EStatus; 14880 1.1 joerg EStatus.Diag = &Notes; 14881 1.1 joerg 14882 1.1.1.2 joerg EvalInfo Info(Ctx, EStatus, 14883 1.1.1.2 joerg (IsConstantInitialization && Ctx.getLangOpts().CPlusPlus11) 14884 1.1.1.2 joerg ? EvalInfo::EM_ConstantExpression 14885 1.1.1.2 joerg : EvalInfo::EM_ConstantFold); 14886 1.1 joerg Info.setEvaluatingDecl(VD, Value); 14887 1.1.1.2 joerg Info.InConstantContext = IsConstantInitialization; 14888 1.1 joerg 14889 1.1 joerg SourceLocation DeclLoc = VD->getLocation(); 14890 1.1 joerg QualType DeclTy = VD->getType(); 14891 1.1 joerg 14892 1.1 joerg if (Info.EnableNewConstInterp) { 14893 1.1 joerg auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext(); 14894 1.1.1.2 joerg if (!InterpCtx.evaluateAsInitializer(Info, VD, Value)) 14895 1.1 joerg return false; 14896 1.1.1.2 joerg } else { 14897 1.1.1.2 joerg LValue LVal; 14898 1.1.1.2 joerg LVal.set(VD); 14899 1.1 joerg 14900 1.1.1.2 joerg if (!EvaluateInPlace(Value, Info, LVal, this, 14901 1.1.1.2 joerg /*AllowNonLiteralTypes=*/true) || 14902 1.1.1.2 joerg EStatus.HasSideEffects) 14903 1.1.1.2 joerg return false; 14904 1.1 joerg 14905 1.1.1.2 joerg // At this point, any lifetime-extended temporaries are completely 14906 1.1.1.2 joerg // initialized. 14907 1.1.1.2 joerg Info.performLifetimeExtension(); 14908 1.1 joerg 14909 1.1.1.2 joerg if (!Info.discardCleanups()) 14910 1.1.1.2 joerg llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 14911 1.1.1.2 joerg } 14912 1.1.1.2 joerg return CheckConstantExpression(Info, DeclLoc, DeclTy, Value, 14913 1.1.1.2 joerg ConstantExprKind::Normal) && 14914 1.1 joerg CheckMemoryLeaks(Info); 14915 1.1 joerg } 14916 1.1 joerg 14917 1.1 joerg bool VarDecl::evaluateDestruction( 14918 1.1 joerg SmallVectorImpl<PartialDiagnosticAt> &Notes) const { 14919 1.1 joerg Expr::EvalStatus EStatus; 14920 1.1 joerg EStatus.Diag = &Notes; 14921 1.1 joerg 14922 1.1.1.2 joerg // Only treat the destruction as constant destruction if we formally have 14923 1.1.1.2 joerg // constant initialization (or are usable in a constant expression). 14924 1.1.1.2 joerg bool IsConstantDestruction = hasConstantInitialization(); 14925 1.1.1.2 joerg 14926 1.1.1.2 joerg // Make a copy of the value for the destructor to mutate, if we know it. 14927 1.1.1.2 joerg // Otherwise, treat the value as default-initialized; if the destructor works 14928 1.1.1.2 joerg // anyway, then the destruction is constant (and must be essentially empty). 14929 1.1.1.2 joerg APValue DestroyedValue; 14930 1.1.1.2 joerg if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent()) 14931 1.1.1.2 joerg DestroyedValue = *getEvaluatedValue(); 14932 1.1.1.2 joerg else if (!getDefaultInitValue(getType(), DestroyedValue)) 14933 1.1.1.2 joerg return false; 14934 1.1.1.2 joerg 14935 1.1.1.2 joerg if (!EvaluateDestruction(getASTContext(), this, std::move(DestroyedValue), 14936 1.1.1.2 joerg getType(), getLocation(), EStatus, 14937 1.1.1.2 joerg IsConstantDestruction) || 14938 1.1 joerg EStatus.HasSideEffects) 14939 1.1 joerg return false; 14940 1.1 joerg 14941 1.1 joerg ensureEvaluatedStmt()->HasConstantDestruction = true; 14942 1.1 joerg return true; 14943 1.1 joerg } 14944 1.1 joerg 14945 1.1 joerg /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be 14946 1.1 joerg /// constant folded, but discard the result. 14947 1.1 joerg bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const { 14948 1.1 joerg assert(!isValueDependent() && 14949 1.1 joerg "Expression evaluator can't be called on a dependent expression."); 14950 1.1 joerg 14951 1.1 joerg EvalResult Result; 14952 1.1 joerg return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) && 14953 1.1 joerg !hasUnacceptableSideEffect(Result, SEK); 14954 1.1 joerg } 14955 1.1 joerg 14956 1.1 joerg APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx, 14957 1.1 joerg SmallVectorImpl<PartialDiagnosticAt> *Diag) const { 14958 1.1 joerg assert(!isValueDependent() && 14959 1.1 joerg "Expression evaluator can't be called on a dependent expression."); 14960 1.1 joerg 14961 1.1 joerg EvalResult EVResult; 14962 1.1 joerg EVResult.Diag = Diag; 14963 1.1 joerg EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 14964 1.1 joerg Info.InConstantContext = true; 14965 1.1 joerg 14966 1.1 joerg bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info); 14967 1.1 joerg (void)Result; 14968 1.1 joerg assert(Result && "Could not evaluate expression"); 14969 1.1 joerg assert(EVResult.Val.isInt() && "Expression did not evaluate to integer"); 14970 1.1 joerg 14971 1.1 joerg return EVResult.Val.getInt(); 14972 1.1 joerg } 14973 1.1 joerg 14974 1.1 joerg APSInt Expr::EvaluateKnownConstIntCheckOverflow( 14975 1.1 joerg const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const { 14976 1.1 joerg assert(!isValueDependent() && 14977 1.1 joerg "Expression evaluator can't be called on a dependent expression."); 14978 1.1 joerg 14979 1.1 joerg EvalResult EVResult; 14980 1.1 joerg EVResult.Diag = Diag; 14981 1.1 joerg EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 14982 1.1 joerg Info.InConstantContext = true; 14983 1.1 joerg Info.CheckingForUndefinedBehavior = true; 14984 1.1 joerg 14985 1.1 joerg bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val); 14986 1.1 joerg (void)Result; 14987 1.1 joerg assert(Result && "Could not evaluate expression"); 14988 1.1 joerg assert(EVResult.Val.isInt() && "Expression did not evaluate to integer"); 14989 1.1 joerg 14990 1.1 joerg return EVResult.Val.getInt(); 14991 1.1 joerg } 14992 1.1 joerg 14993 1.1 joerg void Expr::EvaluateForOverflow(const ASTContext &Ctx) const { 14994 1.1 joerg assert(!isValueDependent() && 14995 1.1 joerg "Expression evaluator can't be called on a dependent expression."); 14996 1.1 joerg 14997 1.1 joerg bool IsConst; 14998 1.1 joerg EvalResult EVResult; 14999 1.1 joerg if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) { 15000 1.1 joerg EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 15001 1.1 joerg Info.CheckingForUndefinedBehavior = true; 15002 1.1 joerg (void)::EvaluateAsRValue(Info, this, EVResult.Val); 15003 1.1 joerg } 15004 1.1 joerg } 15005 1.1 joerg 15006 1.1 joerg bool Expr::EvalResult::isGlobalLValue() const { 15007 1.1 joerg assert(Val.isLValue()); 15008 1.1 joerg return IsGlobalLValue(Val.getLValueBase()); 15009 1.1 joerg } 15010 1.1 joerg 15011 1.1 joerg /// isIntegerConstantExpr - this recursive routine will test if an expression is 15012 1.1 joerg /// an integer constant expression. 15013 1.1 joerg 15014 1.1 joerg /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero, 15015 1.1 joerg /// comma, etc 15016 1.1 joerg 15017 1.1 joerg // CheckICE - This function does the fundamental ICE checking: the returned 15018 1.1 joerg // ICEDiag contains an ICEKind indicating whether the expression is an ICE, 15019 1.1 joerg // and a (possibly null) SourceLocation indicating the location of the problem. 15020 1.1 joerg // 15021 1.1 joerg // Note that to reduce code duplication, this helper does no evaluation 15022 1.1 joerg // itself; the caller checks whether the expression is evaluatable, and 15023 1.1 joerg // in the rare cases where CheckICE actually cares about the evaluated 15024 1.1 joerg // value, it calls into Evaluate. 15025 1.1 joerg 15026 1.1 joerg namespace { 15027 1.1 joerg 15028 1.1 joerg enum ICEKind { 15029 1.1 joerg /// This expression is an ICE. 15030 1.1 joerg IK_ICE, 15031 1.1 joerg /// This expression is not an ICE, but if it isn't evaluated, it's 15032 1.1 joerg /// a legal subexpression for an ICE. This return value is used to handle 15033 1.1 joerg /// the comma operator in C99 mode, and non-constant subexpressions. 15034 1.1 joerg IK_ICEIfUnevaluated, 15035 1.1 joerg /// This expression is not an ICE, and is not a legal subexpression for one. 15036 1.1 joerg IK_NotICE 15037 1.1 joerg }; 15038 1.1 joerg 15039 1.1 joerg struct ICEDiag { 15040 1.1 joerg ICEKind Kind; 15041 1.1 joerg SourceLocation Loc; 15042 1.1 joerg 15043 1.1 joerg ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {} 15044 1.1 joerg }; 15045 1.1 joerg 15046 1.1 joerg } 15047 1.1 joerg 15048 1.1 joerg static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); } 15049 1.1 joerg 15050 1.1 joerg static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; } 15051 1.1 joerg 15052 1.1 joerg static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) { 15053 1.1 joerg Expr::EvalResult EVResult; 15054 1.1 joerg Expr::EvalStatus Status; 15055 1.1 joerg EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); 15056 1.1 joerg 15057 1.1 joerg Info.InConstantContext = true; 15058 1.1 joerg if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects || 15059 1.1 joerg !EVResult.Val.isInt()) 15060 1.1 joerg return ICEDiag(IK_NotICE, E->getBeginLoc()); 15061 1.1 joerg 15062 1.1 joerg return NoDiag(); 15063 1.1 joerg } 15064 1.1 joerg 15065 1.1 joerg static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) { 15066 1.1 joerg assert(!E->isValueDependent() && "Should not see value dependent exprs!"); 15067 1.1 joerg if (!E->getType()->isIntegralOrEnumerationType()) 15068 1.1 joerg return ICEDiag(IK_NotICE, E->getBeginLoc()); 15069 1.1 joerg 15070 1.1 joerg switch (E->getStmtClass()) { 15071 1.1 joerg #define ABSTRACT_STMT(Node) 15072 1.1 joerg #define STMT(Node, Base) case Expr::Node##Class: 15073 1.1 joerg #define EXPR(Node, Base) 15074 1.1 joerg #include "clang/AST/StmtNodes.inc" 15075 1.1 joerg case Expr::PredefinedExprClass: 15076 1.1 joerg case Expr::FloatingLiteralClass: 15077 1.1 joerg case Expr::ImaginaryLiteralClass: 15078 1.1 joerg case Expr::StringLiteralClass: 15079 1.1 joerg case Expr::ArraySubscriptExprClass: 15080 1.1.1.2 joerg case Expr::MatrixSubscriptExprClass: 15081 1.1 joerg case Expr::OMPArraySectionExprClass: 15082 1.1.1.2 joerg case Expr::OMPArrayShapingExprClass: 15083 1.1.1.2 joerg case Expr::OMPIteratorExprClass: 15084 1.1 joerg case Expr::MemberExprClass: 15085 1.1 joerg case Expr::CompoundAssignOperatorClass: 15086 1.1 joerg case Expr::CompoundLiteralExprClass: 15087 1.1 joerg case Expr::ExtVectorElementExprClass: 15088 1.1 joerg case Expr::DesignatedInitExprClass: 15089 1.1 joerg case Expr::ArrayInitLoopExprClass: 15090 1.1 joerg case Expr::ArrayInitIndexExprClass: 15091 1.1 joerg case Expr::NoInitExprClass: 15092 1.1 joerg case Expr::DesignatedInitUpdateExprClass: 15093 1.1 joerg case Expr::ImplicitValueInitExprClass: 15094 1.1 joerg case Expr::ParenListExprClass: 15095 1.1 joerg case Expr::VAArgExprClass: 15096 1.1 joerg case Expr::AddrLabelExprClass: 15097 1.1 joerg case Expr::StmtExprClass: 15098 1.1 joerg case Expr::CXXMemberCallExprClass: 15099 1.1 joerg case Expr::CUDAKernelCallExprClass: 15100 1.1.1.2 joerg case Expr::CXXAddrspaceCastExprClass: 15101 1.1 joerg case Expr::CXXDynamicCastExprClass: 15102 1.1 joerg case Expr::CXXTypeidExprClass: 15103 1.1 joerg case Expr::CXXUuidofExprClass: 15104 1.1 joerg case Expr::MSPropertyRefExprClass: 15105 1.1 joerg case Expr::MSPropertySubscriptExprClass: 15106 1.1 joerg case Expr::CXXNullPtrLiteralExprClass: 15107 1.1 joerg case Expr::UserDefinedLiteralClass: 15108 1.1 joerg case Expr::CXXThisExprClass: 15109 1.1 joerg case Expr::CXXThrowExprClass: 15110 1.1 joerg case Expr::CXXNewExprClass: 15111 1.1 joerg case Expr::CXXDeleteExprClass: 15112 1.1 joerg case Expr::CXXPseudoDestructorExprClass: 15113 1.1 joerg case Expr::UnresolvedLookupExprClass: 15114 1.1 joerg case Expr::TypoExprClass: 15115 1.1.1.2 joerg case Expr::RecoveryExprClass: 15116 1.1 joerg case Expr::DependentScopeDeclRefExprClass: 15117 1.1 joerg case Expr::CXXConstructExprClass: 15118 1.1 joerg case Expr::CXXInheritedCtorInitExprClass: 15119 1.1 joerg case Expr::CXXStdInitializerListExprClass: 15120 1.1 joerg case Expr::CXXBindTemporaryExprClass: 15121 1.1 joerg case Expr::ExprWithCleanupsClass: 15122 1.1 joerg case Expr::CXXTemporaryObjectExprClass: 15123 1.1 joerg case Expr::CXXUnresolvedConstructExprClass: 15124 1.1 joerg case Expr::CXXDependentScopeMemberExprClass: 15125 1.1 joerg case Expr::UnresolvedMemberExprClass: 15126 1.1 joerg case Expr::ObjCStringLiteralClass: 15127 1.1 joerg case Expr::ObjCBoxedExprClass: 15128 1.1 joerg case Expr::ObjCArrayLiteralClass: 15129 1.1 joerg case Expr::ObjCDictionaryLiteralClass: 15130 1.1 joerg case Expr::ObjCEncodeExprClass: 15131 1.1 joerg case Expr::ObjCMessageExprClass: 15132 1.1 joerg case Expr::ObjCSelectorExprClass: 15133 1.1 joerg case Expr::ObjCProtocolExprClass: 15134 1.1 joerg case Expr::ObjCIvarRefExprClass: 15135 1.1 joerg case Expr::ObjCPropertyRefExprClass: 15136 1.1 joerg case Expr::ObjCSubscriptRefExprClass: 15137 1.1 joerg case Expr::ObjCIsaExprClass: 15138 1.1 joerg case Expr::ObjCAvailabilityCheckExprClass: 15139 1.1 joerg case Expr::ShuffleVectorExprClass: 15140 1.1 joerg case Expr::ConvertVectorExprClass: 15141 1.1 joerg case Expr::BlockExprClass: 15142 1.1 joerg case Expr::NoStmtClass: 15143 1.1 joerg case Expr::OpaqueValueExprClass: 15144 1.1 joerg case Expr::PackExpansionExprClass: 15145 1.1 joerg case Expr::SubstNonTypeTemplateParmPackExprClass: 15146 1.1 joerg case Expr::FunctionParmPackExprClass: 15147 1.1 joerg case Expr::AsTypeExprClass: 15148 1.1 joerg case Expr::ObjCIndirectCopyRestoreExprClass: 15149 1.1 joerg case Expr::MaterializeTemporaryExprClass: 15150 1.1 joerg case Expr::PseudoObjectExprClass: 15151 1.1 joerg case Expr::AtomicExprClass: 15152 1.1 joerg case Expr::LambdaExprClass: 15153 1.1 joerg case Expr::CXXFoldExprClass: 15154 1.1 joerg case Expr::CoawaitExprClass: 15155 1.1 joerg case Expr::DependentCoawaitExprClass: 15156 1.1 joerg case Expr::CoyieldExprClass: 15157 1.1 joerg return ICEDiag(IK_NotICE, E->getBeginLoc()); 15158 1.1 joerg 15159 1.1 joerg case Expr::InitListExprClass: { 15160 1.1 joerg // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the 15161 1.1 joerg // form "T x = { a };" is equivalent to "T x = a;". 15162 1.1 joerg // Unless we're initializing a reference, T is a scalar as it is known to be 15163 1.1 joerg // of integral or enumeration type. 15164 1.1 joerg if (E->isRValue()) 15165 1.1 joerg if (cast<InitListExpr>(E)->getNumInits() == 1) 15166 1.1 joerg return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx); 15167 1.1 joerg return ICEDiag(IK_NotICE, E->getBeginLoc()); 15168 1.1 joerg } 15169 1.1 joerg 15170 1.1 joerg case Expr::SizeOfPackExprClass: 15171 1.1 joerg case Expr::GNUNullExprClass: 15172 1.1 joerg case Expr::SourceLocExprClass: 15173 1.1 joerg return NoDiag(); 15174 1.1 joerg 15175 1.1 joerg case Expr::SubstNonTypeTemplateParmExprClass: 15176 1.1 joerg return 15177 1.1 joerg CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx); 15178 1.1 joerg 15179 1.1 joerg case Expr::ConstantExprClass: 15180 1.1 joerg return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx); 15181 1.1 joerg 15182 1.1 joerg case Expr::ParenExprClass: 15183 1.1 joerg return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx); 15184 1.1 joerg case Expr::GenericSelectionExprClass: 15185 1.1 joerg return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx); 15186 1.1 joerg case Expr::IntegerLiteralClass: 15187 1.1 joerg case Expr::FixedPointLiteralClass: 15188 1.1 joerg case Expr::CharacterLiteralClass: 15189 1.1 joerg case Expr::ObjCBoolLiteralExprClass: 15190 1.1 joerg case Expr::CXXBoolLiteralExprClass: 15191 1.1 joerg case Expr::CXXScalarValueInitExprClass: 15192 1.1 joerg case Expr::TypeTraitExprClass: 15193 1.1 joerg case Expr::ConceptSpecializationExprClass: 15194 1.1.1.2 joerg case Expr::RequiresExprClass: 15195 1.1 joerg case Expr::ArrayTypeTraitExprClass: 15196 1.1 joerg case Expr::ExpressionTraitExprClass: 15197 1.1 joerg case Expr::CXXNoexceptExprClass: 15198 1.1 joerg return NoDiag(); 15199 1.1 joerg case Expr::CallExprClass: 15200 1.1 joerg case Expr::CXXOperatorCallExprClass: { 15201 1.1 joerg // C99 6.6/3 allows function calls within unevaluated subexpressions of 15202 1.1 joerg // constant expressions, but they can never be ICEs because an ICE cannot 15203 1.1 joerg // contain an operand of (pointer to) function type. 15204 1.1 joerg const CallExpr *CE = cast<CallExpr>(E); 15205 1.1 joerg if (CE->getBuiltinCallee()) 15206 1.1 joerg return CheckEvalInICE(E, Ctx); 15207 1.1 joerg return ICEDiag(IK_NotICE, E->getBeginLoc()); 15208 1.1 joerg } 15209 1.1 joerg case Expr::CXXRewrittenBinaryOperatorClass: 15210 1.1 joerg return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(), 15211 1.1 joerg Ctx); 15212 1.1 joerg case Expr::DeclRefExprClass: { 15213 1.1.1.2 joerg const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl(); 15214 1.1.1.2 joerg if (isa<EnumConstantDecl>(D)) 15215 1.1 joerg return NoDiag(); 15216 1.1.1.2 joerg 15217 1.1.1.2 joerg // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified 15218 1.1.1.2 joerg // integer variables in constant expressions: 15219 1.1.1.2 joerg // 15220 1.1.1.2 joerg // C++ 7.1.5.1p2 15221 1.1.1.2 joerg // A variable of non-volatile const-qualified integral or enumeration 15222 1.1.1.2 joerg // type initialized by an ICE can be used in ICEs. 15223 1.1.1.2 joerg // 15224 1.1.1.2 joerg // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In 15225 1.1.1.2 joerg // that mode, use of reference variables should not be allowed. 15226 1.1.1.2 joerg const VarDecl *VD = dyn_cast<VarDecl>(D); 15227 1.1.1.2 joerg if (VD && VD->isUsableInConstantExpressions(Ctx) && 15228 1.1.1.2 joerg !VD->getType()->isReferenceType()) 15229 1.1.1.2 joerg return NoDiag(); 15230 1.1.1.2 joerg 15231 1.1 joerg return ICEDiag(IK_NotICE, E->getBeginLoc()); 15232 1.1 joerg } 15233 1.1 joerg case Expr::UnaryOperatorClass: { 15234 1.1 joerg const UnaryOperator *Exp = cast<UnaryOperator>(E); 15235 1.1 joerg switch (Exp->getOpcode()) { 15236 1.1 joerg case UO_PostInc: 15237 1.1 joerg case UO_PostDec: 15238 1.1 joerg case UO_PreInc: 15239 1.1 joerg case UO_PreDec: 15240 1.1 joerg case UO_AddrOf: 15241 1.1 joerg case UO_Deref: 15242 1.1 joerg case UO_Coawait: 15243 1.1 joerg // C99 6.6/3 allows increment and decrement within unevaluated 15244 1.1 joerg // subexpressions of constant expressions, but they can never be ICEs 15245 1.1 joerg // because an ICE cannot contain an lvalue operand. 15246 1.1 joerg return ICEDiag(IK_NotICE, E->getBeginLoc()); 15247 1.1 joerg case UO_Extension: 15248 1.1 joerg case UO_LNot: 15249 1.1 joerg case UO_Plus: 15250 1.1 joerg case UO_Minus: 15251 1.1 joerg case UO_Not: 15252 1.1 joerg case UO_Real: 15253 1.1 joerg case UO_Imag: 15254 1.1 joerg return CheckICE(Exp->getSubExpr(), Ctx); 15255 1.1 joerg } 15256 1.1 joerg llvm_unreachable("invalid unary operator class"); 15257 1.1 joerg } 15258 1.1 joerg case Expr::OffsetOfExprClass: { 15259 1.1 joerg // Note that per C99, offsetof must be an ICE. And AFAIK, using 15260 1.1 joerg // EvaluateAsRValue matches the proposed gcc behavior for cases like 15261 1.1 joerg // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect 15262 1.1 joerg // compliance: we should warn earlier for offsetof expressions with 15263 1.1 joerg // array subscripts that aren't ICEs, and if the array subscripts 15264 1.1 joerg // are ICEs, the value of the offsetof must be an integer constant. 15265 1.1 joerg return CheckEvalInICE(E, Ctx); 15266 1.1 joerg } 15267 1.1 joerg case Expr::UnaryExprOrTypeTraitExprClass: { 15268 1.1 joerg const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E); 15269 1.1 joerg if ((Exp->getKind() == UETT_SizeOf) && 15270 1.1 joerg Exp->getTypeOfArgument()->isVariableArrayType()) 15271 1.1 joerg return ICEDiag(IK_NotICE, E->getBeginLoc()); 15272 1.1 joerg return NoDiag(); 15273 1.1 joerg } 15274 1.1 joerg case Expr::BinaryOperatorClass: { 15275 1.1 joerg const BinaryOperator *Exp = cast<BinaryOperator>(E); 15276 1.1 joerg switch (Exp->getOpcode()) { 15277 1.1 joerg case BO_PtrMemD: 15278 1.1 joerg case BO_PtrMemI: 15279 1.1 joerg case BO_Assign: 15280 1.1 joerg case BO_MulAssign: 15281 1.1 joerg case BO_DivAssign: 15282 1.1 joerg case BO_RemAssign: 15283 1.1 joerg case BO_AddAssign: 15284 1.1 joerg case BO_SubAssign: 15285 1.1 joerg case BO_ShlAssign: 15286 1.1 joerg case BO_ShrAssign: 15287 1.1 joerg case BO_AndAssign: 15288 1.1 joerg case BO_XorAssign: 15289 1.1 joerg case BO_OrAssign: 15290 1.1 joerg // C99 6.6/3 allows assignments within unevaluated subexpressions of 15291 1.1 joerg // constant expressions, but they can never be ICEs because an ICE cannot 15292 1.1 joerg // contain an lvalue operand. 15293 1.1 joerg return ICEDiag(IK_NotICE, E->getBeginLoc()); 15294 1.1 joerg 15295 1.1 joerg case BO_Mul: 15296 1.1 joerg case BO_Div: 15297 1.1 joerg case BO_Rem: 15298 1.1 joerg case BO_Add: 15299 1.1 joerg case BO_Sub: 15300 1.1 joerg case BO_Shl: 15301 1.1 joerg case BO_Shr: 15302 1.1 joerg case BO_LT: 15303 1.1 joerg case BO_GT: 15304 1.1 joerg case BO_LE: 15305 1.1 joerg case BO_GE: 15306 1.1 joerg case BO_EQ: 15307 1.1 joerg case BO_NE: 15308 1.1 joerg case BO_And: 15309 1.1 joerg case BO_Xor: 15310 1.1 joerg case BO_Or: 15311 1.1 joerg case BO_Comma: 15312 1.1 joerg case BO_Cmp: { 15313 1.1 joerg ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 15314 1.1 joerg ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 15315 1.1 joerg if (Exp->getOpcode() == BO_Div || 15316 1.1 joerg Exp->getOpcode() == BO_Rem) { 15317 1.1 joerg // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure 15318 1.1 joerg // we don't evaluate one. 15319 1.1 joerg if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) { 15320 1.1 joerg llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx); 15321 1.1 joerg if (REval == 0) 15322 1.1 joerg return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 15323 1.1 joerg if (REval.isSigned() && REval.isAllOnesValue()) { 15324 1.1 joerg llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx); 15325 1.1 joerg if (LEval.isMinSignedValue()) 15326 1.1 joerg return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 15327 1.1 joerg } 15328 1.1 joerg } 15329 1.1 joerg } 15330 1.1 joerg if (Exp->getOpcode() == BO_Comma) { 15331 1.1 joerg if (Ctx.getLangOpts().C99) { 15332 1.1 joerg // C99 6.6p3 introduces a strange edge case: comma can be in an ICE 15333 1.1 joerg // if it isn't evaluated. 15334 1.1 joerg if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) 15335 1.1 joerg return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 15336 1.1 joerg } else { 15337 1.1 joerg // In both C89 and C++, commas in ICEs are illegal. 15338 1.1 joerg return ICEDiag(IK_NotICE, E->getBeginLoc()); 15339 1.1 joerg } 15340 1.1 joerg } 15341 1.1 joerg return Worst(LHSResult, RHSResult); 15342 1.1 joerg } 15343 1.1 joerg case BO_LAnd: 15344 1.1 joerg case BO_LOr: { 15345 1.1 joerg ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 15346 1.1 joerg ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 15347 1.1 joerg if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) { 15348 1.1 joerg // Rare case where the RHS has a comma "side-effect"; we need 15349 1.1 joerg // to actually check the condition to see whether the side 15350 1.1 joerg // with the comma is evaluated. 15351 1.1 joerg if ((Exp->getOpcode() == BO_LAnd) != 15352 1.1 joerg (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0)) 15353 1.1 joerg return RHSResult; 15354 1.1 joerg return NoDiag(); 15355 1.1 joerg } 15356 1.1 joerg 15357 1.1 joerg return Worst(LHSResult, RHSResult); 15358 1.1 joerg } 15359 1.1 joerg } 15360 1.1 joerg llvm_unreachable("invalid binary operator kind"); 15361 1.1 joerg } 15362 1.1 joerg case Expr::ImplicitCastExprClass: 15363 1.1 joerg case Expr::CStyleCastExprClass: 15364 1.1 joerg case Expr::CXXFunctionalCastExprClass: 15365 1.1 joerg case Expr::CXXStaticCastExprClass: 15366 1.1 joerg case Expr::CXXReinterpretCastExprClass: 15367 1.1 joerg case Expr::CXXConstCastExprClass: 15368 1.1 joerg case Expr::ObjCBridgedCastExprClass: { 15369 1.1 joerg const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr(); 15370 1.1 joerg if (isa<ExplicitCastExpr>(E)) { 15371 1.1 joerg if (const FloatingLiteral *FL 15372 1.1 joerg = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) { 15373 1.1 joerg unsigned DestWidth = Ctx.getIntWidth(E->getType()); 15374 1.1 joerg bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType(); 15375 1.1 joerg APSInt IgnoredVal(DestWidth, !DestSigned); 15376 1.1 joerg bool Ignored; 15377 1.1 joerg // If the value does not fit in the destination type, the behavior is 15378 1.1 joerg // undefined, so we are not required to treat it as a constant 15379 1.1 joerg // expression. 15380 1.1 joerg if (FL->getValue().convertToInteger(IgnoredVal, 15381 1.1 joerg llvm::APFloat::rmTowardZero, 15382 1.1 joerg &Ignored) & APFloat::opInvalidOp) 15383 1.1 joerg return ICEDiag(IK_NotICE, E->getBeginLoc()); 15384 1.1 joerg return NoDiag(); 15385 1.1 joerg } 15386 1.1 joerg } 15387 1.1 joerg switch (cast<CastExpr>(E)->getCastKind()) { 15388 1.1 joerg case CK_LValueToRValue: 15389 1.1 joerg case CK_AtomicToNonAtomic: 15390 1.1 joerg case CK_NonAtomicToAtomic: 15391 1.1 joerg case CK_NoOp: 15392 1.1 joerg case CK_IntegralToBoolean: 15393 1.1 joerg case CK_IntegralCast: 15394 1.1 joerg return CheckICE(SubExpr, Ctx); 15395 1.1 joerg default: 15396 1.1 joerg return ICEDiag(IK_NotICE, E->getBeginLoc()); 15397 1.1 joerg } 15398 1.1 joerg } 15399 1.1 joerg case Expr::BinaryConditionalOperatorClass: { 15400 1.1 joerg const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E); 15401 1.1 joerg ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx); 15402 1.1 joerg if (CommonResult.Kind == IK_NotICE) return CommonResult; 15403 1.1 joerg ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 15404 1.1 joerg if (FalseResult.Kind == IK_NotICE) return FalseResult; 15405 1.1 joerg if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult; 15406 1.1 joerg if (FalseResult.Kind == IK_ICEIfUnevaluated && 15407 1.1 joerg Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag(); 15408 1.1 joerg return FalseResult; 15409 1.1 joerg } 15410 1.1 joerg case Expr::ConditionalOperatorClass: { 15411 1.1 joerg const ConditionalOperator *Exp = cast<ConditionalOperator>(E); 15412 1.1 joerg // If the condition (ignoring parens) is a __builtin_constant_p call, 15413 1.1 joerg // then only the true side is actually considered in an integer constant 15414 1.1 joerg // expression, and it is fully evaluated. This is an important GNU 15415 1.1 joerg // extension. See GCC PR38377 for discussion. 15416 1.1 joerg if (const CallExpr *CallCE 15417 1.1 joerg = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts())) 15418 1.1 joerg if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 15419 1.1 joerg return CheckEvalInICE(E, Ctx); 15420 1.1 joerg ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx); 15421 1.1 joerg if (CondResult.Kind == IK_NotICE) 15422 1.1 joerg return CondResult; 15423 1.1 joerg 15424 1.1 joerg ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx); 15425 1.1 joerg ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 15426 1.1 joerg 15427 1.1 joerg if (TrueResult.Kind == IK_NotICE) 15428 1.1 joerg return TrueResult; 15429 1.1 joerg if (FalseResult.Kind == IK_NotICE) 15430 1.1 joerg return FalseResult; 15431 1.1 joerg if (CondResult.Kind == IK_ICEIfUnevaluated) 15432 1.1 joerg return CondResult; 15433 1.1 joerg if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE) 15434 1.1 joerg return NoDiag(); 15435 1.1 joerg // Rare case where the diagnostics depend on which side is evaluated 15436 1.1 joerg // Note that if we get here, CondResult is 0, and at least one of 15437 1.1 joerg // TrueResult and FalseResult is non-zero. 15438 1.1 joerg if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) 15439 1.1 joerg return FalseResult; 15440 1.1 joerg return TrueResult; 15441 1.1 joerg } 15442 1.1 joerg case Expr::CXXDefaultArgExprClass: 15443 1.1 joerg return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx); 15444 1.1 joerg case Expr::CXXDefaultInitExprClass: 15445 1.1 joerg return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx); 15446 1.1 joerg case Expr::ChooseExprClass: { 15447 1.1 joerg return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx); 15448 1.1 joerg } 15449 1.1 joerg case Expr::BuiltinBitCastExprClass: { 15450 1.1 joerg if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E))) 15451 1.1 joerg return ICEDiag(IK_NotICE, E->getBeginLoc()); 15452 1.1 joerg return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx); 15453 1.1 joerg } 15454 1.1 joerg } 15455 1.1 joerg 15456 1.1 joerg llvm_unreachable("Invalid StmtClass!"); 15457 1.1 joerg } 15458 1.1 joerg 15459 1.1 joerg /// Evaluate an expression as a C++11 integral constant expression. 15460 1.1 joerg static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx, 15461 1.1 joerg const Expr *E, 15462 1.1 joerg llvm::APSInt *Value, 15463 1.1 joerg SourceLocation *Loc) { 15464 1.1 joerg if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 15465 1.1 joerg if (Loc) *Loc = E->getExprLoc(); 15466 1.1 joerg return false; 15467 1.1 joerg } 15468 1.1 joerg 15469 1.1 joerg APValue Result; 15470 1.1 joerg if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc)) 15471 1.1 joerg return false; 15472 1.1 joerg 15473 1.1 joerg if (!Result.isInt()) { 15474 1.1 joerg if (Loc) *Loc = E->getExprLoc(); 15475 1.1 joerg return false; 15476 1.1 joerg } 15477 1.1 joerg 15478 1.1 joerg if (Value) *Value = Result.getInt(); 15479 1.1 joerg return true; 15480 1.1 joerg } 15481 1.1 joerg 15482 1.1 joerg bool Expr::isIntegerConstantExpr(const ASTContext &Ctx, 15483 1.1 joerg SourceLocation *Loc) const { 15484 1.1 joerg assert(!isValueDependent() && 15485 1.1 joerg "Expression evaluator can't be called on a dependent expression."); 15486 1.1 joerg 15487 1.1 joerg if (Ctx.getLangOpts().CPlusPlus11) 15488 1.1 joerg return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc); 15489 1.1 joerg 15490 1.1 joerg ICEDiag D = CheckICE(this, Ctx); 15491 1.1 joerg if (D.Kind != IK_ICE) { 15492 1.1 joerg if (Loc) *Loc = D.Loc; 15493 1.1 joerg return false; 15494 1.1 joerg } 15495 1.1 joerg return true; 15496 1.1 joerg } 15497 1.1 joerg 15498 1.1.1.2 joerg Optional<llvm::APSInt> Expr::getIntegerConstantExpr(const ASTContext &Ctx, 15499 1.1.1.2 joerg SourceLocation *Loc, 15500 1.1.1.2 joerg bool isEvaluated) const { 15501 1.1 joerg assert(!isValueDependent() && 15502 1.1 joerg "Expression evaluator can't be called on a dependent expression."); 15503 1.1 joerg 15504 1.1.1.2 joerg APSInt Value; 15505 1.1.1.2 joerg 15506 1.1.1.2 joerg if (Ctx.getLangOpts().CPlusPlus11) { 15507 1.1.1.2 joerg if (EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc)) 15508 1.1.1.2 joerg return Value; 15509 1.1.1.2 joerg return None; 15510 1.1.1.2 joerg } 15511 1.1 joerg 15512 1.1 joerg if (!isIntegerConstantExpr(Ctx, Loc)) 15513 1.1.1.2 joerg return None; 15514 1.1 joerg 15515 1.1 joerg // The only possible side-effects here are due to UB discovered in the 15516 1.1 joerg // evaluation (for instance, INT_MAX + 1). In such a case, we are still 15517 1.1 joerg // required to treat the expression as an ICE, so we produce the folded 15518 1.1 joerg // value. 15519 1.1 joerg EvalResult ExprResult; 15520 1.1 joerg Expr::EvalStatus Status; 15521 1.1 joerg EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects); 15522 1.1 joerg Info.InConstantContext = true; 15523 1.1 joerg 15524 1.1 joerg if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info)) 15525 1.1 joerg llvm_unreachable("ICE cannot be evaluated!"); 15526 1.1 joerg 15527 1.1.1.2 joerg return ExprResult.Val.getInt(); 15528 1.1 joerg } 15529 1.1 joerg 15530 1.1 joerg bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const { 15531 1.1 joerg assert(!isValueDependent() && 15532 1.1 joerg "Expression evaluator can't be called on a dependent expression."); 15533 1.1 joerg 15534 1.1 joerg return CheckICE(this, Ctx).Kind == IK_ICE; 15535 1.1 joerg } 15536 1.1 joerg 15537 1.1 joerg bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result, 15538 1.1 joerg SourceLocation *Loc) const { 15539 1.1 joerg assert(!isValueDependent() && 15540 1.1 joerg "Expression evaluator can't be called on a dependent expression."); 15541 1.1 joerg 15542 1.1 joerg // We support this checking in C++98 mode in order to diagnose compatibility 15543 1.1 joerg // issues. 15544 1.1 joerg assert(Ctx.getLangOpts().CPlusPlus); 15545 1.1 joerg 15546 1.1 joerg // Build evaluation settings. 15547 1.1 joerg Expr::EvalStatus Status; 15548 1.1 joerg SmallVector<PartialDiagnosticAt, 8> Diags; 15549 1.1 joerg Status.Diag = &Diags; 15550 1.1 joerg EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); 15551 1.1 joerg 15552 1.1 joerg APValue Scratch; 15553 1.1 joerg bool IsConstExpr = 15554 1.1 joerg ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) && 15555 1.1 joerg // FIXME: We don't produce a diagnostic for this, but the callers that 15556 1.1 joerg // call us on arbitrary full-expressions should generally not care. 15557 1.1 joerg Info.discardCleanups() && !Status.HasSideEffects; 15558 1.1 joerg 15559 1.1 joerg if (!Diags.empty()) { 15560 1.1 joerg IsConstExpr = false; 15561 1.1 joerg if (Loc) *Loc = Diags[0].first; 15562 1.1 joerg } else if (!IsConstExpr) { 15563 1.1 joerg // FIXME: This shouldn't happen. 15564 1.1 joerg if (Loc) *Loc = getExprLoc(); 15565 1.1 joerg } 15566 1.1 joerg 15567 1.1 joerg return IsConstExpr; 15568 1.1 joerg } 15569 1.1 joerg 15570 1.1 joerg bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx, 15571 1.1 joerg const FunctionDecl *Callee, 15572 1.1 joerg ArrayRef<const Expr*> Args, 15573 1.1 joerg const Expr *This) const { 15574 1.1 joerg assert(!isValueDependent() && 15575 1.1 joerg "Expression evaluator can't be called on a dependent expression."); 15576 1.1 joerg 15577 1.1 joerg Expr::EvalStatus Status; 15578 1.1 joerg EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated); 15579 1.1 joerg Info.InConstantContext = true; 15580 1.1 joerg 15581 1.1 joerg LValue ThisVal; 15582 1.1 joerg const LValue *ThisPtr = nullptr; 15583 1.1 joerg if (This) { 15584 1.1 joerg #ifndef NDEBUG 15585 1.1 joerg auto *MD = dyn_cast<CXXMethodDecl>(Callee); 15586 1.1 joerg assert(MD && "Don't provide `this` for non-methods."); 15587 1.1 joerg assert(!MD->isStatic() && "Don't provide `this` for static methods."); 15588 1.1 joerg #endif 15589 1.1.1.2 joerg if (!This->isValueDependent() && 15590 1.1.1.2 joerg EvaluateObjectArgument(Info, This, ThisVal) && 15591 1.1.1.2 joerg !Info.EvalStatus.HasSideEffects) 15592 1.1 joerg ThisPtr = &ThisVal; 15593 1.1.1.2 joerg 15594 1.1.1.2 joerg // Ignore any side-effects from a failed evaluation. This is safe because 15595 1.1.1.2 joerg // they can't interfere with any other argument evaluation. 15596 1.1.1.2 joerg Info.EvalStatus.HasSideEffects = false; 15597 1.1 joerg } 15598 1.1 joerg 15599 1.1.1.2 joerg CallRef Call = Info.CurrentCall->createCall(Callee); 15600 1.1 joerg for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end(); 15601 1.1 joerg I != E; ++I) { 15602 1.1.1.2 joerg unsigned Idx = I - Args.begin(); 15603 1.1.1.2 joerg if (Idx >= Callee->getNumParams()) 15604 1.1.1.2 joerg break; 15605 1.1.1.2 joerg const ParmVarDecl *PVD = Callee->getParamDecl(Idx); 15606 1.1 joerg if ((*I)->isValueDependent() || 15607 1.1.1.2 joerg !EvaluateCallArg(PVD, *I, Call, Info) || 15608 1.1.1.2 joerg Info.EvalStatus.HasSideEffects) { 15609 1.1 joerg // If evaluation fails, throw away the argument entirely. 15610 1.1.1.2 joerg if (APValue *Slot = Info.getParamSlot(Call, PVD)) 15611 1.1.1.2 joerg *Slot = APValue(); 15612 1.1.1.2 joerg } 15613 1.1.1.2 joerg 15614 1.1.1.2 joerg // Ignore any side-effects from a failed evaluation. This is safe because 15615 1.1.1.2 joerg // they can't interfere with any other argument evaluation. 15616 1.1.1.2 joerg Info.EvalStatus.HasSideEffects = false; 15617 1.1 joerg } 15618 1.1 joerg 15619 1.1.1.2 joerg // Parameter cleanups happen in the caller and are not part of this 15620 1.1.1.2 joerg // evaluation. 15621 1.1.1.2 joerg Info.discardCleanups(); 15622 1.1.1.2 joerg Info.EvalStatus.HasSideEffects = false; 15623 1.1.1.2 joerg 15624 1.1 joerg // Build fake call to Callee. 15625 1.1.1.2 joerg CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, Call); 15626 1.1.1.2 joerg // FIXME: Missing ExprWithCleanups in enable_if conditions? 15627 1.1.1.2 joerg FullExpressionRAII Scope(Info); 15628 1.1.1.2 joerg return Evaluate(Value, Info, this) && Scope.destroy() && 15629 1.1 joerg !Info.EvalStatus.HasSideEffects; 15630 1.1 joerg } 15631 1.1 joerg 15632 1.1 joerg bool Expr::isPotentialConstantExpr(const FunctionDecl *FD, 15633 1.1 joerg SmallVectorImpl< 15634 1.1 joerg PartialDiagnosticAt> &Diags) { 15635 1.1 joerg // FIXME: It would be useful to check constexpr function templates, but at the 15636 1.1 joerg // moment the constant expression evaluator cannot cope with the non-rigorous 15637 1.1 joerg // ASTs which we build for dependent expressions. 15638 1.1 joerg if (FD->isDependentContext()) 15639 1.1 joerg return true; 15640 1.1 joerg 15641 1.1 joerg Expr::EvalStatus Status; 15642 1.1 joerg Status.Diag = &Diags; 15643 1.1 joerg 15644 1.1 joerg EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression); 15645 1.1 joerg Info.InConstantContext = true; 15646 1.1 joerg Info.CheckingPotentialConstantExpression = true; 15647 1.1 joerg 15648 1.1 joerg // The constexpr VM attempts to compile all methods to bytecode here. 15649 1.1 joerg if (Info.EnableNewConstInterp) { 15650 1.1.1.2 joerg Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD); 15651 1.1.1.2 joerg return Diags.empty(); 15652 1.1 joerg } 15653 1.1 joerg 15654 1.1 joerg const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 15655 1.1 joerg const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr; 15656 1.1 joerg 15657 1.1 joerg // Fabricate an arbitrary expression on the stack and pretend that it 15658 1.1 joerg // is a temporary being used as the 'this' pointer. 15659 1.1 joerg LValue This; 15660 1.1 joerg ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy); 15661 1.1 joerg This.set({&VIE, Info.CurrentCall->Index}); 15662 1.1 joerg 15663 1.1 joerg ArrayRef<const Expr*> Args; 15664 1.1 joerg 15665 1.1 joerg APValue Scratch; 15666 1.1 joerg if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) { 15667 1.1 joerg // Evaluate the call as a constant initializer, to allow the construction 15668 1.1 joerg // of objects of non-literal types. 15669 1.1 joerg Info.setEvaluatingDecl(This.getLValueBase(), Scratch); 15670 1.1 joerg HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch); 15671 1.1 joerg } else { 15672 1.1 joerg SourceLocation Loc = FD->getLocation(); 15673 1.1 joerg HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr, 15674 1.1.1.2 joerg Args, CallRef(), FD->getBody(), Info, Scratch, nullptr); 15675 1.1 joerg } 15676 1.1 joerg 15677 1.1 joerg return Diags.empty(); 15678 1.1 joerg } 15679 1.1 joerg 15680 1.1 joerg bool Expr::isPotentialConstantExprUnevaluated(Expr *E, 15681 1.1 joerg const FunctionDecl *FD, 15682 1.1 joerg SmallVectorImpl< 15683 1.1 joerg PartialDiagnosticAt> &Diags) { 15684 1.1 joerg assert(!E->isValueDependent() && 15685 1.1 joerg "Expression evaluator can't be called on a dependent expression."); 15686 1.1 joerg 15687 1.1 joerg Expr::EvalStatus Status; 15688 1.1 joerg Status.Diag = &Diags; 15689 1.1 joerg 15690 1.1 joerg EvalInfo Info(FD->getASTContext(), Status, 15691 1.1 joerg EvalInfo::EM_ConstantExpressionUnevaluated); 15692 1.1 joerg Info.InConstantContext = true; 15693 1.1 joerg Info.CheckingPotentialConstantExpression = true; 15694 1.1 joerg 15695 1.1 joerg // Fabricate a call stack frame to give the arguments a plausible cover story. 15696 1.1.1.2 joerg CallStackFrame Frame(Info, SourceLocation(), FD, /*This*/ nullptr, CallRef()); 15697 1.1 joerg 15698 1.1 joerg APValue ResultScratch; 15699 1.1 joerg Evaluate(ResultScratch, Info, E); 15700 1.1 joerg return Diags.empty(); 15701 1.1 joerg } 15702 1.1 joerg 15703 1.1 joerg bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx, 15704 1.1 joerg unsigned Type) const { 15705 1.1 joerg if (!getType()->isPointerType()) 15706 1.1 joerg return false; 15707 1.1 joerg 15708 1.1 joerg Expr::EvalStatus Status; 15709 1.1 joerg EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold); 15710 1.1 joerg return tryEvaluateBuiltinObjectSize(this, Type, Info, Result); 15711 1.1 joerg } 15712