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