1 //===--- CGExprConstant.cpp - Emit LLVM Code from Constant Expressions ----===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This contains code to emit Constant Expr nodes as LLVM code. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "ABIInfoImpl.h" 14 #include "CGCXXABI.h" 15 #include "CGObjCRuntime.h" 16 #include "CGRecordLayout.h" 17 #include "CodeGenFunction.h" 18 #include "CodeGenModule.h" 19 #include "ConstantEmitter.h" 20 #include "TargetInfo.h" 21 #include "clang/AST/APValue.h" 22 #include "clang/AST/ASTContext.h" 23 #include "clang/AST/Attr.h" 24 #include "clang/AST/RecordLayout.h" 25 #include "clang/AST/StmtVisitor.h" 26 #include "clang/Basic/Builtins.h" 27 #include "llvm/ADT/STLExtras.h" 28 #include "llvm/ADT/Sequence.h" 29 #include "llvm/Analysis/ConstantFolding.h" 30 #include "llvm/IR/Constants.h" 31 #include "llvm/IR/DataLayout.h" 32 #include "llvm/IR/Function.h" 33 #include "llvm/IR/GlobalVariable.h" 34 #include <optional> 35 using namespace clang; 36 using namespace CodeGen; 37 38 //===----------------------------------------------------------------------===// 39 // ConstantAggregateBuilder 40 //===----------------------------------------------------------------------===// 41 42 namespace { 43 class ConstExprEmitter; 44 45 llvm::Constant *getPadding(const CodeGenModule &CGM, CharUnits PadSize) { 46 llvm::Type *Ty = CGM.CharTy; 47 if (PadSize > CharUnits::One()) 48 Ty = llvm::ArrayType::get(Ty, PadSize.getQuantity()); 49 if (CGM.shouldZeroInitPadding()) { 50 return llvm::Constant::getNullValue(Ty); 51 } 52 return llvm::UndefValue::get(Ty); 53 } 54 55 struct ConstantAggregateBuilderUtils { 56 CodeGenModule &CGM; 57 58 ConstantAggregateBuilderUtils(CodeGenModule &CGM) : CGM(CGM) {} 59 60 CharUnits getAlignment(const llvm::Constant *C) const { 61 return CharUnits::fromQuantity( 62 CGM.getDataLayout().getABITypeAlign(C->getType())); 63 } 64 65 CharUnits getSize(llvm::Type *Ty) const { 66 return CharUnits::fromQuantity(CGM.getDataLayout().getTypeAllocSize(Ty)); 67 } 68 69 CharUnits getSize(const llvm::Constant *C) const { 70 return getSize(C->getType()); 71 } 72 73 llvm::Constant *getPadding(CharUnits PadSize) const { 74 return ::getPadding(CGM, PadSize); 75 } 76 77 llvm::Constant *getZeroes(CharUnits ZeroSize) const { 78 llvm::Type *Ty = llvm::ArrayType::get(CGM.CharTy, ZeroSize.getQuantity()); 79 return llvm::ConstantAggregateZero::get(Ty); 80 } 81 }; 82 83 /// Incremental builder for an llvm::Constant* holding a struct or array 84 /// constant. 85 class ConstantAggregateBuilder : private ConstantAggregateBuilderUtils { 86 /// The elements of the constant. These two arrays must have the same size; 87 /// Offsets[i] describes the offset of Elems[i] within the constant. The 88 /// elements are kept in increasing offset order, and we ensure that there 89 /// is no overlap: Offsets[i+1] >= Offsets[i] + getSize(Elemes[i]). 90 /// 91 /// This may contain explicit padding elements (in order to create a 92 /// natural layout), but need not. Gaps between elements are implicitly 93 /// considered to be filled with undef. 94 llvm::SmallVector<llvm::Constant*, 32> Elems; 95 llvm::SmallVector<CharUnits, 32> Offsets; 96 97 /// The size of the constant (the maximum end offset of any added element). 98 /// May be larger than the end of Elems.back() if we split the last element 99 /// and removed some trailing undefs. 100 CharUnits Size = CharUnits::Zero(); 101 102 /// This is true only if laying out Elems in order as the elements of a 103 /// non-packed LLVM struct will give the correct layout. 104 bool NaturalLayout = true; 105 106 bool split(size_t Index, CharUnits Hint); 107 std::optional<size_t> splitAt(CharUnits Pos); 108 109 static llvm::Constant *buildFrom(CodeGenModule &CGM, 110 ArrayRef<llvm::Constant *> Elems, 111 ArrayRef<CharUnits> Offsets, 112 CharUnits StartOffset, CharUnits Size, 113 bool NaturalLayout, llvm::Type *DesiredTy, 114 bool AllowOversized); 115 116 public: 117 ConstantAggregateBuilder(CodeGenModule &CGM) 118 : ConstantAggregateBuilderUtils(CGM) {} 119 120 /// Update or overwrite the value starting at \p Offset with \c C. 121 /// 122 /// \param AllowOverwrite If \c true, this constant might overwrite (part of) 123 /// a constant that has already been added. This flag is only used to 124 /// detect bugs. 125 bool add(llvm::Constant *C, CharUnits Offset, bool AllowOverwrite); 126 127 /// Update or overwrite the bits starting at \p OffsetInBits with \p Bits. 128 bool addBits(llvm::APInt Bits, uint64_t OffsetInBits, bool AllowOverwrite); 129 130 /// Attempt to condense the value starting at \p Offset to a constant of type 131 /// \p DesiredTy. 132 void condense(CharUnits Offset, llvm::Type *DesiredTy); 133 134 /// Produce a constant representing the entire accumulated value, ideally of 135 /// the specified type. If \p AllowOversized, the constant might be larger 136 /// than implied by \p DesiredTy (eg, if there is a flexible array member). 137 /// Otherwise, the constant will be of exactly the same size as \p DesiredTy 138 /// even if we can't represent it as that type. 139 llvm::Constant *build(llvm::Type *DesiredTy, bool AllowOversized) const { 140 return buildFrom(CGM, Elems, Offsets, CharUnits::Zero(), Size, 141 NaturalLayout, DesiredTy, AllowOversized); 142 } 143 }; 144 145 template<typename Container, typename Range = std::initializer_list< 146 typename Container::value_type>> 147 static void replace(Container &C, size_t BeginOff, size_t EndOff, Range Vals) { 148 assert(BeginOff <= EndOff && "invalid replacement range"); 149 llvm::replace(C, C.begin() + BeginOff, C.begin() + EndOff, Vals); 150 } 151 152 bool ConstantAggregateBuilder::add(llvm::Constant *C, CharUnits Offset, 153 bool AllowOverwrite) { 154 // Common case: appending to a layout. 155 if (Offset >= Size) { 156 CharUnits Align = getAlignment(C); 157 CharUnits AlignedSize = Size.alignTo(Align); 158 if (AlignedSize > Offset || Offset.alignTo(Align) != Offset) 159 NaturalLayout = false; 160 else if (AlignedSize < Offset) { 161 Elems.push_back(getPadding(Offset - Size)); 162 Offsets.push_back(Size); 163 } 164 Elems.push_back(C); 165 Offsets.push_back(Offset); 166 Size = Offset + getSize(C); 167 return true; 168 } 169 170 // Uncommon case: constant overlaps what we've already created. 171 std::optional<size_t> FirstElemToReplace = splitAt(Offset); 172 if (!FirstElemToReplace) 173 return false; 174 175 CharUnits CSize = getSize(C); 176 std::optional<size_t> LastElemToReplace = splitAt(Offset + CSize); 177 if (!LastElemToReplace) 178 return false; 179 180 assert((FirstElemToReplace == LastElemToReplace || AllowOverwrite) && 181 "unexpectedly overwriting field"); 182 183 replace(Elems, *FirstElemToReplace, *LastElemToReplace, {C}); 184 replace(Offsets, *FirstElemToReplace, *LastElemToReplace, {Offset}); 185 Size = std::max(Size, Offset + CSize); 186 NaturalLayout = false; 187 return true; 188 } 189 190 bool ConstantAggregateBuilder::addBits(llvm::APInt Bits, uint64_t OffsetInBits, 191 bool AllowOverwrite) { 192 const ASTContext &Context = CGM.getContext(); 193 const uint64_t CharWidth = CGM.getContext().getCharWidth(); 194 195 // Offset of where we want the first bit to go within the bits of the 196 // current char. 197 unsigned OffsetWithinChar = OffsetInBits % CharWidth; 198 199 // We split bit-fields up into individual bytes. Walk over the bytes and 200 // update them. 201 for (CharUnits OffsetInChars = 202 Context.toCharUnitsFromBits(OffsetInBits - OffsetWithinChar); 203 /**/; ++OffsetInChars) { 204 // Number of bits we want to fill in this char. 205 unsigned WantedBits = 206 std::min((uint64_t)Bits.getBitWidth(), CharWidth - OffsetWithinChar); 207 208 // Get a char containing the bits we want in the right places. The other 209 // bits have unspecified values. 210 llvm::APInt BitsThisChar = Bits; 211 if (BitsThisChar.getBitWidth() < CharWidth) 212 BitsThisChar = BitsThisChar.zext(CharWidth); 213 if (CGM.getDataLayout().isBigEndian()) { 214 // Figure out how much to shift by. We may need to left-shift if we have 215 // less than one byte of Bits left. 216 int Shift = Bits.getBitWidth() - CharWidth + OffsetWithinChar; 217 if (Shift > 0) 218 BitsThisChar.lshrInPlace(Shift); 219 else if (Shift < 0) 220 BitsThisChar = BitsThisChar.shl(-Shift); 221 } else { 222 BitsThisChar = BitsThisChar.shl(OffsetWithinChar); 223 } 224 if (BitsThisChar.getBitWidth() > CharWidth) 225 BitsThisChar = BitsThisChar.trunc(CharWidth); 226 227 if (WantedBits == CharWidth) { 228 // Got a full byte: just add it directly. 229 add(llvm::ConstantInt::get(CGM.getLLVMContext(), BitsThisChar), 230 OffsetInChars, AllowOverwrite); 231 } else { 232 // Partial byte: update the existing integer if there is one. If we 233 // can't split out a 1-CharUnit range to update, then we can't add 234 // these bits and fail the entire constant emission. 235 std::optional<size_t> FirstElemToUpdate = splitAt(OffsetInChars); 236 if (!FirstElemToUpdate) 237 return false; 238 std::optional<size_t> LastElemToUpdate = 239 splitAt(OffsetInChars + CharUnits::One()); 240 if (!LastElemToUpdate) 241 return false; 242 assert(*LastElemToUpdate - *FirstElemToUpdate < 2 && 243 "should have at most one element covering one byte"); 244 245 // Figure out which bits we want and discard the rest. 246 llvm::APInt UpdateMask(CharWidth, 0); 247 if (CGM.getDataLayout().isBigEndian()) 248 UpdateMask.setBits(CharWidth - OffsetWithinChar - WantedBits, 249 CharWidth - OffsetWithinChar); 250 else 251 UpdateMask.setBits(OffsetWithinChar, OffsetWithinChar + WantedBits); 252 BitsThisChar &= UpdateMask; 253 254 if (*FirstElemToUpdate == *LastElemToUpdate || 255 Elems[*FirstElemToUpdate]->isNullValue() || 256 isa<llvm::UndefValue>(Elems[*FirstElemToUpdate])) { 257 // All existing bits are either zero or undef. 258 add(llvm::ConstantInt::get(CGM.getLLVMContext(), BitsThisChar), 259 OffsetInChars, /*AllowOverwrite*/ true); 260 } else { 261 llvm::Constant *&ToUpdate = Elems[*FirstElemToUpdate]; 262 // In order to perform a partial update, we need the existing bitwise 263 // value, which we can only extract for a constant int. 264 auto *CI = dyn_cast<llvm::ConstantInt>(ToUpdate); 265 if (!CI) 266 return false; 267 // Because this is a 1-CharUnit range, the constant occupying it must 268 // be exactly one CharUnit wide. 269 assert(CI->getBitWidth() == CharWidth && "splitAt failed"); 270 assert((!(CI->getValue() & UpdateMask) || AllowOverwrite) && 271 "unexpectedly overwriting bitfield"); 272 BitsThisChar |= (CI->getValue() & ~UpdateMask); 273 ToUpdate = llvm::ConstantInt::get(CGM.getLLVMContext(), BitsThisChar); 274 } 275 } 276 277 // Stop if we've added all the bits. 278 if (WantedBits == Bits.getBitWidth()) 279 break; 280 281 // Remove the consumed bits from Bits. 282 if (!CGM.getDataLayout().isBigEndian()) 283 Bits.lshrInPlace(WantedBits); 284 Bits = Bits.trunc(Bits.getBitWidth() - WantedBits); 285 286 // The remanining bits go at the start of the following bytes. 287 OffsetWithinChar = 0; 288 } 289 290 return true; 291 } 292 293 /// Returns a position within Elems and Offsets such that all elements 294 /// before the returned index end before Pos and all elements at or after 295 /// the returned index begin at or after Pos. Splits elements as necessary 296 /// to ensure this. Returns std::nullopt if we find something we can't split. 297 std::optional<size_t> ConstantAggregateBuilder::splitAt(CharUnits Pos) { 298 if (Pos >= Size) 299 return Offsets.size(); 300 301 while (true) { 302 auto FirstAfterPos = llvm::upper_bound(Offsets, Pos); 303 if (FirstAfterPos == Offsets.begin()) 304 return 0; 305 306 // If we already have an element starting at Pos, we're done. 307 size_t LastAtOrBeforePosIndex = FirstAfterPos - Offsets.begin() - 1; 308 if (Offsets[LastAtOrBeforePosIndex] == Pos) 309 return LastAtOrBeforePosIndex; 310 311 // We found an element starting before Pos. Check for overlap. 312 if (Offsets[LastAtOrBeforePosIndex] + 313 getSize(Elems[LastAtOrBeforePosIndex]) <= Pos) 314 return LastAtOrBeforePosIndex + 1; 315 316 // Try to decompose it into smaller constants. 317 if (!split(LastAtOrBeforePosIndex, Pos)) 318 return std::nullopt; 319 } 320 } 321 322 /// Split the constant at index Index, if possible. Return true if we did. 323 /// Hint indicates the location at which we'd like to split, but may be 324 /// ignored. 325 bool ConstantAggregateBuilder::split(size_t Index, CharUnits Hint) { 326 NaturalLayout = false; 327 llvm::Constant *C = Elems[Index]; 328 CharUnits Offset = Offsets[Index]; 329 330 if (auto *CA = dyn_cast<llvm::ConstantAggregate>(C)) { 331 // Expand the sequence into its contained elements. 332 // FIXME: This assumes vector elements are byte-sized. 333 replace(Elems, Index, Index + 1, 334 llvm::map_range(llvm::seq(0u, CA->getNumOperands()), 335 [&](unsigned Op) { return CA->getOperand(Op); })); 336 if (isa<llvm::ArrayType>(CA->getType()) || 337 isa<llvm::VectorType>(CA->getType())) { 338 // Array or vector. 339 llvm::Type *ElemTy = 340 llvm::GetElementPtrInst::getTypeAtIndex(CA->getType(), (uint64_t)0); 341 CharUnits ElemSize = getSize(ElemTy); 342 replace( 343 Offsets, Index, Index + 1, 344 llvm::map_range(llvm::seq(0u, CA->getNumOperands()), 345 [&](unsigned Op) { return Offset + Op * ElemSize; })); 346 } else { 347 // Must be a struct. 348 auto *ST = cast<llvm::StructType>(CA->getType()); 349 const llvm::StructLayout *Layout = 350 CGM.getDataLayout().getStructLayout(ST); 351 replace(Offsets, Index, Index + 1, 352 llvm::map_range( 353 llvm::seq(0u, CA->getNumOperands()), [&](unsigned Op) { 354 return Offset + CharUnits::fromQuantity( 355 Layout->getElementOffset(Op)); 356 })); 357 } 358 return true; 359 } 360 361 if (auto *CDS = dyn_cast<llvm::ConstantDataSequential>(C)) { 362 // Expand the sequence into its contained elements. 363 // FIXME: This assumes vector elements are byte-sized. 364 // FIXME: If possible, split into two ConstantDataSequentials at Hint. 365 CharUnits ElemSize = getSize(CDS->getElementType()); 366 replace(Elems, Index, Index + 1, 367 llvm::map_range(llvm::seq(uint64_t(0u), CDS->getNumElements()), 368 [&](uint64_t Elem) { 369 return CDS->getElementAsConstant(Elem); 370 })); 371 replace(Offsets, Index, Index + 1, 372 llvm::map_range( 373 llvm::seq(uint64_t(0u), CDS->getNumElements()), 374 [&](uint64_t Elem) { return Offset + Elem * ElemSize; })); 375 return true; 376 } 377 378 if (isa<llvm::ConstantAggregateZero>(C)) { 379 // Split into two zeros at the hinted offset. 380 CharUnits ElemSize = getSize(C); 381 assert(Hint > Offset && Hint < Offset + ElemSize && "nothing to split"); 382 replace(Elems, Index, Index + 1, 383 {getZeroes(Hint - Offset), getZeroes(Offset + ElemSize - Hint)}); 384 replace(Offsets, Index, Index + 1, {Offset, Hint}); 385 return true; 386 } 387 388 if (isa<llvm::UndefValue>(C)) { 389 // Drop undef; it doesn't contribute to the final layout. 390 replace(Elems, Index, Index + 1, {}); 391 replace(Offsets, Index, Index + 1, {}); 392 return true; 393 } 394 395 // FIXME: We could split a ConstantInt if the need ever arose. 396 // We don't need to do this to handle bit-fields because we always eagerly 397 // split them into 1-byte chunks. 398 399 return false; 400 } 401 402 static llvm::Constant * 403 EmitArrayConstant(CodeGenModule &CGM, llvm::ArrayType *DesiredType, 404 llvm::Type *CommonElementType, uint64_t ArrayBound, 405 SmallVectorImpl<llvm::Constant *> &Elements, 406 llvm::Constant *Filler); 407 408 llvm::Constant *ConstantAggregateBuilder::buildFrom( 409 CodeGenModule &CGM, ArrayRef<llvm::Constant *> Elems, 410 ArrayRef<CharUnits> Offsets, CharUnits StartOffset, CharUnits Size, 411 bool NaturalLayout, llvm::Type *DesiredTy, bool AllowOversized) { 412 ConstantAggregateBuilderUtils Utils(CGM); 413 414 if (Elems.empty()) 415 return llvm::UndefValue::get(DesiredTy); 416 417 auto Offset = [&](size_t I) { return Offsets[I] - StartOffset; }; 418 419 // If we want an array type, see if all the elements are the same type and 420 // appropriately spaced. 421 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(DesiredTy)) { 422 assert(!AllowOversized && "oversized array emission not supported"); 423 424 bool CanEmitArray = true; 425 llvm::Type *CommonType = Elems[0]->getType(); 426 llvm::Constant *Filler = llvm::Constant::getNullValue(CommonType); 427 CharUnits ElemSize = Utils.getSize(ATy->getElementType()); 428 SmallVector<llvm::Constant*, 32> ArrayElements; 429 for (size_t I = 0; I != Elems.size(); ++I) { 430 // Skip zeroes; we'll use a zero value as our array filler. 431 if (Elems[I]->isNullValue()) 432 continue; 433 434 // All remaining elements must be the same type. 435 if (Elems[I]->getType() != CommonType || 436 Offset(I) % ElemSize != 0) { 437 CanEmitArray = false; 438 break; 439 } 440 ArrayElements.resize(Offset(I) / ElemSize + 1, Filler); 441 ArrayElements.back() = Elems[I]; 442 } 443 444 if (CanEmitArray) { 445 return EmitArrayConstant(CGM, ATy, CommonType, ATy->getNumElements(), 446 ArrayElements, Filler); 447 } 448 449 // Can't emit as an array, carry on to emit as a struct. 450 } 451 452 // The size of the constant we plan to generate. This is usually just 453 // the size of the initialized type, but in AllowOversized mode (i.e. 454 // flexible array init), it can be larger. 455 CharUnits DesiredSize = Utils.getSize(DesiredTy); 456 if (Size > DesiredSize) { 457 assert(AllowOversized && "Elems are oversized"); 458 DesiredSize = Size; 459 } 460 461 // The natural alignment of an unpacked LLVM struct with the given elements. 462 CharUnits Align = CharUnits::One(); 463 for (llvm::Constant *C : Elems) 464 Align = std::max(Align, Utils.getAlignment(C)); 465 466 // The natural size of an unpacked LLVM struct with the given elements. 467 CharUnits AlignedSize = Size.alignTo(Align); 468 469 bool Packed = false; 470 ArrayRef<llvm::Constant*> UnpackedElems = Elems; 471 llvm::SmallVector<llvm::Constant*, 32> UnpackedElemStorage; 472 if (DesiredSize < AlignedSize || DesiredSize.alignTo(Align) != DesiredSize) { 473 // The natural layout would be too big; force use of a packed layout. 474 NaturalLayout = false; 475 Packed = true; 476 } else if (DesiredSize > AlignedSize) { 477 // The natural layout would be too small. Add padding to fix it. (This 478 // is ignored if we choose a packed layout.) 479 UnpackedElemStorage.assign(Elems.begin(), Elems.end()); 480 UnpackedElemStorage.push_back(Utils.getPadding(DesiredSize - Size)); 481 UnpackedElems = UnpackedElemStorage; 482 } 483 484 // If we don't have a natural layout, insert padding as necessary. 485 // As we go, double-check to see if we can actually just emit Elems 486 // as a non-packed struct and do so opportunistically if possible. 487 llvm::SmallVector<llvm::Constant*, 32> PackedElems; 488 if (!NaturalLayout) { 489 CharUnits SizeSoFar = CharUnits::Zero(); 490 for (size_t I = 0; I != Elems.size(); ++I) { 491 CharUnits Align = Utils.getAlignment(Elems[I]); 492 CharUnits NaturalOffset = SizeSoFar.alignTo(Align); 493 CharUnits DesiredOffset = Offset(I); 494 assert(DesiredOffset >= SizeSoFar && "elements out of order"); 495 496 if (DesiredOffset != NaturalOffset) 497 Packed = true; 498 if (DesiredOffset != SizeSoFar) 499 PackedElems.push_back(Utils.getPadding(DesiredOffset - SizeSoFar)); 500 PackedElems.push_back(Elems[I]); 501 SizeSoFar = DesiredOffset + Utils.getSize(Elems[I]); 502 } 503 // If we're using the packed layout, pad it out to the desired size if 504 // necessary. 505 if (Packed) { 506 assert(SizeSoFar <= DesiredSize && 507 "requested size is too small for contents"); 508 if (SizeSoFar < DesiredSize) 509 PackedElems.push_back(Utils.getPadding(DesiredSize - SizeSoFar)); 510 } 511 } 512 513 llvm::StructType *STy = llvm::ConstantStruct::getTypeForElements( 514 CGM.getLLVMContext(), Packed ? PackedElems : UnpackedElems, Packed); 515 516 // Pick the type to use. If the type is layout identical to the desired 517 // type then use it, otherwise use whatever the builder produced for us. 518 if (llvm::StructType *DesiredSTy = dyn_cast<llvm::StructType>(DesiredTy)) { 519 if (DesiredSTy->isLayoutIdentical(STy)) 520 STy = DesiredSTy; 521 } 522 523 return llvm::ConstantStruct::get(STy, Packed ? PackedElems : UnpackedElems); 524 } 525 526 void ConstantAggregateBuilder::condense(CharUnits Offset, 527 llvm::Type *DesiredTy) { 528 CharUnits Size = getSize(DesiredTy); 529 530 std::optional<size_t> FirstElemToReplace = splitAt(Offset); 531 if (!FirstElemToReplace) 532 return; 533 size_t First = *FirstElemToReplace; 534 535 std::optional<size_t> LastElemToReplace = splitAt(Offset + Size); 536 if (!LastElemToReplace) 537 return; 538 size_t Last = *LastElemToReplace; 539 540 size_t Length = Last - First; 541 if (Length == 0) 542 return; 543 544 if (Length == 1 && Offsets[First] == Offset && 545 getSize(Elems[First]) == Size) { 546 // Re-wrap single element structs if necessary. Otherwise, leave any single 547 // element constant of the right size alone even if it has the wrong type. 548 auto *STy = dyn_cast<llvm::StructType>(DesiredTy); 549 if (STy && STy->getNumElements() == 1 && 550 STy->getElementType(0) == Elems[First]->getType()) 551 Elems[First] = llvm::ConstantStruct::get(STy, Elems[First]); 552 return; 553 } 554 555 llvm::Constant *Replacement = buildFrom( 556 CGM, ArrayRef(Elems).slice(First, Length), 557 ArrayRef(Offsets).slice(First, Length), Offset, getSize(DesiredTy), 558 /*known to have natural layout=*/false, DesiredTy, false); 559 replace(Elems, First, Last, {Replacement}); 560 replace(Offsets, First, Last, {Offset}); 561 } 562 563 //===----------------------------------------------------------------------===// 564 // ConstStructBuilder 565 //===----------------------------------------------------------------------===// 566 567 class ConstStructBuilder { 568 CodeGenModule &CGM; 569 ConstantEmitter &Emitter; 570 ConstantAggregateBuilder &Builder; 571 CharUnits StartOffset; 572 573 public: 574 static llvm::Constant *BuildStruct(ConstantEmitter &Emitter, 575 const InitListExpr *ILE, 576 QualType StructTy); 577 static llvm::Constant *BuildStruct(ConstantEmitter &Emitter, 578 const APValue &Value, QualType ValTy); 579 static bool UpdateStruct(ConstantEmitter &Emitter, 580 ConstantAggregateBuilder &Const, CharUnits Offset, 581 const InitListExpr *Updater); 582 583 private: 584 ConstStructBuilder(ConstantEmitter &Emitter, 585 ConstantAggregateBuilder &Builder, CharUnits StartOffset) 586 : CGM(Emitter.CGM), Emitter(Emitter), Builder(Builder), 587 StartOffset(StartOffset) {} 588 589 bool AppendField(const FieldDecl *Field, uint64_t FieldOffset, 590 llvm::Constant *InitExpr, bool AllowOverwrite = false); 591 592 bool AppendBytes(CharUnits FieldOffsetInChars, llvm::Constant *InitCst, 593 bool AllowOverwrite = false); 594 595 bool AppendBitField(const FieldDecl *Field, uint64_t FieldOffset, 596 llvm::Constant *InitExpr, bool AllowOverwrite = false); 597 598 bool Build(const InitListExpr *ILE, bool AllowOverwrite); 599 bool Build(const APValue &Val, const RecordDecl *RD, bool IsPrimaryBase, 600 const CXXRecordDecl *VTableClass, CharUnits BaseOffset); 601 bool DoZeroInitPadding(const ASTRecordLayout &Layout, unsigned FieldNo, 602 const FieldDecl &Field, bool AllowOverwrite, 603 CharUnits &SizeSoFar, bool &ZeroFieldSize); 604 bool DoZeroInitPadding(const ASTRecordLayout &Layout, bool AllowOverwrite, 605 CharUnits SizeSoFar); 606 llvm::Constant *Finalize(QualType Ty); 607 }; 608 609 bool ConstStructBuilder::AppendField( 610 const FieldDecl *Field, uint64_t FieldOffset, llvm::Constant *InitCst, 611 bool AllowOverwrite) { 612 const ASTContext &Context = CGM.getContext(); 613 614 CharUnits FieldOffsetInChars = Context.toCharUnitsFromBits(FieldOffset); 615 616 return AppendBytes(FieldOffsetInChars, InitCst, AllowOverwrite); 617 } 618 619 bool ConstStructBuilder::AppendBytes(CharUnits FieldOffsetInChars, 620 llvm::Constant *InitCst, 621 bool AllowOverwrite) { 622 return Builder.add(InitCst, StartOffset + FieldOffsetInChars, AllowOverwrite); 623 } 624 625 bool ConstStructBuilder::AppendBitField(const FieldDecl *Field, 626 uint64_t FieldOffset, llvm::Constant *C, 627 bool AllowOverwrite) { 628 629 llvm::ConstantInt *CI = dyn_cast<llvm::ConstantInt>(C); 630 if (!CI) { 631 // Constants for long _BitInt types are sometimes split into individual 632 // bytes. Try to fold these back into an integer constant. If that doesn't 633 // work out, then we are trying to initialize a bitfield with a non-trivial 634 // constant, this must require run-time code. 635 llvm::Type *LoadType = 636 CGM.getTypes().convertTypeForLoadStore(Field->getType(), C->getType()); 637 llvm::Constant *FoldedConstant = llvm::ConstantFoldLoadFromConst( 638 C, LoadType, llvm::APInt::getZero(32), CGM.getDataLayout()); 639 CI = dyn_cast_if_present<llvm::ConstantInt>(FoldedConstant); 640 if (!CI) 641 return false; 642 } 643 644 const CGRecordLayout &RL = 645 CGM.getTypes().getCGRecordLayout(Field->getParent()); 646 const CGBitFieldInfo &Info = RL.getBitFieldInfo(Field); 647 llvm::APInt FieldValue = CI->getValue(); 648 649 // Promote the size of FieldValue if necessary 650 // FIXME: This should never occur, but currently it can because initializer 651 // constants are cast to bool, and because clang is not enforcing bitfield 652 // width limits. 653 if (Info.Size > FieldValue.getBitWidth()) 654 FieldValue = FieldValue.zext(Info.Size); 655 656 // Truncate the size of FieldValue to the bit field size. 657 if (Info.Size < FieldValue.getBitWidth()) 658 FieldValue = FieldValue.trunc(Info.Size); 659 660 return Builder.addBits(FieldValue, 661 CGM.getContext().toBits(StartOffset) + FieldOffset, 662 AllowOverwrite); 663 } 664 665 static bool EmitDesignatedInitUpdater(ConstantEmitter &Emitter, 666 ConstantAggregateBuilder &Const, 667 CharUnits Offset, QualType Type, 668 const InitListExpr *Updater) { 669 if (Type->isRecordType()) 670 return ConstStructBuilder::UpdateStruct(Emitter, Const, Offset, Updater); 671 672 auto CAT = Emitter.CGM.getContext().getAsConstantArrayType(Type); 673 if (!CAT) 674 return false; 675 QualType ElemType = CAT->getElementType(); 676 CharUnits ElemSize = Emitter.CGM.getContext().getTypeSizeInChars(ElemType); 677 llvm::Type *ElemTy = Emitter.CGM.getTypes().ConvertTypeForMem(ElemType); 678 679 llvm::Constant *FillC = nullptr; 680 if (const Expr *Filler = Updater->getArrayFiller()) { 681 if (!isa<NoInitExpr>(Filler)) { 682 FillC = Emitter.tryEmitAbstractForMemory(Filler, ElemType); 683 if (!FillC) 684 return false; 685 } 686 } 687 688 unsigned NumElementsToUpdate = 689 FillC ? CAT->getZExtSize() : Updater->getNumInits(); 690 for (unsigned I = 0; I != NumElementsToUpdate; ++I, Offset += ElemSize) { 691 const Expr *Init = nullptr; 692 if (I < Updater->getNumInits()) 693 Init = Updater->getInit(I); 694 695 if (!Init && FillC) { 696 if (!Const.add(FillC, Offset, true)) 697 return false; 698 } else if (!Init || isa<NoInitExpr>(Init)) { 699 continue; 700 } else if (const auto *ChildILE = dyn_cast<InitListExpr>(Init)) { 701 if (!EmitDesignatedInitUpdater(Emitter, Const, Offset, ElemType, 702 ChildILE)) 703 return false; 704 // Attempt to reduce the array element to a single constant if necessary. 705 Const.condense(Offset, ElemTy); 706 } else { 707 llvm::Constant *Val = Emitter.tryEmitPrivateForMemory(Init, ElemType); 708 if (!Const.add(Val, Offset, true)) 709 return false; 710 } 711 } 712 713 return true; 714 } 715 716 bool ConstStructBuilder::Build(const InitListExpr *ILE, bool AllowOverwrite) { 717 RecordDecl *RD = ILE->getType()->castAs<RecordType>()->getDecl(); 718 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD); 719 720 unsigned FieldNo = -1; 721 unsigned ElementNo = 0; 722 723 // Bail out if we have base classes. We could support these, but they only 724 // arise in C++1z where we will have already constant folded most interesting 725 // cases. FIXME: There are still a few more cases we can handle this way. 726 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 727 if (CXXRD->getNumBases()) 728 return false; 729 730 const bool ZeroInitPadding = CGM.shouldZeroInitPadding(); 731 bool ZeroFieldSize = false; 732 CharUnits SizeSoFar = CharUnits::Zero(); 733 734 for (FieldDecl *Field : RD->fields()) { 735 ++FieldNo; 736 737 // If this is a union, skip all the fields that aren't being initialized. 738 if (RD->isUnion() && 739 !declaresSameEntity(ILE->getInitializedFieldInUnion(), Field)) 740 continue; 741 742 // Don't emit anonymous bitfields. 743 if (Field->isUnnamedBitField()) 744 continue; 745 746 // Get the initializer. A struct can include fields without initializers, 747 // we just use explicit null values for them. 748 const Expr *Init = nullptr; 749 if (ElementNo < ILE->getNumInits()) 750 Init = ILE->getInit(ElementNo++); 751 if (isa_and_nonnull<NoInitExpr>(Init)) { 752 if (ZeroInitPadding && 753 !DoZeroInitPadding(Layout, FieldNo, *Field, AllowOverwrite, SizeSoFar, 754 ZeroFieldSize)) 755 return false; 756 continue; 757 } 758 759 // Zero-sized fields are not emitted, but their initializers may still 760 // prevent emission of this struct as a constant. 761 if (isEmptyFieldForLayout(CGM.getContext(), Field)) { 762 if (Init && Init->HasSideEffects(CGM.getContext())) 763 return false; 764 continue; 765 } 766 767 if (ZeroInitPadding && 768 !DoZeroInitPadding(Layout, FieldNo, *Field, AllowOverwrite, SizeSoFar, 769 ZeroFieldSize)) 770 return false; 771 772 // When emitting a DesignatedInitUpdateExpr, a nested InitListExpr 773 // represents additional overwriting of our current constant value, and not 774 // a new constant to emit independently. 775 if (AllowOverwrite && 776 (Field->getType()->isArrayType() || Field->getType()->isRecordType())) { 777 if (auto *SubILE = dyn_cast<InitListExpr>(Init)) { 778 CharUnits Offset = CGM.getContext().toCharUnitsFromBits( 779 Layout.getFieldOffset(FieldNo)); 780 if (!EmitDesignatedInitUpdater(Emitter, Builder, StartOffset + Offset, 781 Field->getType(), SubILE)) 782 return false; 783 // If we split apart the field's value, try to collapse it down to a 784 // single value now. 785 Builder.condense(StartOffset + Offset, 786 CGM.getTypes().ConvertTypeForMem(Field->getType())); 787 continue; 788 } 789 } 790 791 llvm::Constant *EltInit = 792 Init ? Emitter.tryEmitPrivateForMemory(Init, Field->getType()) 793 : Emitter.emitNullForMemory(Field->getType()); 794 if (!EltInit) 795 return false; 796 797 if (ZeroInitPadding && ZeroFieldSize) 798 SizeSoFar += CharUnits::fromQuantity( 799 CGM.getDataLayout().getTypeAllocSize(EltInit->getType())); 800 801 if (!Field->isBitField()) { 802 // Handle non-bitfield members. 803 if (!AppendField(Field, Layout.getFieldOffset(FieldNo), EltInit, 804 AllowOverwrite)) 805 return false; 806 // After emitting a non-empty field with [[no_unique_address]], we may 807 // need to overwrite its tail padding. 808 if (Field->hasAttr<NoUniqueAddressAttr>()) 809 AllowOverwrite = true; 810 } else { 811 // Otherwise we have a bitfield. 812 if (!AppendBitField(Field, Layout.getFieldOffset(FieldNo), EltInit, 813 AllowOverwrite)) 814 return false; 815 } 816 } 817 818 if (ZeroInitPadding && !DoZeroInitPadding(Layout, AllowOverwrite, SizeSoFar)) 819 return false; 820 821 return true; 822 } 823 824 namespace { 825 struct BaseInfo { 826 BaseInfo(const CXXRecordDecl *Decl, CharUnits Offset, unsigned Index) 827 : Decl(Decl), Offset(Offset), Index(Index) { 828 } 829 830 const CXXRecordDecl *Decl; 831 CharUnits Offset; 832 unsigned Index; 833 834 bool operator<(const BaseInfo &O) const { return Offset < O.Offset; } 835 }; 836 } 837 838 bool ConstStructBuilder::Build(const APValue &Val, const RecordDecl *RD, 839 bool IsPrimaryBase, 840 const CXXRecordDecl *VTableClass, 841 CharUnits Offset) { 842 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD); 843 844 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) { 845 // Add a vtable pointer, if we need one and it hasn't already been added. 846 if (Layout.hasOwnVFPtr()) { 847 llvm::Constant *VTableAddressPoint = 848 CGM.getCXXABI().getVTableAddressPoint(BaseSubobject(CD, Offset), 849 VTableClass); 850 if (auto Authentication = CGM.getVTablePointerAuthentication(CD)) { 851 VTableAddressPoint = Emitter.tryEmitConstantSignedPointer( 852 VTableAddressPoint, *Authentication); 853 if (!VTableAddressPoint) 854 return false; 855 } 856 if (!AppendBytes(Offset, VTableAddressPoint)) 857 return false; 858 } 859 860 // Accumulate and sort bases, in order to visit them in address order, which 861 // may not be the same as declaration order. 862 SmallVector<BaseInfo, 8> Bases; 863 Bases.reserve(CD->getNumBases()); 864 unsigned BaseNo = 0; 865 for (CXXRecordDecl::base_class_const_iterator Base = CD->bases_begin(), 866 BaseEnd = CD->bases_end(); Base != BaseEnd; ++Base, ++BaseNo) { 867 assert(!Base->isVirtual() && "should not have virtual bases here"); 868 const CXXRecordDecl *BD = Base->getType()->getAsCXXRecordDecl(); 869 CharUnits BaseOffset = Layout.getBaseClassOffset(BD); 870 Bases.push_back(BaseInfo(BD, BaseOffset, BaseNo)); 871 } 872 llvm::stable_sort(Bases); 873 874 for (const BaseInfo &Base : Bases) { 875 bool IsPrimaryBase = Layout.getPrimaryBase() == Base.Decl; 876 Build(Val.getStructBase(Base.Index), Base.Decl, IsPrimaryBase, 877 VTableClass, Offset + Base.Offset); 878 } 879 } 880 881 unsigned FieldNo = 0; 882 uint64_t OffsetBits = CGM.getContext().toBits(Offset); 883 const bool ZeroInitPadding = CGM.shouldZeroInitPadding(); 884 bool ZeroFieldSize = false; 885 CharUnits SizeSoFar = CharUnits::Zero(); 886 887 bool AllowOverwrite = false; 888 for (RecordDecl::field_iterator Field = RD->field_begin(), 889 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field, ++FieldNo) { 890 // If this is a union, skip all the fields that aren't being initialized. 891 if (RD->isUnion() && !declaresSameEntity(Val.getUnionField(), *Field)) 892 continue; 893 894 // Don't emit anonymous bitfields or zero-sized fields. 895 if (Field->isUnnamedBitField() || 896 isEmptyFieldForLayout(CGM.getContext(), *Field)) 897 continue; 898 899 // Emit the value of the initializer. 900 const APValue &FieldValue = 901 RD->isUnion() ? Val.getUnionValue() : Val.getStructField(FieldNo); 902 llvm::Constant *EltInit = 903 Emitter.tryEmitPrivateForMemory(FieldValue, Field->getType()); 904 if (!EltInit) 905 return false; 906 907 if (ZeroInitPadding) { 908 if (!DoZeroInitPadding(Layout, FieldNo, **Field, AllowOverwrite, 909 SizeSoFar, ZeroFieldSize)) 910 return false; 911 if (ZeroFieldSize) 912 SizeSoFar += CharUnits::fromQuantity( 913 CGM.getDataLayout().getTypeAllocSize(EltInit->getType())); 914 } 915 916 if (!Field->isBitField()) { 917 // Handle non-bitfield members. 918 if (!AppendField(*Field, Layout.getFieldOffset(FieldNo) + OffsetBits, 919 EltInit, AllowOverwrite)) 920 return false; 921 // After emitting a non-empty field with [[no_unique_address]], we may 922 // need to overwrite its tail padding. 923 if (Field->hasAttr<NoUniqueAddressAttr>()) 924 AllowOverwrite = true; 925 } else { 926 // Otherwise we have a bitfield. 927 if (!AppendBitField(*Field, Layout.getFieldOffset(FieldNo) + OffsetBits, 928 EltInit, AllowOverwrite)) 929 return false; 930 } 931 } 932 if (ZeroInitPadding && !DoZeroInitPadding(Layout, AllowOverwrite, SizeSoFar)) 933 return false; 934 935 return true; 936 } 937 938 bool ConstStructBuilder::DoZeroInitPadding( 939 const ASTRecordLayout &Layout, unsigned FieldNo, const FieldDecl &Field, 940 bool AllowOverwrite, CharUnits &SizeSoFar, bool &ZeroFieldSize) { 941 uint64_t StartBitOffset = Layout.getFieldOffset(FieldNo); 942 CharUnits StartOffset = CGM.getContext().toCharUnitsFromBits(StartBitOffset); 943 if (SizeSoFar < StartOffset) 944 if (!AppendBytes(SizeSoFar, getPadding(CGM, StartOffset - SizeSoFar), 945 AllowOverwrite)) 946 return false; 947 948 if (!Field.isBitField()) { 949 CharUnits FieldSize = CGM.getContext().getTypeSizeInChars(Field.getType()); 950 SizeSoFar = StartOffset + FieldSize; 951 ZeroFieldSize = FieldSize.isZero(); 952 } else { 953 const CGRecordLayout &RL = 954 CGM.getTypes().getCGRecordLayout(Field.getParent()); 955 const CGBitFieldInfo &Info = RL.getBitFieldInfo(&Field); 956 uint64_t EndBitOffset = StartBitOffset + Info.Size; 957 SizeSoFar = CGM.getContext().toCharUnitsFromBits(EndBitOffset); 958 if (EndBitOffset % CGM.getContext().getCharWidth() != 0) { 959 SizeSoFar++; 960 } 961 ZeroFieldSize = Info.Size == 0; 962 } 963 return true; 964 } 965 966 bool ConstStructBuilder::DoZeroInitPadding(const ASTRecordLayout &Layout, 967 bool AllowOverwrite, 968 CharUnits SizeSoFar) { 969 CharUnits TotalSize = Layout.getSize(); 970 if (SizeSoFar < TotalSize) 971 if (!AppendBytes(SizeSoFar, getPadding(CGM, TotalSize - SizeSoFar), 972 AllowOverwrite)) 973 return false; 974 SizeSoFar = TotalSize; 975 return true; 976 } 977 978 llvm::Constant *ConstStructBuilder::Finalize(QualType Type) { 979 Type = Type.getNonReferenceType(); 980 RecordDecl *RD = Type->castAs<RecordType>()->getDecl(); 981 llvm::Type *ValTy = CGM.getTypes().ConvertType(Type); 982 return Builder.build(ValTy, RD->hasFlexibleArrayMember()); 983 } 984 985 llvm::Constant *ConstStructBuilder::BuildStruct(ConstantEmitter &Emitter, 986 const InitListExpr *ILE, 987 QualType ValTy) { 988 ConstantAggregateBuilder Const(Emitter.CGM); 989 ConstStructBuilder Builder(Emitter, Const, CharUnits::Zero()); 990 991 if (!Builder.Build(ILE, /*AllowOverwrite*/false)) 992 return nullptr; 993 994 return Builder.Finalize(ValTy); 995 } 996 997 llvm::Constant *ConstStructBuilder::BuildStruct(ConstantEmitter &Emitter, 998 const APValue &Val, 999 QualType ValTy) { 1000 ConstantAggregateBuilder Const(Emitter.CGM); 1001 ConstStructBuilder Builder(Emitter, Const, CharUnits::Zero()); 1002 1003 const RecordDecl *RD = ValTy->castAs<RecordType>()->getDecl(); 1004 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD); 1005 if (!Builder.Build(Val, RD, false, CD, CharUnits::Zero())) 1006 return nullptr; 1007 1008 return Builder.Finalize(ValTy); 1009 } 1010 1011 bool ConstStructBuilder::UpdateStruct(ConstantEmitter &Emitter, 1012 ConstantAggregateBuilder &Const, 1013 CharUnits Offset, 1014 const InitListExpr *Updater) { 1015 return ConstStructBuilder(Emitter, Const, Offset) 1016 .Build(Updater, /*AllowOverwrite*/ true); 1017 } 1018 1019 //===----------------------------------------------------------------------===// 1020 // ConstExprEmitter 1021 //===----------------------------------------------------------------------===// 1022 1023 static ConstantAddress 1024 tryEmitGlobalCompoundLiteral(ConstantEmitter &emitter, 1025 const CompoundLiteralExpr *E) { 1026 CodeGenModule &CGM = emitter.CGM; 1027 CharUnits Align = CGM.getContext().getTypeAlignInChars(E->getType()); 1028 if (llvm::GlobalVariable *Addr = 1029 CGM.getAddrOfConstantCompoundLiteralIfEmitted(E)) 1030 return ConstantAddress(Addr, Addr->getValueType(), Align); 1031 1032 LangAS addressSpace = E->getType().getAddressSpace(); 1033 llvm::Constant *C = emitter.tryEmitForInitializer(E->getInitializer(), 1034 addressSpace, E->getType()); 1035 if (!C) { 1036 assert(!E->isFileScope() && 1037 "file-scope compound literal did not have constant initializer!"); 1038 return ConstantAddress::invalid(); 1039 } 1040 1041 auto GV = new llvm::GlobalVariable( 1042 CGM.getModule(), C->getType(), 1043 E->getType().isConstantStorage(CGM.getContext(), true, false), 1044 llvm::GlobalValue::InternalLinkage, C, ".compoundliteral", nullptr, 1045 llvm::GlobalVariable::NotThreadLocal, 1046 CGM.getContext().getTargetAddressSpace(addressSpace)); 1047 emitter.finalize(GV); 1048 GV->setAlignment(Align.getAsAlign()); 1049 CGM.setAddrOfConstantCompoundLiteral(E, GV); 1050 return ConstantAddress(GV, GV->getValueType(), Align); 1051 } 1052 1053 static llvm::Constant * 1054 EmitArrayConstant(CodeGenModule &CGM, llvm::ArrayType *DesiredType, 1055 llvm::Type *CommonElementType, uint64_t ArrayBound, 1056 SmallVectorImpl<llvm::Constant *> &Elements, 1057 llvm::Constant *Filler) { 1058 // Figure out how long the initial prefix of non-zero elements is. 1059 uint64_t NonzeroLength = ArrayBound; 1060 if (Elements.size() < NonzeroLength && Filler->isNullValue()) 1061 NonzeroLength = Elements.size(); 1062 if (NonzeroLength == Elements.size()) { 1063 while (NonzeroLength > 0 && Elements[NonzeroLength - 1]->isNullValue()) 1064 --NonzeroLength; 1065 } 1066 1067 if (NonzeroLength == 0) 1068 return llvm::ConstantAggregateZero::get(DesiredType); 1069 1070 // Add a zeroinitializer array filler if we have lots of trailing zeroes. 1071 uint64_t TrailingZeroes = ArrayBound - NonzeroLength; 1072 if (TrailingZeroes >= 8) { 1073 assert(Elements.size() >= NonzeroLength && 1074 "missing initializer for non-zero element"); 1075 1076 // If all the elements had the same type up to the trailing zeroes, emit a 1077 // struct of two arrays (the nonzero data and the zeroinitializer). 1078 if (CommonElementType && NonzeroLength >= 8) { 1079 llvm::Constant *Initial = llvm::ConstantArray::get( 1080 llvm::ArrayType::get(CommonElementType, NonzeroLength), 1081 ArrayRef(Elements).take_front(NonzeroLength)); 1082 Elements.resize(2); 1083 Elements[0] = Initial; 1084 } else { 1085 Elements.resize(NonzeroLength + 1); 1086 } 1087 1088 auto *FillerType = 1089 CommonElementType ? CommonElementType : DesiredType->getElementType(); 1090 FillerType = llvm::ArrayType::get(FillerType, TrailingZeroes); 1091 Elements.back() = llvm::ConstantAggregateZero::get(FillerType); 1092 CommonElementType = nullptr; 1093 } else if (Elements.size() != ArrayBound) { 1094 // Otherwise pad to the right size with the filler if necessary. 1095 Elements.resize(ArrayBound, Filler); 1096 if (Filler->getType() != CommonElementType) 1097 CommonElementType = nullptr; 1098 } 1099 1100 // If all elements have the same type, just emit an array constant. 1101 if (CommonElementType) 1102 return llvm::ConstantArray::get( 1103 llvm::ArrayType::get(CommonElementType, ArrayBound), Elements); 1104 1105 // We have mixed types. Use a packed struct. 1106 llvm::SmallVector<llvm::Type *, 16> Types; 1107 Types.reserve(Elements.size()); 1108 for (llvm::Constant *Elt : Elements) 1109 Types.push_back(Elt->getType()); 1110 llvm::StructType *SType = 1111 llvm::StructType::get(CGM.getLLVMContext(), Types, true); 1112 return llvm::ConstantStruct::get(SType, Elements); 1113 } 1114 1115 // This class only needs to handle arrays, structs and unions. Outside C++11 1116 // mode, we don't currently constant fold those types. All other types are 1117 // handled by constant folding. 1118 // 1119 // Constant folding is currently missing support for a few features supported 1120 // here: CK_ToUnion, CK_ReinterpretMemberPointer, and DesignatedInitUpdateExpr. 1121 class ConstExprEmitter 1122 : public ConstStmtVisitor<ConstExprEmitter, llvm::Constant *, QualType> { 1123 CodeGenModule &CGM; 1124 ConstantEmitter &Emitter; 1125 llvm::LLVMContext &VMContext; 1126 public: 1127 ConstExprEmitter(ConstantEmitter &emitter) 1128 : CGM(emitter.CGM), Emitter(emitter), VMContext(CGM.getLLVMContext()) { 1129 } 1130 1131 //===--------------------------------------------------------------------===// 1132 // Visitor Methods 1133 //===--------------------------------------------------------------------===// 1134 1135 llvm::Constant *VisitStmt(const Stmt *S, QualType T) { return nullptr; } 1136 1137 llvm::Constant *VisitConstantExpr(const ConstantExpr *CE, QualType T) { 1138 if (llvm::Constant *Result = Emitter.tryEmitConstantExpr(CE)) 1139 return Result; 1140 return Visit(CE->getSubExpr(), T); 1141 } 1142 1143 llvm::Constant *VisitParenExpr(const ParenExpr *PE, QualType T) { 1144 return Visit(PE->getSubExpr(), T); 1145 } 1146 1147 llvm::Constant * 1148 VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *PE, 1149 QualType T) { 1150 return Visit(PE->getReplacement(), T); 1151 } 1152 1153 llvm::Constant *VisitGenericSelectionExpr(const GenericSelectionExpr *GE, 1154 QualType T) { 1155 return Visit(GE->getResultExpr(), T); 1156 } 1157 1158 llvm::Constant *VisitChooseExpr(const ChooseExpr *CE, QualType T) { 1159 return Visit(CE->getChosenSubExpr(), T); 1160 } 1161 1162 llvm::Constant *VisitCompoundLiteralExpr(const CompoundLiteralExpr *E, 1163 QualType T) { 1164 return Visit(E->getInitializer(), T); 1165 } 1166 1167 llvm::Constant *ProduceIntToIntCast(const Expr *E, QualType DestType) { 1168 QualType FromType = E->getType(); 1169 // See also HandleIntToIntCast in ExprConstant.cpp 1170 if (FromType->isIntegerType()) 1171 if (llvm::Constant *C = Visit(E, FromType)) 1172 if (auto *CI = dyn_cast<llvm::ConstantInt>(C)) { 1173 unsigned SrcWidth = CGM.getContext().getIntWidth(FromType); 1174 unsigned DstWidth = CGM.getContext().getIntWidth(DestType); 1175 if (DstWidth == SrcWidth) 1176 return CI; 1177 llvm::APInt A = FromType->isSignedIntegerType() 1178 ? CI->getValue().sextOrTrunc(DstWidth) 1179 : CI->getValue().zextOrTrunc(DstWidth); 1180 return llvm::ConstantInt::get(CGM.getLLVMContext(), A); 1181 } 1182 return nullptr; 1183 } 1184 1185 llvm::Constant *VisitCastExpr(const CastExpr *E, QualType destType) { 1186 if (const auto *ECE = dyn_cast<ExplicitCastExpr>(E)) 1187 CGM.EmitExplicitCastExprType(ECE, Emitter.CGF); 1188 const Expr *subExpr = E->getSubExpr(); 1189 1190 switch (E->getCastKind()) { 1191 case CK_ToUnion: { 1192 // GCC cast to union extension 1193 assert(E->getType()->isUnionType() && 1194 "Destination type is not union type!"); 1195 1196 auto field = E->getTargetUnionField(); 1197 1198 auto C = Emitter.tryEmitPrivateForMemory(subExpr, field->getType()); 1199 if (!C) return nullptr; 1200 1201 auto destTy = ConvertType(destType); 1202 if (C->getType() == destTy) return C; 1203 1204 // Build a struct with the union sub-element as the first member, 1205 // and padded to the appropriate size. 1206 SmallVector<llvm::Constant*, 2> Elts; 1207 SmallVector<llvm::Type*, 2> Types; 1208 Elts.push_back(C); 1209 Types.push_back(C->getType()); 1210 unsigned CurSize = CGM.getDataLayout().getTypeAllocSize(C->getType()); 1211 unsigned TotalSize = CGM.getDataLayout().getTypeAllocSize(destTy); 1212 1213 assert(CurSize <= TotalSize && "Union size mismatch!"); 1214 if (unsigned NumPadBytes = TotalSize - CurSize) { 1215 llvm::Constant *Padding = 1216 getPadding(CGM, CharUnits::fromQuantity(NumPadBytes)); 1217 Elts.push_back(Padding); 1218 Types.push_back(Padding->getType()); 1219 } 1220 1221 llvm::StructType *STy = llvm::StructType::get(VMContext, Types, false); 1222 return llvm::ConstantStruct::get(STy, Elts); 1223 } 1224 1225 case CK_AddressSpaceConversion: { 1226 auto C = Emitter.tryEmitPrivate(subExpr, subExpr->getType()); 1227 if (!C) 1228 return nullptr; 1229 LangAS srcAS = subExpr->getType()->getPointeeType().getAddressSpace(); 1230 llvm::Type *destTy = ConvertType(E->getType()); 1231 return CGM.getTargetCodeGenInfo().performAddrSpaceCast(CGM, C, srcAS, 1232 destTy); 1233 } 1234 1235 case CK_LValueToRValue: { 1236 // We don't really support doing lvalue-to-rvalue conversions here; any 1237 // interesting conversions should be done in Evaluate(). But as a 1238 // special case, allow compound literals to support the gcc extension 1239 // allowing "struct x {int x;} x = (struct x) {};". 1240 if (const auto *E = 1241 dyn_cast<CompoundLiteralExpr>(subExpr->IgnoreParens())) 1242 return Visit(E->getInitializer(), destType); 1243 return nullptr; 1244 } 1245 1246 case CK_AtomicToNonAtomic: 1247 case CK_NonAtomicToAtomic: 1248 case CK_NoOp: 1249 case CK_ConstructorConversion: 1250 return Visit(subExpr, destType); 1251 1252 case CK_ArrayToPointerDecay: 1253 if (const auto *S = dyn_cast<StringLiteral>(subExpr)) 1254 return CGM.GetAddrOfConstantStringFromLiteral(S).getPointer(); 1255 return nullptr; 1256 case CK_NullToPointer: 1257 if (Visit(subExpr, destType)) 1258 return CGM.EmitNullConstant(destType); 1259 return nullptr; 1260 1261 case CK_IntToOCLSampler: 1262 llvm_unreachable("global sampler variables are not generated"); 1263 1264 case CK_IntegralCast: 1265 return ProduceIntToIntCast(subExpr, destType); 1266 1267 case CK_Dependent: llvm_unreachable("saw dependent cast!"); 1268 1269 case CK_BuiltinFnToFnPtr: 1270 llvm_unreachable("builtin functions are handled elsewhere"); 1271 1272 case CK_ReinterpretMemberPointer: 1273 case CK_DerivedToBaseMemberPointer: 1274 case CK_BaseToDerivedMemberPointer: { 1275 auto C = Emitter.tryEmitPrivate(subExpr, subExpr->getType()); 1276 if (!C) return nullptr; 1277 return CGM.getCXXABI().EmitMemberPointerConversion(E, C); 1278 } 1279 1280 // These will never be supported. 1281 case CK_ObjCObjectLValueCast: 1282 case CK_ARCProduceObject: 1283 case CK_ARCConsumeObject: 1284 case CK_ARCReclaimReturnedObject: 1285 case CK_ARCExtendBlockObject: 1286 case CK_CopyAndAutoreleaseBlockObject: 1287 return nullptr; 1288 1289 // These don't need to be handled here because Evaluate knows how to 1290 // evaluate them in the cases where they can be folded. 1291 case CK_BitCast: 1292 case CK_ToVoid: 1293 case CK_Dynamic: 1294 case CK_LValueBitCast: 1295 case CK_LValueToRValueBitCast: 1296 case CK_NullToMemberPointer: 1297 case CK_UserDefinedConversion: 1298 case CK_CPointerToObjCPointerCast: 1299 case CK_BlockPointerToObjCPointerCast: 1300 case CK_AnyPointerToBlockPointerCast: 1301 case CK_FunctionToPointerDecay: 1302 case CK_BaseToDerived: 1303 case CK_DerivedToBase: 1304 case CK_UncheckedDerivedToBase: 1305 case CK_MemberPointerToBoolean: 1306 case CK_VectorSplat: 1307 case CK_FloatingRealToComplex: 1308 case CK_FloatingComplexToReal: 1309 case CK_FloatingComplexToBoolean: 1310 case CK_FloatingComplexCast: 1311 case CK_FloatingComplexToIntegralComplex: 1312 case CK_IntegralRealToComplex: 1313 case CK_IntegralComplexToReal: 1314 case CK_IntegralComplexToBoolean: 1315 case CK_IntegralComplexCast: 1316 case CK_IntegralComplexToFloatingComplex: 1317 case CK_PointerToIntegral: 1318 case CK_PointerToBoolean: 1319 case CK_BooleanToSignedIntegral: 1320 case CK_IntegralToPointer: 1321 case CK_IntegralToBoolean: 1322 case CK_IntegralToFloating: 1323 case CK_FloatingToIntegral: 1324 case CK_FloatingToBoolean: 1325 case CK_FloatingCast: 1326 case CK_FloatingToFixedPoint: 1327 case CK_FixedPointToFloating: 1328 case CK_FixedPointCast: 1329 case CK_FixedPointToBoolean: 1330 case CK_FixedPointToIntegral: 1331 case CK_IntegralToFixedPoint: 1332 case CK_ZeroToOCLOpaqueType: 1333 case CK_MatrixCast: 1334 case CK_HLSLVectorTruncation: 1335 case CK_HLSLArrayRValue: 1336 case CK_HLSLElementwiseCast: 1337 case CK_HLSLAggregateSplatCast: 1338 return nullptr; 1339 } 1340 llvm_unreachable("Invalid CastKind"); 1341 } 1342 1343 llvm::Constant *VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *DIE, 1344 QualType T) { 1345 // No need for a DefaultInitExprScope: we don't handle 'this' in a 1346 // constant expression. 1347 return Visit(DIE->getExpr(), T); 1348 } 1349 1350 llvm::Constant *VisitExprWithCleanups(const ExprWithCleanups *E, QualType T) { 1351 return Visit(E->getSubExpr(), T); 1352 } 1353 1354 llvm::Constant *VisitIntegerLiteral(const IntegerLiteral *I, QualType T) { 1355 return llvm::ConstantInt::get(CGM.getLLVMContext(), I->getValue()); 1356 } 1357 1358 static APValue withDestType(ASTContext &Ctx, const Expr *E, QualType SrcType, 1359 QualType DestType, const llvm::APSInt &Value) { 1360 if (!Ctx.hasSameType(SrcType, DestType)) { 1361 if (DestType->isFloatingType()) { 1362 llvm::APFloat Result = 1363 llvm::APFloat(Ctx.getFloatTypeSemantics(DestType), 1); 1364 llvm::RoundingMode RM = 1365 E->getFPFeaturesInEffect(Ctx.getLangOpts()).getRoundingMode(); 1366 if (RM == llvm::RoundingMode::Dynamic) 1367 RM = llvm::RoundingMode::NearestTiesToEven; 1368 Result.convertFromAPInt(Value, Value.isSigned(), RM); 1369 return APValue(Result); 1370 } 1371 } 1372 return APValue(Value); 1373 } 1374 1375 llvm::Constant *EmitArrayInitialization(const InitListExpr *ILE, QualType T) { 1376 auto *CAT = CGM.getContext().getAsConstantArrayType(ILE->getType()); 1377 assert(CAT && "can't emit array init for non-constant-bound array"); 1378 uint64_t NumInitElements = ILE->getNumInits(); 1379 const uint64_t NumElements = CAT->getZExtSize(); 1380 for (const auto *Init : ILE->inits()) { 1381 if (const auto *Embed = 1382 dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts())) { 1383 NumInitElements += Embed->getDataElementCount() - 1; 1384 if (NumInitElements > NumElements) { 1385 NumInitElements = NumElements; 1386 break; 1387 } 1388 } 1389 } 1390 1391 // Initialising an array requires us to automatically 1392 // initialise any elements that have not been initialised explicitly 1393 uint64_t NumInitableElts = std::min<uint64_t>(NumInitElements, NumElements); 1394 1395 QualType EltType = CAT->getElementType(); 1396 1397 // Initialize remaining array elements. 1398 llvm::Constant *fillC = nullptr; 1399 if (const Expr *filler = ILE->getArrayFiller()) { 1400 fillC = Emitter.tryEmitAbstractForMemory(filler, EltType); 1401 if (!fillC) 1402 return nullptr; 1403 } 1404 1405 // Copy initializer elements. 1406 SmallVector<llvm::Constant *, 16> Elts; 1407 if (fillC && fillC->isNullValue()) 1408 Elts.reserve(NumInitableElts + 1); 1409 else 1410 Elts.reserve(NumElements); 1411 1412 llvm::Type *CommonElementType = nullptr; 1413 auto Emit = [&](const Expr *Init, unsigned ArrayIndex) { 1414 llvm::Constant *C = nullptr; 1415 C = Emitter.tryEmitPrivateForMemory(Init, EltType); 1416 if (!C) 1417 return false; 1418 if (ArrayIndex == 0) 1419 CommonElementType = C->getType(); 1420 else if (C->getType() != CommonElementType) 1421 CommonElementType = nullptr; 1422 Elts.push_back(C); 1423 return true; 1424 }; 1425 1426 unsigned ArrayIndex = 0; 1427 QualType DestTy = CAT->getElementType(); 1428 for (unsigned i = 0; i < ILE->getNumInits(); ++i) { 1429 const Expr *Init = ILE->getInit(i); 1430 if (auto *EmbedS = dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts())) { 1431 StringLiteral *SL = EmbedS->getDataStringLiteral(); 1432 llvm::APSInt Value(CGM.getContext().getTypeSize(DestTy), 1433 DestTy->isUnsignedIntegerType()); 1434 llvm::Constant *C; 1435 for (unsigned I = EmbedS->getStartingElementPos(), 1436 N = EmbedS->getDataElementCount(); 1437 I != EmbedS->getStartingElementPos() + N; ++I) { 1438 Value = SL->getCodeUnit(I); 1439 if (DestTy->isIntegerType()) { 1440 C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value); 1441 } else { 1442 C = Emitter.tryEmitPrivateForMemory( 1443 withDestType(CGM.getContext(), Init, EmbedS->getType(), DestTy, 1444 Value), 1445 EltType); 1446 } 1447 if (!C) 1448 return nullptr; 1449 Elts.push_back(C); 1450 ArrayIndex++; 1451 } 1452 if ((ArrayIndex - EmbedS->getDataElementCount()) == 0) 1453 CommonElementType = C->getType(); 1454 else if (C->getType() != CommonElementType) 1455 CommonElementType = nullptr; 1456 } else { 1457 if (!Emit(Init, ArrayIndex)) 1458 return nullptr; 1459 ArrayIndex++; 1460 } 1461 } 1462 1463 llvm::ArrayType *Desired = 1464 cast<llvm::ArrayType>(CGM.getTypes().ConvertType(ILE->getType())); 1465 return EmitArrayConstant(CGM, Desired, CommonElementType, NumElements, Elts, 1466 fillC); 1467 } 1468 1469 llvm::Constant *EmitRecordInitialization(const InitListExpr *ILE, 1470 QualType T) { 1471 return ConstStructBuilder::BuildStruct(Emitter, ILE, T); 1472 } 1473 1474 llvm::Constant *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E, 1475 QualType T) { 1476 return CGM.EmitNullConstant(T); 1477 } 1478 1479 llvm::Constant *VisitInitListExpr(const InitListExpr *ILE, QualType T) { 1480 if (ILE->isTransparent()) 1481 return Visit(ILE->getInit(0), T); 1482 1483 if (ILE->getType()->isArrayType()) 1484 return EmitArrayInitialization(ILE, T); 1485 1486 if (ILE->getType()->isRecordType()) 1487 return EmitRecordInitialization(ILE, T); 1488 1489 return nullptr; 1490 } 1491 1492 llvm::Constant * 1493 VisitDesignatedInitUpdateExpr(const DesignatedInitUpdateExpr *E, 1494 QualType destType) { 1495 auto C = Visit(E->getBase(), destType); 1496 if (!C) 1497 return nullptr; 1498 1499 ConstantAggregateBuilder Const(CGM); 1500 Const.add(C, CharUnits::Zero(), false); 1501 1502 if (!EmitDesignatedInitUpdater(Emitter, Const, CharUnits::Zero(), destType, 1503 E->getUpdater())) 1504 return nullptr; 1505 1506 llvm::Type *ValTy = CGM.getTypes().ConvertType(destType); 1507 bool HasFlexibleArray = false; 1508 if (const auto *RT = destType->getAs<RecordType>()) 1509 HasFlexibleArray = RT->getDecl()->hasFlexibleArrayMember(); 1510 return Const.build(ValTy, HasFlexibleArray); 1511 } 1512 1513 llvm::Constant *VisitCXXConstructExpr(const CXXConstructExpr *E, 1514 QualType Ty) { 1515 if (!E->getConstructor()->isTrivial()) 1516 return nullptr; 1517 1518 // Only default and copy/move constructors can be trivial. 1519 if (E->getNumArgs()) { 1520 assert(E->getNumArgs() == 1 && "trivial ctor with > 1 argument"); 1521 assert(E->getConstructor()->isCopyOrMoveConstructor() && 1522 "trivial ctor has argument but isn't a copy/move ctor"); 1523 1524 const Expr *Arg = E->getArg(0); 1525 assert(CGM.getContext().hasSameUnqualifiedType(Ty, Arg->getType()) && 1526 "argument to copy ctor is of wrong type"); 1527 1528 // Look through the temporary; it's just converting the value to an 1529 // lvalue to pass it to the constructor. 1530 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Arg)) 1531 return Visit(MTE->getSubExpr(), Ty); 1532 // Don't try to support arbitrary lvalue-to-rvalue conversions for now. 1533 return nullptr; 1534 } 1535 1536 return CGM.EmitNullConstant(Ty); 1537 } 1538 1539 llvm::Constant *VisitStringLiteral(const StringLiteral *E, QualType T) { 1540 // This is a string literal initializing an array in an initializer. 1541 return CGM.GetConstantArrayFromStringLiteral(E); 1542 } 1543 1544 llvm::Constant *VisitObjCEncodeExpr(const ObjCEncodeExpr *E, QualType T) { 1545 // This must be an @encode initializing an array in a static initializer. 1546 // Don't emit it as the address of the string, emit the string data itself 1547 // as an inline array. 1548 std::string Str; 1549 CGM.getContext().getObjCEncodingForType(E->getEncodedType(), Str); 1550 const ConstantArrayType *CAT = CGM.getContext().getAsConstantArrayType(T); 1551 assert(CAT && "String data not of constant array type!"); 1552 1553 // Resize the string to the right size, adding zeros at the end, or 1554 // truncating as needed. 1555 Str.resize(CAT->getZExtSize(), '\0'); 1556 return llvm::ConstantDataArray::getString(VMContext, Str, false); 1557 } 1558 1559 llvm::Constant *VisitUnaryExtension(const UnaryOperator *E, QualType T) { 1560 return Visit(E->getSubExpr(), T); 1561 } 1562 1563 llvm::Constant *VisitUnaryMinus(const UnaryOperator *U, QualType T) { 1564 if (llvm::Constant *C = Visit(U->getSubExpr(), T)) 1565 if (auto *CI = dyn_cast<llvm::ConstantInt>(C)) 1566 return llvm::ConstantInt::get(CGM.getLLVMContext(), -CI->getValue()); 1567 return nullptr; 1568 } 1569 1570 llvm::Constant *VisitPackIndexingExpr(const PackIndexingExpr *E, QualType T) { 1571 return Visit(E->getSelectedExpr(), T); 1572 } 1573 1574 // Utility methods 1575 llvm::Type *ConvertType(QualType T) { 1576 return CGM.getTypes().ConvertType(T); 1577 } 1578 }; 1579 1580 } // end anonymous namespace. 1581 1582 llvm::Constant *ConstantEmitter::validateAndPopAbstract(llvm::Constant *C, 1583 AbstractState saved) { 1584 Abstract = saved.OldValue; 1585 1586 assert(saved.OldPlaceholdersSize == PlaceholderAddresses.size() && 1587 "created a placeholder while doing an abstract emission?"); 1588 1589 // No validation necessary for now. 1590 // No cleanup to do for now. 1591 return C; 1592 } 1593 1594 llvm::Constant * 1595 ConstantEmitter::tryEmitAbstractForInitializer(const VarDecl &D) { 1596 auto state = pushAbstract(); 1597 auto C = tryEmitPrivateForVarInit(D); 1598 return validateAndPopAbstract(C, state); 1599 } 1600 1601 llvm::Constant * 1602 ConstantEmitter::tryEmitAbstract(const Expr *E, QualType destType) { 1603 auto state = pushAbstract(); 1604 auto C = tryEmitPrivate(E, destType); 1605 return validateAndPopAbstract(C, state); 1606 } 1607 1608 llvm::Constant * 1609 ConstantEmitter::tryEmitAbstract(const APValue &value, QualType destType) { 1610 auto state = pushAbstract(); 1611 auto C = tryEmitPrivate(value, destType); 1612 return validateAndPopAbstract(C, state); 1613 } 1614 1615 llvm::Constant *ConstantEmitter::tryEmitConstantExpr(const ConstantExpr *CE) { 1616 if (!CE->hasAPValueResult()) 1617 return nullptr; 1618 1619 QualType RetType = CE->getType(); 1620 if (CE->isGLValue()) 1621 RetType = CGM.getContext().getLValueReferenceType(RetType); 1622 1623 return emitAbstract(CE->getBeginLoc(), CE->getAPValueResult(), RetType); 1624 } 1625 1626 llvm::Constant * 1627 ConstantEmitter::emitAbstract(const Expr *E, QualType destType) { 1628 auto state = pushAbstract(); 1629 auto C = tryEmitPrivate(E, destType); 1630 C = validateAndPopAbstract(C, state); 1631 if (!C) { 1632 CGM.Error(E->getExprLoc(), 1633 "internal error: could not emit constant value \"abstractly\""); 1634 C = CGM.EmitNullConstant(destType); 1635 } 1636 return C; 1637 } 1638 1639 llvm::Constant * 1640 ConstantEmitter::emitAbstract(SourceLocation loc, const APValue &value, 1641 QualType destType, 1642 bool EnablePtrAuthFunctionTypeDiscrimination) { 1643 auto state = pushAbstract(); 1644 auto C = 1645 tryEmitPrivate(value, destType, EnablePtrAuthFunctionTypeDiscrimination); 1646 C = validateAndPopAbstract(C, state); 1647 if (!C) { 1648 CGM.Error(loc, 1649 "internal error: could not emit constant value \"abstractly\""); 1650 C = CGM.EmitNullConstant(destType); 1651 } 1652 return C; 1653 } 1654 1655 llvm::Constant *ConstantEmitter::tryEmitForInitializer(const VarDecl &D) { 1656 initializeNonAbstract(D.getType().getAddressSpace()); 1657 return markIfFailed(tryEmitPrivateForVarInit(D)); 1658 } 1659 1660 llvm::Constant *ConstantEmitter::tryEmitForInitializer(const Expr *E, 1661 LangAS destAddrSpace, 1662 QualType destType) { 1663 initializeNonAbstract(destAddrSpace); 1664 return markIfFailed(tryEmitPrivateForMemory(E, destType)); 1665 } 1666 1667 llvm::Constant *ConstantEmitter::emitForInitializer(const APValue &value, 1668 LangAS destAddrSpace, 1669 QualType destType) { 1670 initializeNonAbstract(destAddrSpace); 1671 auto C = tryEmitPrivateForMemory(value, destType); 1672 assert(C && "couldn't emit constant value non-abstractly?"); 1673 return C; 1674 } 1675 1676 llvm::GlobalValue *ConstantEmitter::getCurrentAddrPrivate() { 1677 assert(!Abstract && "cannot get current address for abstract constant"); 1678 1679 1680 1681 // Make an obviously ill-formed global that should blow up compilation 1682 // if it survives. 1683 auto global = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8Ty, true, 1684 llvm::GlobalValue::PrivateLinkage, 1685 /*init*/ nullptr, 1686 /*name*/ "", 1687 /*before*/ nullptr, 1688 llvm::GlobalVariable::NotThreadLocal, 1689 CGM.getContext().getTargetAddressSpace(DestAddressSpace)); 1690 1691 PlaceholderAddresses.push_back(std::make_pair(nullptr, global)); 1692 1693 return global; 1694 } 1695 1696 void ConstantEmitter::registerCurrentAddrPrivate(llvm::Constant *signal, 1697 llvm::GlobalValue *placeholder) { 1698 assert(!PlaceholderAddresses.empty()); 1699 assert(PlaceholderAddresses.back().first == nullptr); 1700 assert(PlaceholderAddresses.back().second == placeholder); 1701 PlaceholderAddresses.back().first = signal; 1702 } 1703 1704 namespace { 1705 struct ReplacePlaceholders { 1706 CodeGenModule &CGM; 1707 1708 /// The base address of the global. 1709 llvm::Constant *Base; 1710 llvm::Type *BaseValueTy = nullptr; 1711 1712 /// The placeholder addresses that were registered during emission. 1713 llvm::DenseMap<llvm::Constant*, llvm::GlobalVariable*> PlaceholderAddresses; 1714 1715 /// The locations of the placeholder signals. 1716 llvm::DenseMap<llvm::GlobalVariable*, llvm::Constant*> Locations; 1717 1718 /// The current index stack. We use a simple unsigned stack because 1719 /// we assume that placeholders will be relatively sparse in the 1720 /// initializer, but we cache the index values we find just in case. 1721 llvm::SmallVector<unsigned, 8> Indices; 1722 llvm::SmallVector<llvm::Constant*, 8> IndexValues; 1723 1724 ReplacePlaceholders(CodeGenModule &CGM, llvm::Constant *base, 1725 ArrayRef<std::pair<llvm::Constant*, 1726 llvm::GlobalVariable*>> addresses) 1727 : CGM(CGM), Base(base), 1728 PlaceholderAddresses(addresses.begin(), addresses.end()) { 1729 } 1730 1731 void replaceInInitializer(llvm::Constant *init) { 1732 // Remember the type of the top-most initializer. 1733 BaseValueTy = init->getType(); 1734 1735 // Initialize the stack. 1736 Indices.push_back(0); 1737 IndexValues.push_back(nullptr); 1738 1739 // Recurse into the initializer. 1740 findLocations(init); 1741 1742 // Check invariants. 1743 assert(IndexValues.size() == Indices.size() && "mismatch"); 1744 assert(Indices.size() == 1 && "didn't pop all indices"); 1745 1746 // Do the replacement; this basically invalidates 'init'. 1747 assert(Locations.size() == PlaceholderAddresses.size() && 1748 "missed a placeholder?"); 1749 1750 // We're iterating over a hashtable, so this would be a source of 1751 // non-determinism in compiler output *except* that we're just 1752 // messing around with llvm::Constant structures, which never itself 1753 // does anything that should be visible in compiler output. 1754 for (auto &entry : Locations) { 1755 assert(entry.first->getName() == "" && "not a placeholder!"); 1756 entry.first->replaceAllUsesWith(entry.second); 1757 entry.first->eraseFromParent(); 1758 } 1759 } 1760 1761 private: 1762 void findLocations(llvm::Constant *init) { 1763 // Recurse into aggregates. 1764 if (auto agg = dyn_cast<llvm::ConstantAggregate>(init)) { 1765 for (unsigned i = 0, e = agg->getNumOperands(); i != e; ++i) { 1766 Indices.push_back(i); 1767 IndexValues.push_back(nullptr); 1768 1769 findLocations(agg->getOperand(i)); 1770 1771 IndexValues.pop_back(); 1772 Indices.pop_back(); 1773 } 1774 return; 1775 } 1776 1777 // Otherwise, check for registered constants. 1778 while (true) { 1779 auto it = PlaceholderAddresses.find(init); 1780 if (it != PlaceholderAddresses.end()) { 1781 setLocation(it->second); 1782 break; 1783 } 1784 1785 // Look through bitcasts or other expressions. 1786 if (auto expr = dyn_cast<llvm::ConstantExpr>(init)) { 1787 init = expr->getOperand(0); 1788 } else { 1789 break; 1790 } 1791 } 1792 } 1793 1794 void setLocation(llvm::GlobalVariable *placeholder) { 1795 assert(!Locations.contains(placeholder) && 1796 "already found location for placeholder!"); 1797 1798 // Lazily fill in IndexValues with the values from Indices. 1799 // We do this in reverse because we should always have a strict 1800 // prefix of indices from the start. 1801 assert(Indices.size() == IndexValues.size()); 1802 for (size_t i = Indices.size() - 1; i != size_t(-1); --i) { 1803 if (IndexValues[i]) { 1804 #ifndef NDEBUG 1805 for (size_t j = 0; j != i + 1; ++j) { 1806 assert(IndexValues[j] && 1807 isa<llvm::ConstantInt>(IndexValues[j]) && 1808 cast<llvm::ConstantInt>(IndexValues[j])->getZExtValue() 1809 == Indices[j]); 1810 } 1811 #endif 1812 break; 1813 } 1814 1815 IndexValues[i] = llvm::ConstantInt::get(CGM.Int32Ty, Indices[i]); 1816 } 1817 1818 llvm::Constant *location = llvm::ConstantExpr::getInBoundsGetElementPtr( 1819 BaseValueTy, Base, IndexValues); 1820 1821 Locations.insert({placeholder, location}); 1822 } 1823 }; 1824 } 1825 1826 void ConstantEmitter::finalize(llvm::GlobalVariable *global) { 1827 assert(InitializedNonAbstract && 1828 "finalizing emitter that was used for abstract emission?"); 1829 assert(!Finalized && "finalizing emitter multiple times"); 1830 assert(global->getInitializer()); 1831 1832 // Note that we might also be Failed. 1833 Finalized = true; 1834 1835 if (!PlaceholderAddresses.empty()) { 1836 ReplacePlaceholders(CGM, global, PlaceholderAddresses) 1837 .replaceInInitializer(global->getInitializer()); 1838 PlaceholderAddresses.clear(); // satisfy 1839 } 1840 } 1841 1842 ConstantEmitter::~ConstantEmitter() { 1843 assert((!InitializedNonAbstract || Finalized || Failed) && 1844 "not finalized after being initialized for non-abstract emission"); 1845 assert(PlaceholderAddresses.empty() && "unhandled placeholders"); 1846 } 1847 1848 static QualType getNonMemoryType(CodeGenModule &CGM, QualType type) { 1849 if (auto AT = type->getAs<AtomicType>()) { 1850 return CGM.getContext().getQualifiedType(AT->getValueType(), 1851 type.getQualifiers()); 1852 } 1853 return type; 1854 } 1855 1856 llvm::Constant *ConstantEmitter::tryEmitPrivateForVarInit(const VarDecl &D) { 1857 // Make a quick check if variable can be default NULL initialized 1858 // and avoid going through rest of code which may do, for c++11, 1859 // initialization of memory to all NULLs. 1860 if (!D.hasLocalStorage()) { 1861 QualType Ty = CGM.getContext().getBaseElementType(D.getType()); 1862 if (Ty->isRecordType()) 1863 if (const CXXConstructExpr *E = 1864 dyn_cast_or_null<CXXConstructExpr>(D.getInit())) { 1865 const CXXConstructorDecl *CD = E->getConstructor(); 1866 if (CD->isTrivial() && CD->isDefaultConstructor()) 1867 return CGM.EmitNullConstant(D.getType()); 1868 } 1869 } 1870 InConstantContext = D.hasConstantInitialization(); 1871 1872 QualType destType = D.getType(); 1873 const Expr *E = D.getInit(); 1874 assert(E && "No initializer to emit"); 1875 1876 if (!destType->isReferenceType()) { 1877 QualType nonMemoryDestType = getNonMemoryType(CGM, destType); 1878 if (llvm::Constant *C = ConstExprEmitter(*this).Visit(E, nonMemoryDestType)) 1879 return emitForMemory(C, destType); 1880 } 1881 1882 // Try to emit the initializer. Note that this can allow some things that 1883 // are not allowed by tryEmitPrivateForMemory alone. 1884 if (APValue *value = D.evaluateValue()) { 1885 assert(!value->allowConstexprUnknown() && 1886 "Constexpr unknown values are not allowed in CodeGen"); 1887 return tryEmitPrivateForMemory(*value, destType); 1888 } 1889 1890 return nullptr; 1891 } 1892 1893 llvm::Constant * 1894 ConstantEmitter::tryEmitAbstractForMemory(const Expr *E, QualType destType) { 1895 auto nonMemoryDestType = getNonMemoryType(CGM, destType); 1896 auto C = tryEmitAbstract(E, nonMemoryDestType); 1897 return (C ? emitForMemory(C, destType) : nullptr); 1898 } 1899 1900 llvm::Constant * 1901 ConstantEmitter::tryEmitAbstractForMemory(const APValue &value, 1902 QualType destType) { 1903 auto nonMemoryDestType = getNonMemoryType(CGM, destType); 1904 auto C = tryEmitAbstract(value, nonMemoryDestType); 1905 return (C ? emitForMemory(C, destType) : nullptr); 1906 } 1907 1908 llvm::Constant *ConstantEmitter::tryEmitPrivateForMemory(const Expr *E, 1909 QualType destType) { 1910 auto nonMemoryDestType = getNonMemoryType(CGM, destType); 1911 llvm::Constant *C = tryEmitPrivate(E, nonMemoryDestType); 1912 return (C ? emitForMemory(C, destType) : nullptr); 1913 } 1914 1915 llvm::Constant *ConstantEmitter::tryEmitPrivateForMemory(const APValue &value, 1916 QualType destType) { 1917 auto nonMemoryDestType = getNonMemoryType(CGM, destType); 1918 auto C = tryEmitPrivate(value, nonMemoryDestType); 1919 return (C ? emitForMemory(C, destType) : nullptr); 1920 } 1921 1922 /// Try to emit a constant signed pointer, given a raw pointer and the 1923 /// destination ptrauth qualifier. 1924 /// 1925 /// This can fail if the qualifier needs address discrimination and the 1926 /// emitter is in an abstract mode. 1927 llvm::Constant * 1928 ConstantEmitter::tryEmitConstantSignedPointer(llvm::Constant *UnsignedPointer, 1929 PointerAuthQualifier Schema) { 1930 assert(Schema && "applying trivial ptrauth schema"); 1931 1932 if (Schema.hasKeyNone()) 1933 return UnsignedPointer; 1934 1935 unsigned Key = Schema.getKey(); 1936 1937 // Create an address placeholder if we're using address discrimination. 1938 llvm::GlobalValue *StorageAddress = nullptr; 1939 if (Schema.isAddressDiscriminated()) { 1940 // We can't do this if the emitter is in an abstract state. 1941 if (isAbstract()) 1942 return nullptr; 1943 1944 StorageAddress = getCurrentAddrPrivate(); 1945 } 1946 1947 llvm::ConstantInt *Discriminator = 1948 llvm::ConstantInt::get(CGM.IntPtrTy, Schema.getExtraDiscriminator()); 1949 1950 llvm::Constant *SignedPointer = CGM.getConstantSignedPointer( 1951 UnsignedPointer, Key, StorageAddress, Discriminator); 1952 1953 if (Schema.isAddressDiscriminated()) 1954 registerCurrentAddrPrivate(SignedPointer, StorageAddress); 1955 1956 return SignedPointer; 1957 } 1958 1959 llvm::Constant *ConstantEmitter::emitForMemory(CodeGenModule &CGM, 1960 llvm::Constant *C, 1961 QualType destType) { 1962 // For an _Atomic-qualified constant, we may need to add tail padding. 1963 if (auto AT = destType->getAs<AtomicType>()) { 1964 QualType destValueType = AT->getValueType(); 1965 C = emitForMemory(CGM, C, destValueType); 1966 1967 uint64_t innerSize = CGM.getContext().getTypeSize(destValueType); 1968 uint64_t outerSize = CGM.getContext().getTypeSize(destType); 1969 if (innerSize == outerSize) 1970 return C; 1971 1972 assert(innerSize < outerSize && "emitted over-large constant for atomic"); 1973 llvm::Constant *elts[] = { 1974 C, 1975 llvm::ConstantAggregateZero::get( 1976 llvm::ArrayType::get(CGM.Int8Ty, (outerSize - innerSize) / 8)) 1977 }; 1978 return llvm::ConstantStruct::getAnon(elts); 1979 } 1980 1981 // Zero-extend bool. 1982 // In HLSL bool vectors are stored in memory as a vector of i32 1983 if ((C->getType()->isIntegerTy(1) && !destType->isBitIntType()) || 1984 (destType->isExtVectorBoolType() && 1985 !destType->isPackedVectorBoolType(CGM.getContext()))) { 1986 llvm::Type *boolTy = CGM.getTypes().ConvertTypeForMem(destType); 1987 llvm::Constant *Res = llvm::ConstantFoldCastOperand( 1988 llvm::Instruction::ZExt, C, boolTy, CGM.getDataLayout()); 1989 assert(Res && "Constant folding must succeed"); 1990 return Res; 1991 } 1992 1993 if (destType->isBitIntType()) { 1994 ConstantAggregateBuilder Builder(CGM); 1995 llvm::Type *LoadStoreTy = CGM.getTypes().convertTypeForLoadStore(destType); 1996 // ptrtoint/inttoptr should not involve _BitInt in constant expressions, so 1997 // casting to ConstantInt is safe here. 1998 auto *CI = cast<llvm::ConstantInt>(C); 1999 llvm::Constant *Res = llvm::ConstantFoldCastOperand( 2000 destType->isSignedIntegerOrEnumerationType() ? llvm::Instruction::SExt 2001 : llvm::Instruction::ZExt, 2002 CI, LoadStoreTy, CGM.getDataLayout()); 2003 if (CGM.getTypes().typeRequiresSplitIntoByteArray(destType, C->getType())) { 2004 // Long _BitInt has array of bytes as in-memory type. 2005 // So, split constant into individual bytes. 2006 llvm::Type *DesiredTy = CGM.getTypes().ConvertTypeForMem(destType); 2007 llvm::APInt Value = cast<llvm::ConstantInt>(Res)->getValue(); 2008 Builder.addBits(Value, /*OffsetInBits=*/0, /*AllowOverwrite=*/false); 2009 return Builder.build(DesiredTy, /*AllowOversized*/ false); 2010 } 2011 return Res; 2012 } 2013 2014 return C; 2015 } 2016 2017 llvm::Constant *ConstantEmitter::tryEmitPrivate(const Expr *E, 2018 QualType destType) { 2019 assert(!destType->isVoidType() && "can't emit a void constant"); 2020 2021 if (!destType->isReferenceType()) 2022 if (llvm::Constant *C = ConstExprEmitter(*this).Visit(E, destType)) 2023 return C; 2024 2025 Expr::EvalResult Result; 2026 2027 bool Success = false; 2028 2029 if (destType->isReferenceType()) 2030 Success = E->EvaluateAsLValue(Result, CGM.getContext()); 2031 else 2032 Success = E->EvaluateAsRValue(Result, CGM.getContext(), InConstantContext); 2033 2034 if (Success && !Result.HasSideEffects) 2035 return tryEmitPrivate(Result.Val, destType); 2036 2037 return nullptr; 2038 } 2039 2040 llvm::Constant *CodeGenModule::getNullPointer(llvm::PointerType *T, QualType QT) { 2041 return getTargetCodeGenInfo().getNullPointer(*this, T, QT); 2042 } 2043 2044 namespace { 2045 /// A struct which can be used to peephole certain kinds of finalization 2046 /// that normally happen during l-value emission. 2047 struct ConstantLValue { 2048 llvm::Constant *Value; 2049 bool HasOffsetApplied; 2050 bool HasDestPointerAuth; 2051 2052 /*implicit*/ ConstantLValue(llvm::Constant *value, 2053 bool hasOffsetApplied = false, 2054 bool hasDestPointerAuth = false) 2055 : Value(value), HasOffsetApplied(hasOffsetApplied), 2056 HasDestPointerAuth(hasDestPointerAuth) {} 2057 2058 /*implicit*/ ConstantLValue(ConstantAddress address) 2059 : ConstantLValue(address.getPointer()) {} 2060 }; 2061 2062 /// A helper class for emitting constant l-values. 2063 class ConstantLValueEmitter : public ConstStmtVisitor<ConstantLValueEmitter, 2064 ConstantLValue> { 2065 CodeGenModule &CGM; 2066 ConstantEmitter &Emitter; 2067 const APValue &Value; 2068 QualType DestType; 2069 bool EnablePtrAuthFunctionTypeDiscrimination; 2070 2071 // Befriend StmtVisitorBase so that we don't have to expose Visit*. 2072 friend StmtVisitorBase; 2073 2074 public: 2075 ConstantLValueEmitter(ConstantEmitter &emitter, const APValue &value, 2076 QualType destType, 2077 bool EnablePtrAuthFunctionTypeDiscrimination = true) 2078 : CGM(emitter.CGM), Emitter(emitter), Value(value), DestType(destType), 2079 EnablePtrAuthFunctionTypeDiscrimination( 2080 EnablePtrAuthFunctionTypeDiscrimination) {} 2081 2082 llvm::Constant *tryEmit(); 2083 2084 private: 2085 llvm::Constant *tryEmitAbsolute(llvm::Type *destTy); 2086 ConstantLValue tryEmitBase(const APValue::LValueBase &base); 2087 2088 ConstantLValue VisitStmt(const Stmt *S) { return nullptr; } 2089 ConstantLValue VisitConstantExpr(const ConstantExpr *E); 2090 ConstantLValue VisitCompoundLiteralExpr(const CompoundLiteralExpr *E); 2091 ConstantLValue VisitStringLiteral(const StringLiteral *E); 2092 ConstantLValue VisitObjCBoxedExpr(const ObjCBoxedExpr *E); 2093 ConstantLValue VisitObjCEncodeExpr(const ObjCEncodeExpr *E); 2094 ConstantLValue VisitObjCStringLiteral(const ObjCStringLiteral *E); 2095 ConstantLValue VisitPredefinedExpr(const PredefinedExpr *E); 2096 ConstantLValue VisitAddrLabelExpr(const AddrLabelExpr *E); 2097 ConstantLValue VisitCallExpr(const CallExpr *E); 2098 ConstantLValue VisitBlockExpr(const BlockExpr *E); 2099 ConstantLValue VisitCXXTypeidExpr(const CXXTypeidExpr *E); 2100 ConstantLValue VisitMaterializeTemporaryExpr( 2101 const MaterializeTemporaryExpr *E); 2102 2103 ConstantLValue emitPointerAuthSignConstant(const CallExpr *E); 2104 llvm::Constant *emitPointerAuthPointer(const Expr *E); 2105 unsigned emitPointerAuthKey(const Expr *E); 2106 std::pair<llvm::Constant *, llvm::ConstantInt *> 2107 emitPointerAuthDiscriminator(const Expr *E); 2108 2109 bool hasNonZeroOffset() const { 2110 return !Value.getLValueOffset().isZero(); 2111 } 2112 2113 /// Return the value offset. 2114 llvm::Constant *getOffset() { 2115 return llvm::ConstantInt::get(CGM.Int64Ty, 2116 Value.getLValueOffset().getQuantity()); 2117 } 2118 2119 /// Apply the value offset to the given constant. 2120 llvm::Constant *applyOffset(llvm::Constant *C) { 2121 if (!hasNonZeroOffset()) 2122 return C; 2123 2124 return llvm::ConstantExpr::getGetElementPtr(CGM.Int8Ty, C, getOffset()); 2125 } 2126 }; 2127 2128 } 2129 2130 llvm::Constant *ConstantLValueEmitter::tryEmit() { 2131 const APValue::LValueBase &base = Value.getLValueBase(); 2132 2133 // The destination type should be a pointer or reference 2134 // type, but it might also be a cast thereof. 2135 // 2136 // FIXME: the chain of casts required should be reflected in the APValue. 2137 // We need this in order to correctly handle things like a ptrtoint of a 2138 // non-zero null pointer and addrspace casts that aren't trivially 2139 // represented in LLVM IR. 2140 auto destTy = CGM.getTypes().ConvertTypeForMem(DestType); 2141 assert(isa<llvm::IntegerType>(destTy) || isa<llvm::PointerType>(destTy)); 2142 2143 // If there's no base at all, this is a null or absolute pointer, 2144 // possibly cast back to an integer type. 2145 if (!base) { 2146 return tryEmitAbsolute(destTy); 2147 } 2148 2149 // Otherwise, try to emit the base. 2150 ConstantLValue result = tryEmitBase(base); 2151 2152 // If that failed, we're done. 2153 llvm::Constant *value = result.Value; 2154 if (!value) return nullptr; 2155 2156 // Apply the offset if necessary and not already done. 2157 if (!result.HasOffsetApplied) { 2158 value = applyOffset(value); 2159 } 2160 2161 // Apply pointer-auth signing from the destination type. 2162 if (PointerAuthQualifier PointerAuth = DestType.getPointerAuth(); 2163 PointerAuth && !result.HasDestPointerAuth) { 2164 value = Emitter.tryEmitConstantSignedPointer(value, PointerAuth); 2165 if (!value) 2166 return nullptr; 2167 } 2168 2169 // Convert to the appropriate type; this could be an lvalue for 2170 // an integer. FIXME: performAddrSpaceCast 2171 if (isa<llvm::PointerType>(destTy)) 2172 return llvm::ConstantExpr::getPointerCast(value, destTy); 2173 2174 return llvm::ConstantExpr::getPtrToInt(value, destTy); 2175 } 2176 2177 /// Try to emit an absolute l-value, such as a null pointer or an integer 2178 /// bitcast to pointer type. 2179 llvm::Constant * 2180 ConstantLValueEmitter::tryEmitAbsolute(llvm::Type *destTy) { 2181 // If we're producing a pointer, this is easy. 2182 auto destPtrTy = cast<llvm::PointerType>(destTy); 2183 if (Value.isNullPointer()) { 2184 // FIXME: integer offsets from non-zero null pointers. 2185 return CGM.getNullPointer(destPtrTy, DestType); 2186 } 2187 2188 // Convert the integer to a pointer-sized integer before converting it 2189 // to a pointer. 2190 // FIXME: signedness depends on the original integer type. 2191 auto intptrTy = CGM.getDataLayout().getIntPtrType(destPtrTy); 2192 llvm::Constant *C; 2193 C = llvm::ConstantFoldIntegerCast(getOffset(), intptrTy, /*isSigned*/ false, 2194 CGM.getDataLayout()); 2195 assert(C && "Must have folded, as Offset is a ConstantInt"); 2196 C = llvm::ConstantExpr::getIntToPtr(C, destPtrTy); 2197 return C; 2198 } 2199 2200 ConstantLValue 2201 ConstantLValueEmitter::tryEmitBase(const APValue::LValueBase &base) { 2202 // Handle values. 2203 if (const ValueDecl *D = base.dyn_cast<const ValueDecl*>()) { 2204 // The constant always points to the canonical declaration. We want to look 2205 // at properties of the most recent declaration at the point of emission. 2206 D = cast<ValueDecl>(D->getMostRecentDecl()); 2207 2208 if (D->hasAttr<WeakRefAttr>()) 2209 return CGM.GetWeakRefReference(D).getPointer(); 2210 2211 auto PtrAuthSign = [&](llvm::Constant *C) { 2212 if (PointerAuthQualifier PointerAuth = DestType.getPointerAuth()) { 2213 C = applyOffset(C); 2214 C = Emitter.tryEmitConstantSignedPointer(C, PointerAuth); 2215 return ConstantLValue(C, /*applied offset*/ true, /*signed*/ true); 2216 } 2217 2218 CGPointerAuthInfo AuthInfo; 2219 2220 if (EnablePtrAuthFunctionTypeDiscrimination) 2221 AuthInfo = CGM.getFunctionPointerAuthInfo(DestType); 2222 2223 if (AuthInfo) { 2224 if (hasNonZeroOffset()) 2225 return ConstantLValue(nullptr); 2226 2227 C = applyOffset(C); 2228 C = CGM.getConstantSignedPointer( 2229 C, AuthInfo.getKey(), nullptr, 2230 cast_or_null<llvm::ConstantInt>(AuthInfo.getDiscriminator())); 2231 return ConstantLValue(C, /*applied offset*/ true, /*signed*/ true); 2232 } 2233 2234 return ConstantLValue(C); 2235 }; 2236 2237 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 2238 llvm::Constant *C = CGM.getRawFunctionPointer(FD); 2239 if (FD->getType()->isCFIUncheckedCalleeFunctionType()) 2240 C = llvm::NoCFIValue::get(cast<llvm::GlobalValue>(C)); 2241 return PtrAuthSign(C); 2242 } 2243 2244 if (const auto *VD = dyn_cast<VarDecl>(D)) { 2245 // We can never refer to a variable with local storage. 2246 if (!VD->hasLocalStorage()) { 2247 if (VD->isFileVarDecl() || VD->hasExternalStorage()) 2248 return CGM.GetAddrOfGlobalVar(VD); 2249 2250 if (VD->isLocalVarDecl()) { 2251 return CGM.getOrCreateStaticVarDecl( 2252 *VD, CGM.getLLVMLinkageVarDefinition(VD)); 2253 } 2254 } 2255 } 2256 2257 if (const auto *GD = dyn_cast<MSGuidDecl>(D)) 2258 return CGM.GetAddrOfMSGuidDecl(GD); 2259 2260 if (const auto *GCD = dyn_cast<UnnamedGlobalConstantDecl>(D)) 2261 return CGM.GetAddrOfUnnamedGlobalConstantDecl(GCD); 2262 2263 if (const auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) 2264 return CGM.GetAddrOfTemplateParamObject(TPO); 2265 2266 return nullptr; 2267 } 2268 2269 // Handle typeid(T). 2270 if (TypeInfoLValue TI = base.dyn_cast<TypeInfoLValue>()) 2271 return CGM.GetAddrOfRTTIDescriptor(QualType(TI.getType(), 0)); 2272 2273 // Otherwise, it must be an expression. 2274 return Visit(base.get<const Expr*>()); 2275 } 2276 2277 ConstantLValue 2278 ConstantLValueEmitter::VisitConstantExpr(const ConstantExpr *E) { 2279 if (llvm::Constant *Result = Emitter.tryEmitConstantExpr(E)) 2280 return Result; 2281 return Visit(E->getSubExpr()); 2282 } 2283 2284 ConstantLValue 2285 ConstantLValueEmitter::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 2286 ConstantEmitter CompoundLiteralEmitter(CGM, Emitter.CGF); 2287 CompoundLiteralEmitter.setInConstantContext(Emitter.isInConstantContext()); 2288 return tryEmitGlobalCompoundLiteral(CompoundLiteralEmitter, E); 2289 } 2290 2291 ConstantLValue 2292 ConstantLValueEmitter::VisitStringLiteral(const StringLiteral *E) { 2293 return CGM.GetAddrOfConstantStringFromLiteral(E); 2294 } 2295 2296 ConstantLValue 2297 ConstantLValueEmitter::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { 2298 return CGM.GetAddrOfConstantStringFromObjCEncode(E); 2299 } 2300 2301 static ConstantLValue emitConstantObjCStringLiteral(const StringLiteral *S, 2302 QualType T, 2303 CodeGenModule &CGM) { 2304 auto C = CGM.getObjCRuntime().GenerateConstantString(S); 2305 return C.withElementType(CGM.getTypes().ConvertTypeForMem(T)); 2306 } 2307 2308 ConstantLValue 2309 ConstantLValueEmitter::VisitObjCStringLiteral(const ObjCStringLiteral *E) { 2310 return emitConstantObjCStringLiteral(E->getString(), E->getType(), CGM); 2311 } 2312 2313 ConstantLValue 2314 ConstantLValueEmitter::VisitObjCBoxedExpr(const ObjCBoxedExpr *E) { 2315 assert(E->isExpressibleAsConstantInitializer() && 2316 "this boxed expression can't be emitted as a compile-time constant"); 2317 const auto *SL = cast<StringLiteral>(E->getSubExpr()->IgnoreParenCasts()); 2318 return emitConstantObjCStringLiteral(SL, E->getType(), CGM); 2319 } 2320 2321 ConstantLValue 2322 ConstantLValueEmitter::VisitPredefinedExpr(const PredefinedExpr *E) { 2323 return CGM.GetAddrOfConstantStringFromLiteral(E->getFunctionName()); 2324 } 2325 2326 ConstantLValue 2327 ConstantLValueEmitter::VisitAddrLabelExpr(const AddrLabelExpr *E) { 2328 assert(Emitter.CGF && "Invalid address of label expression outside function"); 2329 llvm::Constant *Ptr = Emitter.CGF->GetAddrOfLabel(E->getLabel()); 2330 return Ptr; 2331 } 2332 2333 ConstantLValue 2334 ConstantLValueEmitter::VisitCallExpr(const CallExpr *E) { 2335 unsigned builtin = E->getBuiltinCallee(); 2336 if (builtin == Builtin::BI__builtin_function_start) 2337 return CGM.GetFunctionStart( 2338 E->getArg(0)->getAsBuiltinConstantDeclRef(CGM.getContext())); 2339 2340 if (builtin == Builtin::BI__builtin_ptrauth_sign_constant) 2341 return emitPointerAuthSignConstant(E); 2342 2343 if (builtin != Builtin::BI__builtin___CFStringMakeConstantString && 2344 builtin != Builtin::BI__builtin___NSStringMakeConstantString) 2345 return nullptr; 2346 2347 const auto *Literal = cast<StringLiteral>(E->getArg(0)->IgnoreParenCasts()); 2348 if (builtin == Builtin::BI__builtin___NSStringMakeConstantString) { 2349 return CGM.getObjCRuntime().GenerateConstantString(Literal); 2350 } else { 2351 // FIXME: need to deal with UCN conversion issues. 2352 return CGM.GetAddrOfConstantCFString(Literal); 2353 } 2354 } 2355 2356 ConstantLValue 2357 ConstantLValueEmitter::emitPointerAuthSignConstant(const CallExpr *E) { 2358 llvm::Constant *UnsignedPointer = emitPointerAuthPointer(E->getArg(0)); 2359 unsigned Key = emitPointerAuthKey(E->getArg(1)); 2360 auto [StorageAddress, OtherDiscriminator] = 2361 emitPointerAuthDiscriminator(E->getArg(2)); 2362 2363 llvm::Constant *SignedPointer = CGM.getConstantSignedPointer( 2364 UnsignedPointer, Key, StorageAddress, OtherDiscriminator); 2365 return SignedPointer; 2366 } 2367 2368 llvm::Constant *ConstantLValueEmitter::emitPointerAuthPointer(const Expr *E) { 2369 Expr::EvalResult Result; 2370 bool Succeeded = E->EvaluateAsRValue(Result, CGM.getContext()); 2371 assert(Succeeded); 2372 (void)Succeeded; 2373 2374 // The assertions here are all checked by Sema. 2375 assert(Result.Val.isLValue()); 2376 if (isa<FunctionDecl>(Result.Val.getLValueBase().get<const ValueDecl *>())) 2377 assert(Result.Val.getLValueOffset().isZero()); 2378 return ConstantEmitter(CGM, Emitter.CGF) 2379 .emitAbstract(E->getExprLoc(), Result.Val, E->getType(), false); 2380 } 2381 2382 unsigned ConstantLValueEmitter::emitPointerAuthKey(const Expr *E) { 2383 return E->EvaluateKnownConstInt(CGM.getContext()).getZExtValue(); 2384 } 2385 2386 std::pair<llvm::Constant *, llvm::ConstantInt *> 2387 ConstantLValueEmitter::emitPointerAuthDiscriminator(const Expr *E) { 2388 E = E->IgnoreParens(); 2389 2390 if (const auto *Call = dyn_cast<CallExpr>(E)) { 2391 if (Call->getBuiltinCallee() == 2392 Builtin::BI__builtin_ptrauth_blend_discriminator) { 2393 llvm::Constant *Pointer = ConstantEmitter(CGM).emitAbstract( 2394 Call->getArg(0), Call->getArg(0)->getType()); 2395 auto *Extra = cast<llvm::ConstantInt>(ConstantEmitter(CGM).emitAbstract( 2396 Call->getArg(1), Call->getArg(1)->getType())); 2397 return {Pointer, Extra}; 2398 } 2399 } 2400 2401 llvm::Constant *Result = ConstantEmitter(CGM).emitAbstract(E, E->getType()); 2402 if (Result->getType()->isPointerTy()) 2403 return {Result, nullptr}; 2404 return {nullptr, cast<llvm::ConstantInt>(Result)}; 2405 } 2406 2407 ConstantLValue 2408 ConstantLValueEmitter::VisitBlockExpr(const BlockExpr *E) { 2409 StringRef functionName; 2410 if (auto CGF = Emitter.CGF) 2411 functionName = CGF->CurFn->getName(); 2412 else 2413 functionName = "global"; 2414 2415 return CGM.GetAddrOfGlobalBlock(E, functionName); 2416 } 2417 2418 ConstantLValue 2419 ConstantLValueEmitter::VisitCXXTypeidExpr(const CXXTypeidExpr *E) { 2420 QualType T; 2421 if (E->isTypeOperand()) 2422 T = E->getTypeOperand(CGM.getContext()); 2423 else 2424 T = E->getExprOperand()->getType(); 2425 return CGM.GetAddrOfRTTIDescriptor(T); 2426 } 2427 2428 ConstantLValue 2429 ConstantLValueEmitter::VisitMaterializeTemporaryExpr( 2430 const MaterializeTemporaryExpr *E) { 2431 assert(E->getStorageDuration() == SD_Static); 2432 const Expr *Inner = E->getSubExpr()->skipRValueSubobjectAdjustments(); 2433 return CGM.GetAddrOfGlobalTemporary(E, Inner); 2434 } 2435 2436 llvm::Constant * 2437 ConstantEmitter::tryEmitPrivate(const APValue &Value, QualType DestType, 2438 bool EnablePtrAuthFunctionTypeDiscrimination) { 2439 switch (Value.getKind()) { 2440 case APValue::None: 2441 case APValue::Indeterminate: 2442 // Out-of-lifetime and indeterminate values can be modeled as 'undef'. 2443 return llvm::UndefValue::get(CGM.getTypes().ConvertType(DestType)); 2444 case APValue::LValue: 2445 return ConstantLValueEmitter(*this, Value, DestType, 2446 EnablePtrAuthFunctionTypeDiscrimination) 2447 .tryEmit(); 2448 case APValue::Int: 2449 if (PointerAuthQualifier PointerAuth = DestType.getPointerAuth(); 2450 PointerAuth && 2451 (PointerAuth.authenticatesNullValues() || Value.getInt() != 0)) 2452 return nullptr; 2453 return llvm::ConstantInt::get(CGM.getLLVMContext(), Value.getInt()); 2454 case APValue::FixedPoint: 2455 return llvm::ConstantInt::get(CGM.getLLVMContext(), 2456 Value.getFixedPoint().getValue()); 2457 case APValue::ComplexInt: { 2458 llvm::Constant *Complex[2]; 2459 2460 Complex[0] = llvm::ConstantInt::get(CGM.getLLVMContext(), 2461 Value.getComplexIntReal()); 2462 Complex[1] = llvm::ConstantInt::get(CGM.getLLVMContext(), 2463 Value.getComplexIntImag()); 2464 2465 // FIXME: the target may want to specify that this is packed. 2466 llvm::StructType *STy = 2467 llvm::StructType::get(Complex[0]->getType(), Complex[1]->getType()); 2468 return llvm::ConstantStruct::get(STy, Complex); 2469 } 2470 case APValue::Float: { 2471 const llvm::APFloat &Init = Value.getFloat(); 2472 if (&Init.getSemantics() == &llvm::APFloat::IEEEhalf() && 2473 !CGM.getContext().getLangOpts().NativeHalfType && 2474 CGM.getContext().getTargetInfo().useFP16ConversionIntrinsics()) 2475 return llvm::ConstantInt::get(CGM.getLLVMContext(), 2476 Init.bitcastToAPInt()); 2477 else 2478 return llvm::ConstantFP::get(CGM.getLLVMContext(), Init); 2479 } 2480 case APValue::ComplexFloat: { 2481 llvm::Constant *Complex[2]; 2482 2483 Complex[0] = llvm::ConstantFP::get(CGM.getLLVMContext(), 2484 Value.getComplexFloatReal()); 2485 Complex[1] = llvm::ConstantFP::get(CGM.getLLVMContext(), 2486 Value.getComplexFloatImag()); 2487 2488 // FIXME: the target may want to specify that this is packed. 2489 llvm::StructType *STy = 2490 llvm::StructType::get(Complex[0]->getType(), Complex[1]->getType()); 2491 return llvm::ConstantStruct::get(STy, Complex); 2492 } 2493 case APValue::Vector: { 2494 unsigned NumElts = Value.getVectorLength(); 2495 SmallVector<llvm::Constant *, 4> Inits(NumElts); 2496 2497 for (unsigned I = 0; I != NumElts; ++I) { 2498 const APValue &Elt = Value.getVectorElt(I); 2499 if (Elt.isInt()) 2500 Inits[I] = llvm::ConstantInt::get(CGM.getLLVMContext(), Elt.getInt()); 2501 else if (Elt.isFloat()) 2502 Inits[I] = llvm::ConstantFP::get(CGM.getLLVMContext(), Elt.getFloat()); 2503 else if (Elt.isIndeterminate()) 2504 Inits[I] = llvm::UndefValue::get(CGM.getTypes().ConvertType( 2505 DestType->castAs<VectorType>()->getElementType())); 2506 else 2507 llvm_unreachable("unsupported vector element type"); 2508 } 2509 return llvm::ConstantVector::get(Inits); 2510 } 2511 case APValue::AddrLabelDiff: { 2512 const AddrLabelExpr *LHSExpr = Value.getAddrLabelDiffLHS(); 2513 const AddrLabelExpr *RHSExpr = Value.getAddrLabelDiffRHS(); 2514 llvm::Constant *LHS = tryEmitPrivate(LHSExpr, LHSExpr->getType()); 2515 llvm::Constant *RHS = tryEmitPrivate(RHSExpr, RHSExpr->getType()); 2516 if (!LHS || !RHS) return nullptr; 2517 2518 // Compute difference 2519 llvm::Type *ResultType = CGM.getTypes().ConvertType(DestType); 2520 LHS = llvm::ConstantExpr::getPtrToInt(LHS, CGM.IntPtrTy); 2521 RHS = llvm::ConstantExpr::getPtrToInt(RHS, CGM.IntPtrTy); 2522 llvm::Constant *AddrLabelDiff = llvm::ConstantExpr::getSub(LHS, RHS); 2523 2524 // LLVM is a bit sensitive about the exact format of the 2525 // address-of-label difference; make sure to truncate after 2526 // the subtraction. 2527 return llvm::ConstantExpr::getTruncOrBitCast(AddrLabelDiff, ResultType); 2528 } 2529 case APValue::Struct: 2530 case APValue::Union: 2531 return ConstStructBuilder::BuildStruct(*this, Value, DestType); 2532 case APValue::Array: { 2533 const ArrayType *ArrayTy = CGM.getContext().getAsArrayType(DestType); 2534 unsigned NumElements = Value.getArraySize(); 2535 unsigned NumInitElts = Value.getArrayInitializedElts(); 2536 2537 // Emit array filler, if there is one. 2538 llvm::Constant *Filler = nullptr; 2539 if (Value.hasArrayFiller()) { 2540 Filler = tryEmitAbstractForMemory(Value.getArrayFiller(), 2541 ArrayTy->getElementType()); 2542 if (!Filler) 2543 return nullptr; 2544 } 2545 2546 // Emit initializer elements. 2547 SmallVector<llvm::Constant*, 16> Elts; 2548 if (Filler && Filler->isNullValue()) 2549 Elts.reserve(NumInitElts + 1); 2550 else 2551 Elts.reserve(NumElements); 2552 2553 llvm::Type *CommonElementType = nullptr; 2554 for (unsigned I = 0; I < NumInitElts; ++I) { 2555 llvm::Constant *C = tryEmitPrivateForMemory( 2556 Value.getArrayInitializedElt(I), ArrayTy->getElementType()); 2557 if (!C) return nullptr; 2558 2559 if (I == 0) 2560 CommonElementType = C->getType(); 2561 else if (C->getType() != CommonElementType) 2562 CommonElementType = nullptr; 2563 Elts.push_back(C); 2564 } 2565 2566 llvm::ArrayType *Desired = 2567 cast<llvm::ArrayType>(CGM.getTypes().ConvertType(DestType)); 2568 2569 // Fix the type of incomplete arrays if the initializer isn't empty. 2570 if (DestType->isIncompleteArrayType() && !Elts.empty()) 2571 Desired = llvm::ArrayType::get(Desired->getElementType(), Elts.size()); 2572 2573 return EmitArrayConstant(CGM, Desired, CommonElementType, NumElements, Elts, 2574 Filler); 2575 } 2576 case APValue::MemberPointer: 2577 return CGM.getCXXABI().EmitMemberPointer(Value, DestType); 2578 } 2579 llvm_unreachable("Unknown APValue kind"); 2580 } 2581 2582 llvm::GlobalVariable *CodeGenModule::getAddrOfConstantCompoundLiteralIfEmitted( 2583 const CompoundLiteralExpr *E) { 2584 return EmittedCompoundLiterals.lookup(E); 2585 } 2586 2587 void CodeGenModule::setAddrOfConstantCompoundLiteral( 2588 const CompoundLiteralExpr *CLE, llvm::GlobalVariable *GV) { 2589 bool Ok = EmittedCompoundLiterals.insert(std::make_pair(CLE, GV)).second; 2590 (void)Ok; 2591 assert(Ok && "CLE has already been emitted!"); 2592 } 2593 2594 ConstantAddress 2595 CodeGenModule::GetAddrOfConstantCompoundLiteral(const CompoundLiteralExpr *E) { 2596 assert(E->isFileScope() && "not a file-scope compound literal expr"); 2597 ConstantEmitter emitter(*this); 2598 return tryEmitGlobalCompoundLiteral(emitter, E); 2599 } 2600 2601 llvm::Constant * 2602 CodeGenModule::getMemberPointerConstant(const UnaryOperator *uo) { 2603 // Member pointer constants always have a very particular form. 2604 const MemberPointerType *type = cast<MemberPointerType>(uo->getType()); 2605 const ValueDecl *decl = cast<DeclRefExpr>(uo->getSubExpr())->getDecl(); 2606 2607 // A member function pointer. 2608 if (const CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(decl)) 2609 return getCXXABI().EmitMemberFunctionPointer(method); 2610 2611 // Otherwise, a member data pointer. 2612 uint64_t fieldOffset = getContext().getFieldOffset(decl); 2613 CharUnits chars = getContext().toCharUnitsFromBits((int64_t) fieldOffset); 2614 return getCXXABI().EmitMemberDataPointer(type, chars); 2615 } 2616 2617 static llvm::Constant *EmitNullConstantForBase(CodeGenModule &CGM, 2618 llvm::Type *baseType, 2619 const CXXRecordDecl *base); 2620 2621 static llvm::Constant *EmitNullConstant(CodeGenModule &CGM, 2622 const RecordDecl *record, 2623 bool asCompleteObject) { 2624 const CGRecordLayout &layout = CGM.getTypes().getCGRecordLayout(record); 2625 llvm::StructType *structure = 2626 (asCompleteObject ? layout.getLLVMType() 2627 : layout.getBaseSubobjectLLVMType()); 2628 2629 unsigned numElements = structure->getNumElements(); 2630 std::vector<llvm::Constant *> elements(numElements); 2631 2632 auto CXXR = dyn_cast<CXXRecordDecl>(record); 2633 // Fill in all the bases. 2634 if (CXXR) { 2635 for (const auto &I : CXXR->bases()) { 2636 if (I.isVirtual()) { 2637 // Ignore virtual bases; if we're laying out for a complete 2638 // object, we'll lay these out later. 2639 continue; 2640 } 2641 2642 const CXXRecordDecl *base = 2643 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl()); 2644 2645 // Ignore empty bases. 2646 if (isEmptyRecordForLayout(CGM.getContext(), I.getType()) || 2647 CGM.getContext() 2648 .getASTRecordLayout(base) 2649 .getNonVirtualSize() 2650 .isZero()) 2651 continue; 2652 2653 unsigned fieldIndex = layout.getNonVirtualBaseLLVMFieldNo(base); 2654 llvm::Type *baseType = structure->getElementType(fieldIndex); 2655 elements[fieldIndex] = EmitNullConstantForBase(CGM, baseType, base); 2656 } 2657 } 2658 2659 // Fill in all the fields. 2660 for (const auto *Field : record->fields()) { 2661 // Fill in non-bitfields. (Bitfields always use a zero pattern, which we 2662 // will fill in later.) 2663 if (!Field->isBitField() && 2664 !isEmptyFieldForLayout(CGM.getContext(), Field)) { 2665 unsigned fieldIndex = layout.getLLVMFieldNo(Field); 2666 elements[fieldIndex] = CGM.EmitNullConstant(Field->getType()); 2667 } 2668 2669 // For unions, stop after the first named field. 2670 if (record->isUnion()) { 2671 if (Field->getIdentifier()) 2672 break; 2673 if (const auto *FieldRD = Field->getType()->getAsRecordDecl()) 2674 if (FieldRD->findFirstNamedDataMember()) 2675 break; 2676 } 2677 } 2678 2679 // Fill in the virtual bases, if we're working with the complete object. 2680 if (CXXR && asCompleteObject) { 2681 for (const auto &I : CXXR->vbases()) { 2682 const CXXRecordDecl *base = 2683 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl()); 2684 2685 // Ignore empty bases. 2686 if (isEmptyRecordForLayout(CGM.getContext(), I.getType())) 2687 continue; 2688 2689 unsigned fieldIndex = layout.getVirtualBaseIndex(base); 2690 2691 // We might have already laid this field out. 2692 if (elements[fieldIndex]) continue; 2693 2694 llvm::Type *baseType = structure->getElementType(fieldIndex); 2695 elements[fieldIndex] = EmitNullConstantForBase(CGM, baseType, base); 2696 } 2697 } 2698 2699 // Now go through all other fields and zero them out. 2700 for (unsigned i = 0; i != numElements; ++i) { 2701 if (!elements[i]) 2702 elements[i] = llvm::Constant::getNullValue(structure->getElementType(i)); 2703 } 2704 2705 return llvm::ConstantStruct::get(structure, elements); 2706 } 2707 2708 /// Emit the null constant for a base subobject. 2709 static llvm::Constant *EmitNullConstantForBase(CodeGenModule &CGM, 2710 llvm::Type *baseType, 2711 const CXXRecordDecl *base) { 2712 const CGRecordLayout &baseLayout = CGM.getTypes().getCGRecordLayout(base); 2713 2714 // Just zero out bases that don't have any pointer to data members. 2715 if (baseLayout.isZeroInitializableAsBase()) 2716 return llvm::Constant::getNullValue(baseType); 2717 2718 // Otherwise, we can just use its null constant. 2719 return EmitNullConstant(CGM, base, /*asCompleteObject=*/false); 2720 } 2721 2722 llvm::Constant *ConstantEmitter::emitNullForMemory(CodeGenModule &CGM, 2723 QualType T) { 2724 return emitForMemory(CGM, CGM.EmitNullConstant(T), T); 2725 } 2726 2727 llvm::Constant *CodeGenModule::EmitNullConstant(QualType T) { 2728 if (T->getAs<PointerType>()) 2729 return getNullPointer( 2730 cast<llvm::PointerType>(getTypes().ConvertTypeForMem(T)), T); 2731 2732 if (getTypes().isZeroInitializable(T)) 2733 return llvm::Constant::getNullValue(getTypes().ConvertTypeForMem(T)); 2734 2735 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(T)) { 2736 llvm::ArrayType *ATy = 2737 cast<llvm::ArrayType>(getTypes().ConvertTypeForMem(T)); 2738 2739 QualType ElementTy = CAT->getElementType(); 2740 2741 llvm::Constant *Element = 2742 ConstantEmitter::emitNullForMemory(*this, ElementTy); 2743 unsigned NumElements = CAT->getZExtSize(); 2744 SmallVector<llvm::Constant *, 8> Array(NumElements, Element); 2745 return llvm::ConstantArray::get(ATy, Array); 2746 } 2747 2748 if (const RecordType *RT = T->getAs<RecordType>()) 2749 return ::EmitNullConstant(*this, RT->getDecl(), /*complete object*/ true); 2750 2751 assert(T->isMemberDataPointerType() && 2752 "Should only see pointers to data members here!"); 2753 2754 return getCXXABI().EmitNullMemberPointer(T->castAs<MemberPointerType>()); 2755 } 2756 2757 llvm::Constant * 2758 CodeGenModule::EmitNullConstantForBase(const CXXRecordDecl *Record) { 2759 return ::EmitNullConstant(*this, Record, false); 2760 } 2761