1 //===--- CGExprConstant.cpp - Emit LLVM Code from Constant Expressions ----===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This contains code to emit Constant Expr nodes as LLVM code. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "CodeGenFunction.h" 15 #include "CGCXXABI.h" 16 #include "CGObjCRuntime.h" 17 #include "CGRecordLayout.h" 18 #include "CodeGenModule.h" 19 #include "TargetInfo.h" 20 #include "clang/AST/APValue.h" 21 #include "clang/AST/ASTContext.h" 22 #include "clang/AST/RecordLayout.h" 23 #include "clang/AST/StmtVisitor.h" 24 #include "clang/Basic/Builtins.h" 25 #include "llvm/IR/Constants.h" 26 #include "llvm/IR/DataLayout.h" 27 #include "llvm/IR/Function.h" 28 #include "llvm/IR/GlobalVariable.h" 29 using namespace clang; 30 using namespace CodeGen; 31 32 //===----------------------------------------------------------------------===// 33 // ConstStructBuilder 34 //===----------------------------------------------------------------------===// 35 36 namespace { 37 class ConstExprEmitter; 38 class ConstStructBuilder { 39 CodeGenModule &CGM; 40 CodeGenFunction *CGF; 41 42 bool Packed; 43 CharUnits NextFieldOffsetInChars; 44 CharUnits LLVMStructAlignment; 45 SmallVector<llvm::Constant *, 32> Elements; 46 public: 47 static llvm::Constant *BuildStruct(CodeGenModule &CGM, CodeGenFunction *CFG, 48 ConstExprEmitter *Emitter, 49 llvm::ConstantStruct *Base, 50 InitListExpr *Updater); 51 static llvm::Constant *BuildStruct(CodeGenModule &CGM, CodeGenFunction *CGF, 52 InitListExpr *ILE); 53 static llvm::Constant *BuildStruct(CodeGenModule &CGM, CodeGenFunction *CGF, 54 const APValue &Value, QualType ValTy); 55 56 private: 57 ConstStructBuilder(CodeGenModule &CGM, CodeGenFunction *CGF) 58 : CGM(CGM), CGF(CGF), Packed(false), 59 NextFieldOffsetInChars(CharUnits::Zero()), 60 LLVMStructAlignment(CharUnits::One()) { } 61 62 void AppendField(const FieldDecl *Field, uint64_t FieldOffset, 63 llvm::Constant *InitExpr); 64 65 void AppendBytes(CharUnits FieldOffsetInChars, llvm::Constant *InitCst); 66 67 void AppendBitField(const FieldDecl *Field, uint64_t FieldOffset, 68 llvm::ConstantInt *InitExpr); 69 70 void AppendPadding(CharUnits PadSize); 71 72 void AppendTailPadding(CharUnits RecordSize); 73 74 void ConvertStructToPacked(); 75 76 bool Build(InitListExpr *ILE); 77 bool Build(ConstExprEmitter *Emitter, llvm::ConstantStruct *Base, 78 InitListExpr *Updater); 79 void Build(const APValue &Val, const RecordDecl *RD, bool IsPrimaryBase, 80 const CXXRecordDecl *VTableClass, CharUnits BaseOffset); 81 llvm::Constant *Finalize(QualType Ty); 82 83 CharUnits getAlignment(const llvm::Constant *C) const { 84 if (Packed) return CharUnits::One(); 85 return CharUnits::fromQuantity( 86 CGM.getDataLayout().getABITypeAlignment(C->getType())); 87 } 88 89 CharUnits getSizeInChars(const llvm::Constant *C) const { 90 return CharUnits::fromQuantity( 91 CGM.getDataLayout().getTypeAllocSize(C->getType())); 92 } 93 }; 94 95 void ConstStructBuilder:: 96 AppendField(const FieldDecl *Field, uint64_t FieldOffset, 97 llvm::Constant *InitCst) { 98 const ASTContext &Context = CGM.getContext(); 99 100 CharUnits FieldOffsetInChars = Context.toCharUnitsFromBits(FieldOffset); 101 102 AppendBytes(FieldOffsetInChars, InitCst); 103 } 104 105 void ConstStructBuilder:: 106 AppendBytes(CharUnits FieldOffsetInChars, llvm::Constant *InitCst) { 107 108 assert(NextFieldOffsetInChars <= FieldOffsetInChars 109 && "Field offset mismatch!"); 110 111 CharUnits FieldAlignment = getAlignment(InitCst); 112 113 // Round up the field offset to the alignment of the field type. 114 CharUnits AlignedNextFieldOffsetInChars = 115 NextFieldOffsetInChars.alignTo(FieldAlignment); 116 117 if (AlignedNextFieldOffsetInChars < FieldOffsetInChars) { 118 // We need to append padding. 119 AppendPadding(FieldOffsetInChars - NextFieldOffsetInChars); 120 121 assert(NextFieldOffsetInChars == FieldOffsetInChars && 122 "Did not add enough padding!"); 123 124 AlignedNextFieldOffsetInChars = 125 NextFieldOffsetInChars.alignTo(FieldAlignment); 126 } 127 128 if (AlignedNextFieldOffsetInChars > FieldOffsetInChars) { 129 assert(!Packed && "Alignment is wrong even with a packed struct!"); 130 131 // Convert the struct to a packed struct. 132 ConvertStructToPacked(); 133 134 // After we pack the struct, we may need to insert padding. 135 if (NextFieldOffsetInChars < FieldOffsetInChars) { 136 // We need to append padding. 137 AppendPadding(FieldOffsetInChars - NextFieldOffsetInChars); 138 139 assert(NextFieldOffsetInChars == FieldOffsetInChars && 140 "Did not add enough padding!"); 141 } 142 AlignedNextFieldOffsetInChars = NextFieldOffsetInChars; 143 } 144 145 // Add the field. 146 Elements.push_back(InitCst); 147 NextFieldOffsetInChars = AlignedNextFieldOffsetInChars + 148 getSizeInChars(InitCst); 149 150 if (Packed) 151 assert(LLVMStructAlignment == CharUnits::One() && 152 "Packed struct not byte-aligned!"); 153 else 154 LLVMStructAlignment = std::max(LLVMStructAlignment, FieldAlignment); 155 } 156 157 void ConstStructBuilder::AppendBitField(const FieldDecl *Field, 158 uint64_t FieldOffset, 159 llvm::ConstantInt *CI) { 160 const ASTContext &Context = CGM.getContext(); 161 const uint64_t CharWidth = Context.getCharWidth(); 162 uint64_t NextFieldOffsetInBits = Context.toBits(NextFieldOffsetInChars); 163 if (FieldOffset > NextFieldOffsetInBits) { 164 // We need to add padding. 165 CharUnits PadSize = Context.toCharUnitsFromBits( 166 llvm::alignTo(FieldOffset - NextFieldOffsetInBits, 167 Context.getTargetInfo().getCharAlign())); 168 169 AppendPadding(PadSize); 170 } 171 172 uint64_t FieldSize = Field->getBitWidthValue(Context); 173 174 llvm::APInt FieldValue = CI->getValue(); 175 176 // Promote the size of FieldValue if necessary 177 // FIXME: This should never occur, but currently it can because initializer 178 // constants are cast to bool, and because clang is not enforcing bitfield 179 // width limits. 180 if (FieldSize > FieldValue.getBitWidth()) 181 FieldValue = FieldValue.zext(FieldSize); 182 183 // Truncate the size of FieldValue to the bit field size. 184 if (FieldSize < FieldValue.getBitWidth()) 185 FieldValue = FieldValue.trunc(FieldSize); 186 187 NextFieldOffsetInBits = Context.toBits(NextFieldOffsetInChars); 188 if (FieldOffset < NextFieldOffsetInBits) { 189 // Either part of the field or the entire field can go into the previous 190 // byte. 191 assert(!Elements.empty() && "Elements can't be empty!"); 192 193 unsigned BitsInPreviousByte = NextFieldOffsetInBits - FieldOffset; 194 195 bool FitsCompletelyInPreviousByte = 196 BitsInPreviousByte >= FieldValue.getBitWidth(); 197 198 llvm::APInt Tmp = FieldValue; 199 200 if (!FitsCompletelyInPreviousByte) { 201 unsigned NewFieldWidth = FieldSize - BitsInPreviousByte; 202 203 if (CGM.getDataLayout().isBigEndian()) { 204 Tmp = Tmp.lshr(NewFieldWidth); 205 Tmp = Tmp.trunc(BitsInPreviousByte); 206 207 // We want the remaining high bits. 208 FieldValue = FieldValue.trunc(NewFieldWidth); 209 } else { 210 Tmp = Tmp.trunc(BitsInPreviousByte); 211 212 // We want the remaining low bits. 213 FieldValue = FieldValue.lshr(BitsInPreviousByte); 214 FieldValue = FieldValue.trunc(NewFieldWidth); 215 } 216 } 217 218 Tmp = Tmp.zext(CharWidth); 219 if (CGM.getDataLayout().isBigEndian()) { 220 if (FitsCompletelyInPreviousByte) 221 Tmp = Tmp.shl(BitsInPreviousByte - FieldValue.getBitWidth()); 222 } else { 223 Tmp = Tmp.shl(CharWidth - BitsInPreviousByte); 224 } 225 226 // 'or' in the bits that go into the previous byte. 227 llvm::Value *LastElt = Elements.back(); 228 if (llvm::ConstantInt *Val = dyn_cast<llvm::ConstantInt>(LastElt)) 229 Tmp |= Val->getValue(); 230 else { 231 assert(isa<llvm::UndefValue>(LastElt)); 232 // If there is an undef field that we're adding to, it can either be a 233 // scalar undef (in which case, we just replace it with our field) or it 234 // is an array. If it is an array, we have to pull one byte off the 235 // array so that the other undef bytes stay around. 236 if (!isa<llvm::IntegerType>(LastElt->getType())) { 237 // The undef padding will be a multibyte array, create a new smaller 238 // padding and then an hole for our i8 to get plopped into. 239 assert(isa<llvm::ArrayType>(LastElt->getType()) && 240 "Expected array padding of undefs"); 241 llvm::ArrayType *AT = cast<llvm::ArrayType>(LastElt->getType()); 242 assert(AT->getElementType()->isIntegerTy(CharWidth) && 243 AT->getNumElements() != 0 && 244 "Expected non-empty array padding of undefs"); 245 246 // Remove the padding array. 247 NextFieldOffsetInChars -= CharUnits::fromQuantity(AT->getNumElements()); 248 Elements.pop_back(); 249 250 // Add the padding back in two chunks. 251 AppendPadding(CharUnits::fromQuantity(AT->getNumElements()-1)); 252 AppendPadding(CharUnits::One()); 253 assert(isa<llvm::UndefValue>(Elements.back()) && 254 Elements.back()->getType()->isIntegerTy(CharWidth) && 255 "Padding addition didn't work right"); 256 } 257 } 258 259 Elements.back() = llvm::ConstantInt::get(CGM.getLLVMContext(), Tmp); 260 261 if (FitsCompletelyInPreviousByte) 262 return; 263 } 264 265 while (FieldValue.getBitWidth() > CharWidth) { 266 llvm::APInt Tmp; 267 268 if (CGM.getDataLayout().isBigEndian()) { 269 // We want the high bits. 270 Tmp = 271 FieldValue.lshr(FieldValue.getBitWidth() - CharWidth).trunc(CharWidth); 272 } else { 273 // We want the low bits. 274 Tmp = FieldValue.trunc(CharWidth); 275 276 FieldValue = FieldValue.lshr(CharWidth); 277 } 278 279 Elements.push_back(llvm::ConstantInt::get(CGM.getLLVMContext(), Tmp)); 280 ++NextFieldOffsetInChars; 281 282 FieldValue = FieldValue.trunc(FieldValue.getBitWidth() - CharWidth); 283 } 284 285 assert(FieldValue.getBitWidth() > 0 && 286 "Should have at least one bit left!"); 287 assert(FieldValue.getBitWidth() <= CharWidth && 288 "Should not have more than a byte left!"); 289 290 if (FieldValue.getBitWidth() < CharWidth) { 291 if (CGM.getDataLayout().isBigEndian()) { 292 unsigned BitWidth = FieldValue.getBitWidth(); 293 294 FieldValue = FieldValue.zext(CharWidth) << (CharWidth - BitWidth); 295 } else 296 FieldValue = FieldValue.zext(CharWidth); 297 } 298 299 // Append the last element. 300 Elements.push_back(llvm::ConstantInt::get(CGM.getLLVMContext(), 301 FieldValue)); 302 ++NextFieldOffsetInChars; 303 } 304 305 void ConstStructBuilder::AppendPadding(CharUnits PadSize) { 306 if (PadSize.isZero()) 307 return; 308 309 llvm::Type *Ty = CGM.Int8Ty; 310 if (PadSize > CharUnits::One()) 311 Ty = llvm::ArrayType::get(Ty, PadSize.getQuantity()); 312 313 llvm::Constant *C = llvm::UndefValue::get(Ty); 314 Elements.push_back(C); 315 assert(getAlignment(C) == CharUnits::One() && 316 "Padding must have 1 byte alignment!"); 317 318 NextFieldOffsetInChars += getSizeInChars(C); 319 } 320 321 void ConstStructBuilder::AppendTailPadding(CharUnits RecordSize) { 322 assert(NextFieldOffsetInChars <= RecordSize && 323 "Size mismatch!"); 324 325 AppendPadding(RecordSize - NextFieldOffsetInChars); 326 } 327 328 void ConstStructBuilder::ConvertStructToPacked() { 329 SmallVector<llvm::Constant *, 16> PackedElements; 330 CharUnits ElementOffsetInChars = CharUnits::Zero(); 331 332 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 333 llvm::Constant *C = Elements[i]; 334 335 CharUnits ElementAlign = CharUnits::fromQuantity( 336 CGM.getDataLayout().getABITypeAlignment(C->getType())); 337 CharUnits AlignedElementOffsetInChars = 338 ElementOffsetInChars.alignTo(ElementAlign); 339 340 if (AlignedElementOffsetInChars > ElementOffsetInChars) { 341 // We need some padding. 342 CharUnits NumChars = 343 AlignedElementOffsetInChars - ElementOffsetInChars; 344 345 llvm::Type *Ty = CGM.Int8Ty; 346 if (NumChars > CharUnits::One()) 347 Ty = llvm::ArrayType::get(Ty, NumChars.getQuantity()); 348 349 llvm::Constant *Padding = llvm::UndefValue::get(Ty); 350 PackedElements.push_back(Padding); 351 ElementOffsetInChars += getSizeInChars(Padding); 352 } 353 354 PackedElements.push_back(C); 355 ElementOffsetInChars += getSizeInChars(C); 356 } 357 358 assert(ElementOffsetInChars == NextFieldOffsetInChars && 359 "Packing the struct changed its size!"); 360 361 Elements.swap(PackedElements); 362 LLVMStructAlignment = CharUnits::One(); 363 Packed = true; 364 } 365 366 bool ConstStructBuilder::Build(InitListExpr *ILE) { 367 RecordDecl *RD = ILE->getType()->getAs<RecordType>()->getDecl(); 368 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD); 369 370 unsigned FieldNo = 0; 371 unsigned ElementNo = 0; 372 373 // Bail out if we have base classes. We could support these, but they only 374 // arise in C++1z where we will have already constant folded most interesting 375 // cases. FIXME: There are still a few more cases we can handle this way. 376 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 377 if (CXXRD->getNumBases()) 378 return false; 379 380 for (RecordDecl::field_iterator Field = RD->field_begin(), 381 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field, ++FieldNo) { 382 // If this is a union, skip all the fields that aren't being initialized. 383 if (RD->isUnion() && ILE->getInitializedFieldInUnion() != *Field) 384 continue; 385 386 // Don't emit anonymous bitfields, they just affect layout. 387 if (Field->isUnnamedBitfield()) 388 continue; 389 390 // Get the initializer. A struct can include fields without initializers, 391 // we just use explicit null values for them. 392 llvm::Constant *EltInit; 393 if (ElementNo < ILE->getNumInits()) 394 EltInit = CGM.EmitConstantExpr(ILE->getInit(ElementNo++), 395 Field->getType(), CGF); 396 else 397 EltInit = CGM.EmitNullConstant(Field->getType()); 398 399 if (!EltInit) 400 return false; 401 402 if (!Field->isBitField()) { 403 // Handle non-bitfield members. 404 AppendField(*Field, Layout.getFieldOffset(FieldNo), EltInit); 405 } else { 406 // Otherwise we have a bitfield. 407 if (auto *CI = dyn_cast<llvm::ConstantInt>(EltInit)) { 408 AppendBitField(*Field, Layout.getFieldOffset(FieldNo), CI); 409 } else { 410 // We are trying to initialize a bitfield with a non-trivial constant, 411 // this must require run-time code. 412 return false; 413 } 414 } 415 } 416 417 return true; 418 } 419 420 namespace { 421 struct BaseInfo { 422 BaseInfo(const CXXRecordDecl *Decl, CharUnits Offset, unsigned Index) 423 : Decl(Decl), Offset(Offset), Index(Index) { 424 } 425 426 const CXXRecordDecl *Decl; 427 CharUnits Offset; 428 unsigned Index; 429 430 bool operator<(const BaseInfo &O) const { return Offset < O.Offset; } 431 }; 432 } 433 434 void ConstStructBuilder::Build(const APValue &Val, const RecordDecl *RD, 435 bool IsPrimaryBase, 436 const CXXRecordDecl *VTableClass, 437 CharUnits Offset) { 438 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD); 439 440 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) { 441 // Add a vtable pointer, if we need one and it hasn't already been added. 442 if (CD->isDynamicClass() && !IsPrimaryBase) { 443 llvm::Constant *VTableAddressPoint = 444 CGM.getCXXABI().getVTableAddressPointForConstExpr( 445 BaseSubobject(CD, Offset), VTableClass); 446 AppendBytes(Offset, VTableAddressPoint); 447 } 448 449 // Accumulate and sort bases, in order to visit them in address order, which 450 // may not be the same as declaration order. 451 SmallVector<BaseInfo, 8> Bases; 452 Bases.reserve(CD->getNumBases()); 453 unsigned BaseNo = 0; 454 for (CXXRecordDecl::base_class_const_iterator Base = CD->bases_begin(), 455 BaseEnd = CD->bases_end(); Base != BaseEnd; ++Base, ++BaseNo) { 456 assert(!Base->isVirtual() && "should not have virtual bases here"); 457 const CXXRecordDecl *BD = Base->getType()->getAsCXXRecordDecl(); 458 CharUnits BaseOffset = Layout.getBaseClassOffset(BD); 459 Bases.push_back(BaseInfo(BD, BaseOffset, BaseNo)); 460 } 461 std::stable_sort(Bases.begin(), Bases.end()); 462 463 for (unsigned I = 0, N = Bases.size(); I != N; ++I) { 464 BaseInfo &Base = Bases[I]; 465 466 bool IsPrimaryBase = Layout.getPrimaryBase() == Base.Decl; 467 Build(Val.getStructBase(Base.Index), Base.Decl, IsPrimaryBase, 468 VTableClass, Offset + Base.Offset); 469 } 470 } 471 472 unsigned FieldNo = 0; 473 uint64_t OffsetBits = CGM.getContext().toBits(Offset); 474 475 for (RecordDecl::field_iterator Field = RD->field_begin(), 476 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field, ++FieldNo) { 477 // If this is a union, skip all the fields that aren't being initialized. 478 if (RD->isUnion() && Val.getUnionField() != *Field) 479 continue; 480 481 // Don't emit anonymous bitfields, they just affect layout. 482 if (Field->isUnnamedBitfield()) 483 continue; 484 485 // Emit the value of the initializer. 486 const APValue &FieldValue = 487 RD->isUnion() ? Val.getUnionValue() : Val.getStructField(FieldNo); 488 llvm::Constant *EltInit = 489 CGM.EmitConstantValueForMemory(FieldValue, Field->getType(), CGF); 490 assert(EltInit && "EmitConstantValue can't fail"); 491 492 if (!Field->isBitField()) { 493 // Handle non-bitfield members. 494 AppendField(*Field, Layout.getFieldOffset(FieldNo) + OffsetBits, EltInit); 495 } else { 496 // Otherwise we have a bitfield. 497 AppendBitField(*Field, Layout.getFieldOffset(FieldNo) + OffsetBits, 498 cast<llvm::ConstantInt>(EltInit)); 499 } 500 } 501 } 502 503 llvm::Constant *ConstStructBuilder::Finalize(QualType Ty) { 504 RecordDecl *RD = Ty->getAs<RecordType>()->getDecl(); 505 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD); 506 507 CharUnits LayoutSizeInChars = Layout.getSize(); 508 509 if (NextFieldOffsetInChars > LayoutSizeInChars) { 510 // If the struct is bigger than the size of the record type, 511 // we must have a flexible array member at the end. 512 assert(RD->hasFlexibleArrayMember() && 513 "Must have flexible array member if struct is bigger than type!"); 514 515 // No tail padding is necessary. 516 } else { 517 // Append tail padding if necessary. 518 CharUnits LLVMSizeInChars = 519 NextFieldOffsetInChars.alignTo(LLVMStructAlignment); 520 521 if (LLVMSizeInChars != LayoutSizeInChars) 522 AppendTailPadding(LayoutSizeInChars); 523 524 LLVMSizeInChars = NextFieldOffsetInChars.alignTo(LLVMStructAlignment); 525 526 // Check if we need to convert the struct to a packed struct. 527 if (NextFieldOffsetInChars <= LayoutSizeInChars && 528 LLVMSizeInChars > LayoutSizeInChars) { 529 assert(!Packed && "Size mismatch!"); 530 531 ConvertStructToPacked(); 532 assert(NextFieldOffsetInChars <= LayoutSizeInChars && 533 "Converting to packed did not help!"); 534 } 535 536 LLVMSizeInChars = NextFieldOffsetInChars.alignTo(LLVMStructAlignment); 537 538 assert(LayoutSizeInChars == LLVMSizeInChars && 539 "Tail padding mismatch!"); 540 } 541 542 // Pick the type to use. If the type is layout identical to the ConvertType 543 // type then use it, otherwise use whatever the builder produced for us. 544 llvm::StructType *STy = 545 llvm::ConstantStruct::getTypeForElements(CGM.getLLVMContext(), 546 Elements, Packed); 547 llvm::Type *ValTy = CGM.getTypes().ConvertType(Ty); 548 if (llvm::StructType *ValSTy = dyn_cast<llvm::StructType>(ValTy)) { 549 if (ValSTy->isLayoutIdentical(STy)) 550 STy = ValSTy; 551 } 552 553 llvm::Constant *Result = llvm::ConstantStruct::get(STy, Elements); 554 555 assert(NextFieldOffsetInChars.alignTo(getAlignment(Result)) == 556 getSizeInChars(Result) && 557 "Size mismatch!"); 558 559 return Result; 560 } 561 562 llvm::Constant *ConstStructBuilder::BuildStruct(CodeGenModule &CGM, 563 CodeGenFunction *CGF, 564 ConstExprEmitter *Emitter, 565 llvm::ConstantStruct *Base, 566 InitListExpr *Updater) { 567 ConstStructBuilder Builder(CGM, CGF); 568 if (!Builder.Build(Emitter, Base, Updater)) 569 return nullptr; 570 return Builder.Finalize(Updater->getType()); 571 } 572 573 llvm::Constant *ConstStructBuilder::BuildStruct(CodeGenModule &CGM, 574 CodeGenFunction *CGF, 575 InitListExpr *ILE) { 576 ConstStructBuilder Builder(CGM, CGF); 577 578 if (!Builder.Build(ILE)) 579 return nullptr; 580 581 return Builder.Finalize(ILE->getType()); 582 } 583 584 llvm::Constant *ConstStructBuilder::BuildStruct(CodeGenModule &CGM, 585 CodeGenFunction *CGF, 586 const APValue &Val, 587 QualType ValTy) { 588 ConstStructBuilder Builder(CGM, CGF); 589 590 const RecordDecl *RD = ValTy->castAs<RecordType>()->getDecl(); 591 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD); 592 Builder.Build(Val, RD, false, CD, CharUnits::Zero()); 593 594 return Builder.Finalize(ValTy); 595 } 596 597 598 //===----------------------------------------------------------------------===// 599 // ConstExprEmitter 600 //===----------------------------------------------------------------------===// 601 602 /// This class only needs to handle two cases: 603 /// 1) Literals (this is used by APValue emission to emit literals). 604 /// 2) Arrays, structs and unions (outside C++11 mode, we don't currently 605 /// constant fold these types). 606 class ConstExprEmitter : 607 public StmtVisitor<ConstExprEmitter, llvm::Constant*> { 608 CodeGenModule &CGM; 609 CodeGenFunction *CGF; 610 llvm::LLVMContext &VMContext; 611 public: 612 ConstExprEmitter(CodeGenModule &cgm, CodeGenFunction *cgf) 613 : CGM(cgm), CGF(cgf), VMContext(cgm.getLLVMContext()) { 614 } 615 616 //===--------------------------------------------------------------------===// 617 // Visitor Methods 618 //===--------------------------------------------------------------------===// 619 620 llvm::Constant *VisitStmt(Stmt *S) { 621 return nullptr; 622 } 623 624 llvm::Constant *VisitParenExpr(ParenExpr *PE) { 625 return Visit(PE->getSubExpr()); 626 } 627 628 llvm::Constant * 629 VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *PE) { 630 return Visit(PE->getReplacement()); 631 } 632 633 llvm::Constant *VisitGenericSelectionExpr(GenericSelectionExpr *GE) { 634 return Visit(GE->getResultExpr()); 635 } 636 637 llvm::Constant *VisitChooseExpr(ChooseExpr *CE) { 638 return Visit(CE->getChosenSubExpr()); 639 } 640 641 llvm::Constant *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) { 642 return Visit(E->getInitializer()); 643 } 644 645 llvm::Constant *VisitCastExpr(CastExpr* E) { 646 if (const auto *ECE = dyn_cast<ExplicitCastExpr>(E)) 647 CGM.EmitExplicitCastExprType(ECE, CGF); 648 Expr *subExpr = E->getSubExpr(); 649 llvm::Constant *C = CGM.EmitConstantExpr(subExpr, subExpr->getType(), CGF); 650 if (!C) return nullptr; 651 652 llvm::Type *destType = ConvertType(E->getType()); 653 654 switch (E->getCastKind()) { 655 case CK_ToUnion: { 656 // GCC cast to union extension 657 assert(E->getType()->isUnionType() && 658 "Destination type is not union type!"); 659 660 // Build a struct with the union sub-element as the first member, 661 // and padded to the appropriate size 662 SmallVector<llvm::Constant*, 2> Elts; 663 SmallVector<llvm::Type*, 2> Types; 664 Elts.push_back(C); 665 Types.push_back(C->getType()); 666 unsigned CurSize = CGM.getDataLayout().getTypeAllocSize(C->getType()); 667 unsigned TotalSize = CGM.getDataLayout().getTypeAllocSize(destType); 668 669 assert(CurSize <= TotalSize && "Union size mismatch!"); 670 if (unsigned NumPadBytes = TotalSize - CurSize) { 671 llvm::Type *Ty = CGM.Int8Ty; 672 if (NumPadBytes > 1) 673 Ty = llvm::ArrayType::get(Ty, NumPadBytes); 674 675 Elts.push_back(llvm::UndefValue::get(Ty)); 676 Types.push_back(Ty); 677 } 678 679 llvm::StructType* STy = 680 llvm::StructType::get(C->getType()->getContext(), Types, false); 681 return llvm::ConstantStruct::get(STy, Elts); 682 } 683 684 case CK_AddressSpaceConversion: 685 return llvm::ConstantExpr::getAddrSpaceCast(C, destType); 686 687 case CK_LValueToRValue: 688 case CK_AtomicToNonAtomic: 689 case CK_NonAtomicToAtomic: 690 case CK_NoOp: 691 case CK_ConstructorConversion: 692 return C; 693 694 case CK_IntToOCLSampler: 695 llvm_unreachable("global sampler variables are not generated"); 696 697 case CK_Dependent: llvm_unreachable("saw dependent cast!"); 698 699 case CK_BuiltinFnToFnPtr: 700 llvm_unreachable("builtin functions are handled elsewhere"); 701 702 case CK_ReinterpretMemberPointer: 703 case CK_DerivedToBaseMemberPointer: 704 case CK_BaseToDerivedMemberPointer: 705 return CGM.getCXXABI().EmitMemberPointerConversion(E, C); 706 707 // These will never be supported. 708 case CK_ObjCObjectLValueCast: 709 case CK_ARCProduceObject: 710 case CK_ARCConsumeObject: 711 case CK_ARCReclaimReturnedObject: 712 case CK_ARCExtendBlockObject: 713 case CK_CopyAndAutoreleaseBlockObject: 714 return nullptr; 715 716 // These don't need to be handled here because Evaluate knows how to 717 // evaluate them in the cases where they can be folded. 718 case CK_BitCast: 719 case CK_ToVoid: 720 case CK_Dynamic: 721 case CK_LValueBitCast: 722 case CK_NullToMemberPointer: 723 case CK_UserDefinedConversion: 724 case CK_CPointerToObjCPointerCast: 725 case CK_BlockPointerToObjCPointerCast: 726 case CK_AnyPointerToBlockPointerCast: 727 case CK_ArrayToPointerDecay: 728 case CK_FunctionToPointerDecay: 729 case CK_BaseToDerived: 730 case CK_DerivedToBase: 731 case CK_UncheckedDerivedToBase: 732 case CK_MemberPointerToBoolean: 733 case CK_VectorSplat: 734 case CK_FloatingRealToComplex: 735 case CK_FloatingComplexToReal: 736 case CK_FloatingComplexToBoolean: 737 case CK_FloatingComplexCast: 738 case CK_FloatingComplexToIntegralComplex: 739 case CK_IntegralRealToComplex: 740 case CK_IntegralComplexToReal: 741 case CK_IntegralComplexToBoolean: 742 case CK_IntegralComplexCast: 743 case CK_IntegralComplexToFloatingComplex: 744 case CK_PointerToIntegral: 745 case CK_PointerToBoolean: 746 case CK_NullToPointer: 747 case CK_IntegralCast: 748 case CK_BooleanToSignedIntegral: 749 case CK_IntegralToPointer: 750 case CK_IntegralToBoolean: 751 case CK_IntegralToFloating: 752 case CK_FloatingToIntegral: 753 case CK_FloatingToBoolean: 754 case CK_FloatingCast: 755 case CK_ZeroToOCLEvent: 756 return nullptr; 757 } 758 llvm_unreachable("Invalid CastKind"); 759 } 760 761 llvm::Constant *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) { 762 return Visit(DAE->getExpr()); 763 } 764 765 llvm::Constant *VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE) { 766 // No need for a DefaultInitExprScope: we don't handle 'this' in a 767 // constant expression. 768 return Visit(DIE->getExpr()); 769 } 770 771 llvm::Constant *VisitExprWithCleanups(ExprWithCleanups *E) { 772 if (!E->cleanupsHaveSideEffects()) 773 return Visit(E->getSubExpr()); 774 return nullptr; 775 } 776 777 llvm::Constant *VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E) { 778 return Visit(E->GetTemporaryExpr()); 779 } 780 781 llvm::Constant *EmitArrayInitialization(InitListExpr *ILE) { 782 llvm::ArrayType *AType = 783 cast<llvm::ArrayType>(ConvertType(ILE->getType())); 784 llvm::Type *ElemTy = AType->getElementType(); 785 unsigned NumInitElements = ILE->getNumInits(); 786 unsigned NumElements = AType->getNumElements(); 787 788 // Initialising an array requires us to automatically 789 // initialise any elements that have not been initialised explicitly 790 unsigned NumInitableElts = std::min(NumInitElements, NumElements); 791 792 // Initialize remaining array elements. 793 // FIXME: This doesn't handle member pointers correctly! 794 llvm::Constant *fillC; 795 if (Expr *filler = ILE->getArrayFiller()) 796 fillC = CGM.EmitConstantExpr(filler, filler->getType(), CGF); 797 else 798 fillC = llvm::Constant::getNullValue(ElemTy); 799 if (!fillC) 800 return nullptr; 801 802 // Try to use a ConstantAggregateZero if we can. 803 if (fillC->isNullValue() && !NumInitableElts) 804 return llvm::ConstantAggregateZero::get(AType); 805 806 // Copy initializer elements. 807 std::vector<llvm::Constant*> Elts; 808 Elts.reserve(NumInitableElts + NumElements); 809 810 bool RewriteType = false; 811 for (unsigned i = 0; i < NumInitableElts; ++i) { 812 Expr *Init = ILE->getInit(i); 813 llvm::Constant *C = CGM.EmitConstantExpr(Init, Init->getType(), CGF); 814 if (!C) 815 return nullptr; 816 RewriteType |= (C->getType() != ElemTy); 817 Elts.push_back(C); 818 } 819 820 RewriteType |= (fillC->getType() != ElemTy); 821 Elts.resize(NumElements, fillC); 822 823 if (RewriteType) { 824 // FIXME: Try to avoid packing the array 825 std::vector<llvm::Type*> Types; 826 Types.reserve(NumInitableElts + NumElements); 827 for (unsigned i = 0, e = Elts.size(); i < e; ++i) 828 Types.push_back(Elts[i]->getType()); 829 llvm::StructType *SType = llvm::StructType::get(AType->getContext(), 830 Types, true); 831 return llvm::ConstantStruct::get(SType, Elts); 832 } 833 834 return llvm::ConstantArray::get(AType, Elts); 835 } 836 837 llvm::Constant *EmitRecordInitialization(InitListExpr *ILE) { 838 return ConstStructBuilder::BuildStruct(CGM, CGF, ILE); 839 } 840 841 llvm::Constant *VisitImplicitValueInitExpr(ImplicitValueInitExpr* E) { 842 return CGM.EmitNullConstant(E->getType()); 843 } 844 845 llvm::Constant *VisitInitListExpr(InitListExpr *ILE) { 846 if (ILE->isTransparent()) 847 return Visit(ILE->getInit(0)); 848 849 if (ILE->getType()->isArrayType()) 850 return EmitArrayInitialization(ILE); 851 852 if (ILE->getType()->isRecordType()) 853 return EmitRecordInitialization(ILE); 854 855 return nullptr; 856 } 857 858 llvm::Constant *EmitDesignatedInitUpdater(llvm::Constant *Base, 859 InitListExpr *Updater) { 860 QualType ExprType = Updater->getType(); 861 862 if (ExprType->isArrayType()) { 863 llvm::ArrayType *AType = cast<llvm::ArrayType>(ConvertType(ExprType)); 864 llvm::Type *ElemType = AType->getElementType(); 865 866 unsigned NumInitElements = Updater->getNumInits(); 867 unsigned NumElements = AType->getNumElements(); 868 869 std::vector<llvm::Constant *> Elts; 870 Elts.reserve(NumElements); 871 872 if (llvm::ConstantDataArray *DataArray = 873 dyn_cast<llvm::ConstantDataArray>(Base)) 874 for (unsigned i = 0; i != NumElements; ++i) 875 Elts.push_back(DataArray->getElementAsConstant(i)); 876 else if (llvm::ConstantArray *Array = 877 dyn_cast<llvm::ConstantArray>(Base)) 878 for (unsigned i = 0; i != NumElements; ++i) 879 Elts.push_back(Array->getOperand(i)); 880 else 881 return nullptr; // FIXME: other array types not implemented 882 883 llvm::Constant *fillC = nullptr; 884 if (Expr *filler = Updater->getArrayFiller()) 885 if (!isa<NoInitExpr>(filler)) 886 fillC = CGM.EmitConstantExpr(filler, filler->getType(), CGF); 887 bool RewriteType = (fillC && fillC->getType() != ElemType); 888 889 for (unsigned i = 0; i != NumElements; ++i) { 890 Expr *Init = nullptr; 891 if (i < NumInitElements) 892 Init = Updater->getInit(i); 893 894 if (!Init && fillC) 895 Elts[i] = fillC; 896 else if (!Init || isa<NoInitExpr>(Init)) 897 ; // Do nothing. 898 else if (InitListExpr *ChildILE = dyn_cast<InitListExpr>(Init)) 899 Elts[i] = EmitDesignatedInitUpdater(Elts[i], ChildILE); 900 else 901 Elts[i] = CGM.EmitConstantExpr(Init, Init->getType(), CGF); 902 903 if (!Elts[i]) 904 return nullptr; 905 RewriteType |= (Elts[i]->getType() != ElemType); 906 } 907 908 if (RewriteType) { 909 std::vector<llvm::Type *> Types; 910 Types.reserve(NumElements); 911 for (unsigned i = 0; i != NumElements; ++i) 912 Types.push_back(Elts[i]->getType()); 913 llvm::StructType *SType = llvm::StructType::get(AType->getContext(), 914 Types, true); 915 return llvm::ConstantStruct::get(SType, Elts); 916 } 917 918 return llvm::ConstantArray::get(AType, Elts); 919 } 920 921 if (ExprType->isRecordType()) 922 return ConstStructBuilder::BuildStruct(CGM, CGF, this, 923 dyn_cast<llvm::ConstantStruct>(Base), Updater); 924 925 return nullptr; 926 } 927 928 llvm::Constant *VisitDesignatedInitUpdateExpr(DesignatedInitUpdateExpr *E) { 929 return EmitDesignatedInitUpdater( 930 CGM.EmitConstantExpr(E->getBase(), E->getType(), CGF), 931 E->getUpdater()); 932 } 933 934 llvm::Constant *VisitCXXConstructExpr(CXXConstructExpr *E) { 935 if (!E->getConstructor()->isTrivial()) 936 return nullptr; 937 938 QualType Ty = E->getType(); 939 940 // FIXME: We should not have to call getBaseElementType here. 941 const RecordType *RT = 942 CGM.getContext().getBaseElementType(Ty)->getAs<RecordType>(); 943 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 944 945 // If the class doesn't have a trivial destructor, we can't emit it as a 946 // constant expr. 947 if (!RD->hasTrivialDestructor()) 948 return nullptr; 949 950 // Only copy and default constructors can be trivial. 951 952 953 if (E->getNumArgs()) { 954 assert(E->getNumArgs() == 1 && "trivial ctor with > 1 argument"); 955 assert(E->getConstructor()->isCopyOrMoveConstructor() && 956 "trivial ctor has argument but isn't a copy/move ctor"); 957 958 Expr *Arg = E->getArg(0); 959 assert(CGM.getContext().hasSameUnqualifiedType(Ty, Arg->getType()) && 960 "argument to copy ctor is of wrong type"); 961 962 return Visit(Arg); 963 } 964 965 return CGM.EmitNullConstant(Ty); 966 } 967 968 llvm::Constant *VisitStringLiteral(StringLiteral *E) { 969 return CGM.GetConstantArrayFromStringLiteral(E); 970 } 971 972 llvm::Constant *VisitObjCEncodeExpr(ObjCEncodeExpr *E) { 973 // This must be an @encode initializing an array in a static initializer. 974 // Don't emit it as the address of the string, emit the string data itself 975 // as an inline array. 976 std::string Str; 977 CGM.getContext().getObjCEncodingForType(E->getEncodedType(), Str); 978 QualType T = E->getType(); 979 if (T->getTypeClass() == Type::TypeOfExpr) 980 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType(); 981 const ConstantArrayType *CAT = cast<ConstantArrayType>(T); 982 983 // Resize the string to the right size, adding zeros at the end, or 984 // truncating as needed. 985 Str.resize(CAT->getSize().getZExtValue(), '\0'); 986 return llvm::ConstantDataArray::getString(VMContext, Str, false); 987 } 988 989 llvm::Constant *VisitUnaryExtension(const UnaryOperator *E) { 990 return Visit(E->getSubExpr()); 991 } 992 993 // Utility methods 994 llvm::Type *ConvertType(QualType T) { 995 return CGM.getTypes().ConvertType(T); 996 } 997 998 public: 999 ConstantAddress EmitLValue(APValue::LValueBase LVBase) { 1000 if (const ValueDecl *Decl = LVBase.dyn_cast<const ValueDecl*>()) { 1001 if (Decl->hasAttr<WeakRefAttr>()) 1002 return CGM.GetWeakRefReference(Decl); 1003 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Decl)) 1004 return ConstantAddress(CGM.GetAddrOfFunction(FD), CharUnits::One()); 1005 if (const VarDecl* VD = dyn_cast<VarDecl>(Decl)) { 1006 // We can never refer to a variable with local storage. 1007 if (!VD->hasLocalStorage()) { 1008 CharUnits Align = CGM.getContext().getDeclAlign(VD); 1009 if (VD->isFileVarDecl() || VD->hasExternalStorage()) 1010 return ConstantAddress(CGM.GetAddrOfGlobalVar(VD), Align); 1011 else if (VD->isLocalVarDecl()) { 1012 auto Ptr = CGM.getOrCreateStaticVarDecl( 1013 *VD, CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false)); 1014 return ConstantAddress(Ptr, Align); 1015 } 1016 } 1017 } 1018 return ConstantAddress::invalid(); 1019 } 1020 1021 Expr *E = const_cast<Expr*>(LVBase.get<const Expr*>()); 1022 switch (E->getStmtClass()) { 1023 default: break; 1024 case Expr::CompoundLiteralExprClass: { 1025 // Note that due to the nature of compound literals, this is guaranteed 1026 // to be the only use of the variable, so we just generate it here. 1027 CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E); 1028 llvm::Constant* C = CGM.EmitConstantExpr(CLE->getInitializer(), 1029 CLE->getType(), CGF); 1030 // FIXME: "Leaked" on failure. 1031 if (!C) return ConstantAddress::invalid(); 1032 1033 CharUnits Align = CGM.getContext().getTypeAlignInChars(E->getType()); 1034 1035 auto GV = new llvm::GlobalVariable(CGM.getModule(), C->getType(), 1036 E->getType().isConstant(CGM.getContext()), 1037 llvm::GlobalValue::InternalLinkage, 1038 C, ".compoundliteral", nullptr, 1039 llvm::GlobalVariable::NotThreadLocal, 1040 CGM.getContext().getTargetAddressSpace(E->getType())); 1041 GV->setAlignment(Align.getQuantity()); 1042 return ConstantAddress(GV, Align); 1043 } 1044 case Expr::StringLiteralClass: 1045 return CGM.GetAddrOfConstantStringFromLiteral(cast<StringLiteral>(E)); 1046 case Expr::ObjCEncodeExprClass: 1047 return CGM.GetAddrOfConstantStringFromObjCEncode(cast<ObjCEncodeExpr>(E)); 1048 case Expr::ObjCStringLiteralClass: { 1049 ObjCStringLiteral* SL = cast<ObjCStringLiteral>(E); 1050 ConstantAddress C = 1051 CGM.getObjCRuntime().GenerateConstantString(SL->getString()); 1052 return C.getElementBitCast(ConvertType(E->getType())); 1053 } 1054 case Expr::PredefinedExprClass: { 1055 unsigned Type = cast<PredefinedExpr>(E)->getIdentType(); 1056 if (CGF) { 1057 LValue Res = CGF->EmitPredefinedLValue(cast<PredefinedExpr>(E)); 1058 return cast<ConstantAddress>(Res.getAddress()); 1059 } else if (Type == PredefinedExpr::PrettyFunction) { 1060 return CGM.GetAddrOfConstantCString("top level", ".tmp"); 1061 } 1062 1063 return CGM.GetAddrOfConstantCString("", ".tmp"); 1064 } 1065 case Expr::AddrLabelExprClass: { 1066 assert(CGF && "Invalid address of label expression outside function."); 1067 llvm::Constant *Ptr = 1068 CGF->GetAddrOfLabel(cast<AddrLabelExpr>(E)->getLabel()); 1069 Ptr = llvm::ConstantExpr::getBitCast(Ptr, ConvertType(E->getType())); 1070 return ConstantAddress(Ptr, CharUnits::One()); 1071 } 1072 case Expr::CallExprClass: { 1073 CallExpr* CE = cast<CallExpr>(E); 1074 unsigned builtin = CE->getBuiltinCallee(); 1075 if (builtin != 1076 Builtin::BI__builtin___CFStringMakeConstantString && 1077 builtin != 1078 Builtin::BI__builtin___NSStringMakeConstantString) 1079 break; 1080 const Expr *Arg = CE->getArg(0)->IgnoreParenCasts(); 1081 const StringLiteral *Literal = cast<StringLiteral>(Arg); 1082 if (builtin == 1083 Builtin::BI__builtin___NSStringMakeConstantString) { 1084 return CGM.getObjCRuntime().GenerateConstantString(Literal); 1085 } 1086 // FIXME: need to deal with UCN conversion issues. 1087 return CGM.GetAddrOfConstantCFString(Literal); 1088 } 1089 case Expr::BlockExprClass: { 1090 StringRef FunctionName; 1091 if (CGF) 1092 FunctionName = CGF->CurFn->getName(); 1093 else 1094 FunctionName = "global"; 1095 1096 // This is not really an l-value. 1097 llvm::Constant *Ptr = 1098 CGM.GetAddrOfGlobalBlock(cast<BlockExpr>(E), FunctionName); 1099 return ConstantAddress(Ptr, CGM.getPointerAlign()); 1100 } 1101 case Expr::CXXTypeidExprClass: { 1102 CXXTypeidExpr *Typeid = cast<CXXTypeidExpr>(E); 1103 QualType T; 1104 if (Typeid->isTypeOperand()) 1105 T = Typeid->getTypeOperand(CGM.getContext()); 1106 else 1107 T = Typeid->getExprOperand()->getType(); 1108 return ConstantAddress(CGM.GetAddrOfRTTIDescriptor(T), 1109 CGM.getPointerAlign()); 1110 } 1111 case Expr::CXXUuidofExprClass: { 1112 return CGM.GetAddrOfUuidDescriptor(cast<CXXUuidofExpr>(E)); 1113 } 1114 case Expr::MaterializeTemporaryExprClass: { 1115 MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(E); 1116 assert(MTE->getStorageDuration() == SD_Static); 1117 SmallVector<const Expr *, 2> CommaLHSs; 1118 SmallVector<SubobjectAdjustment, 2> Adjustments; 1119 const Expr *Inner = MTE->GetTemporaryExpr() 1120 ->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments); 1121 return CGM.GetAddrOfGlobalTemporary(MTE, Inner); 1122 } 1123 } 1124 1125 return ConstantAddress::invalid(); 1126 } 1127 }; 1128 1129 } // end anonymous namespace. 1130 1131 bool ConstStructBuilder::Build(ConstExprEmitter *Emitter, 1132 llvm::ConstantStruct *Base, 1133 InitListExpr *Updater) { 1134 assert(Base && "base expression should not be empty"); 1135 1136 QualType ExprType = Updater->getType(); 1137 RecordDecl *RD = ExprType->getAs<RecordType>()->getDecl(); 1138 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD); 1139 const llvm::StructLayout *BaseLayout = CGM.getDataLayout().getStructLayout( 1140 Base->getType()); 1141 unsigned FieldNo = -1; 1142 unsigned ElementNo = 0; 1143 1144 // Bail out if we have base classes. We could support these, but they only 1145 // arise in C++1z where we will have already constant folded most interesting 1146 // cases. FIXME: There are still a few more cases we can handle this way. 1147 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 1148 if (CXXRD->getNumBases()) 1149 return false; 1150 1151 for (FieldDecl *Field : RD->fields()) { 1152 ++FieldNo; 1153 1154 if (RD->isUnion() && Updater->getInitializedFieldInUnion() != Field) 1155 continue; 1156 1157 // Skip anonymous bitfields. 1158 if (Field->isUnnamedBitfield()) 1159 continue; 1160 1161 llvm::Constant *EltInit = Base->getOperand(ElementNo); 1162 1163 // Bail out if the type of the ConstantStruct does not have the same layout 1164 // as the type of the InitListExpr. 1165 if (CGM.getTypes().ConvertType(Field->getType()) != EltInit->getType() || 1166 Layout.getFieldOffset(ElementNo) != 1167 BaseLayout->getElementOffsetInBits(ElementNo)) 1168 return false; 1169 1170 // Get the initializer. If we encounter an empty field or a NoInitExpr, 1171 // we use values from the base expression. 1172 Expr *Init = nullptr; 1173 if (ElementNo < Updater->getNumInits()) 1174 Init = Updater->getInit(ElementNo); 1175 1176 if (!Init || isa<NoInitExpr>(Init)) 1177 ; // Do nothing. 1178 else if (InitListExpr *ChildILE = dyn_cast<InitListExpr>(Init)) 1179 EltInit = Emitter->EmitDesignatedInitUpdater(EltInit, ChildILE); 1180 else 1181 EltInit = CGM.EmitConstantExpr(Init, Field->getType(), CGF); 1182 1183 ++ElementNo; 1184 1185 if (!EltInit) 1186 return false; 1187 1188 if (!Field->isBitField()) 1189 AppendField(Field, Layout.getFieldOffset(FieldNo), EltInit); 1190 else if (llvm::ConstantInt *CI = dyn_cast<llvm::ConstantInt>(EltInit)) 1191 AppendBitField(Field, Layout.getFieldOffset(FieldNo), CI); 1192 else 1193 // Initializing a bitfield with a non-trivial constant? 1194 return false; 1195 } 1196 1197 return true; 1198 } 1199 1200 llvm::Constant *CodeGenModule::EmitConstantInit(const VarDecl &D, 1201 CodeGenFunction *CGF) { 1202 // Make a quick check if variable can be default NULL initialized 1203 // and avoid going through rest of code which may do, for c++11, 1204 // initialization of memory to all NULLs. 1205 if (!D.hasLocalStorage()) { 1206 QualType Ty = D.getType(); 1207 if (Ty->isArrayType()) 1208 Ty = Context.getBaseElementType(Ty); 1209 if (Ty->isRecordType()) 1210 if (const CXXConstructExpr *E = 1211 dyn_cast_or_null<CXXConstructExpr>(D.getInit())) { 1212 const CXXConstructorDecl *CD = E->getConstructor(); 1213 if (CD->isTrivial() && CD->isDefaultConstructor()) 1214 return EmitNullConstant(D.getType()); 1215 } 1216 } 1217 1218 if (const APValue *Value = D.evaluateValue()) 1219 return EmitConstantValueForMemory(*Value, D.getType(), CGF); 1220 1221 // FIXME: Implement C++11 [basic.start.init]p2: if the initializer of a 1222 // reference is a constant expression, and the reference binds to a temporary, 1223 // then constant initialization is performed. ConstExprEmitter will 1224 // incorrectly emit a prvalue constant in this case, and the calling code 1225 // interprets that as the (pointer) value of the reference, rather than the 1226 // desired value of the referee. 1227 if (D.getType()->isReferenceType()) 1228 return nullptr; 1229 1230 const Expr *E = D.getInit(); 1231 assert(E && "No initializer to emit"); 1232 1233 llvm::Constant* C = ConstExprEmitter(*this, CGF).Visit(const_cast<Expr*>(E)); 1234 if (C && C->getType()->isIntegerTy(1)) { 1235 llvm::Type *BoolTy = getTypes().ConvertTypeForMem(E->getType()); 1236 C = llvm::ConstantExpr::getZExt(C, BoolTy); 1237 } 1238 return C; 1239 } 1240 1241 llvm::Constant *CodeGenModule::EmitConstantExpr(const Expr *E, 1242 QualType DestType, 1243 CodeGenFunction *CGF) { 1244 Expr::EvalResult Result; 1245 1246 bool Success = false; 1247 1248 if (DestType->isReferenceType()) 1249 Success = E->EvaluateAsLValue(Result, Context); 1250 else 1251 Success = E->EvaluateAsRValue(Result, Context); 1252 1253 llvm::Constant *C = nullptr; 1254 if (Success && !Result.HasSideEffects) 1255 C = EmitConstantValue(Result.Val, DestType, CGF); 1256 else 1257 C = ConstExprEmitter(*this, CGF).Visit(const_cast<Expr*>(E)); 1258 1259 if (C && C->getType()->isIntegerTy(1)) { 1260 llvm::Type *BoolTy = getTypes().ConvertTypeForMem(E->getType()); 1261 C = llvm::ConstantExpr::getZExt(C, BoolTy); 1262 } 1263 return C; 1264 } 1265 1266 llvm::Constant *CodeGenModule::getNullPointer(llvm::PointerType *T, QualType QT) { 1267 return getTargetCodeGenInfo().getNullPointer(*this, T, QT); 1268 } 1269 1270 llvm::Constant *CodeGenModule::EmitConstantValue(const APValue &Value, 1271 QualType DestType, 1272 CodeGenFunction *CGF) { 1273 // For an _Atomic-qualified constant, we may need to add tail padding. 1274 if (auto *AT = DestType->getAs<AtomicType>()) { 1275 QualType InnerType = AT->getValueType(); 1276 auto *Inner = EmitConstantValue(Value, InnerType, CGF); 1277 1278 uint64_t InnerSize = Context.getTypeSize(InnerType); 1279 uint64_t OuterSize = Context.getTypeSize(DestType); 1280 if (InnerSize == OuterSize) 1281 return Inner; 1282 1283 assert(InnerSize < OuterSize && "emitted over-large constant for atomic"); 1284 llvm::Constant *Elts[] = { 1285 Inner, 1286 llvm::ConstantAggregateZero::get( 1287 llvm::ArrayType::get(Int8Ty, (OuterSize - InnerSize) / 8)) 1288 }; 1289 return llvm::ConstantStruct::getAnon(Elts); 1290 } 1291 1292 switch (Value.getKind()) { 1293 case APValue::Uninitialized: 1294 llvm_unreachable("Constant expressions should be initialized."); 1295 case APValue::LValue: { 1296 llvm::Type *DestTy = getTypes().ConvertTypeForMem(DestType); 1297 llvm::Constant *Offset = 1298 llvm::ConstantInt::get(Int64Ty, Value.getLValueOffset().getQuantity()); 1299 1300 llvm::Constant *C = nullptr; 1301 1302 if (APValue::LValueBase LVBase = Value.getLValueBase()) { 1303 // An array can be represented as an lvalue referring to the base. 1304 if (isa<llvm::ArrayType>(DestTy)) { 1305 assert(Offset->isNullValue() && "offset on array initializer"); 1306 return ConstExprEmitter(*this, CGF).Visit( 1307 const_cast<Expr*>(LVBase.get<const Expr*>())); 1308 } 1309 1310 C = ConstExprEmitter(*this, CGF).EmitLValue(LVBase).getPointer(); 1311 1312 // Apply offset if necessary. 1313 if (!Offset->isNullValue()) { 1314 unsigned AS = C->getType()->getPointerAddressSpace(); 1315 llvm::Type *CharPtrTy = Int8Ty->getPointerTo(AS); 1316 llvm::Constant *Casted = llvm::ConstantExpr::getBitCast(C, CharPtrTy); 1317 Casted = llvm::ConstantExpr::getGetElementPtr(Int8Ty, Casted, Offset); 1318 C = llvm::ConstantExpr::getPointerCast(Casted, C->getType()); 1319 } 1320 1321 // Convert to the appropriate type; this could be an lvalue for 1322 // an integer. 1323 if (isa<llvm::PointerType>(DestTy)) 1324 return llvm::ConstantExpr::getPointerCast(C, DestTy); 1325 1326 return llvm::ConstantExpr::getPtrToInt(C, DestTy); 1327 } else { 1328 C = Offset; 1329 1330 // Convert to the appropriate type; this could be an lvalue for 1331 // an integer. 1332 if (auto PT = dyn_cast<llvm::PointerType>(DestTy)) { 1333 if (Value.isNullPointer()) 1334 return getNullPointer(PT, DestType); 1335 // Convert the integer to a pointer-sized integer before converting it 1336 // to a pointer. 1337 C = llvm::ConstantExpr::getIntegerCast( 1338 C, getDataLayout().getIntPtrType(DestTy), 1339 /*isSigned=*/false); 1340 return llvm::ConstantExpr::getIntToPtr(C, DestTy); 1341 } 1342 1343 // If the types don't match this should only be a truncate. 1344 if (C->getType() != DestTy) 1345 return llvm::ConstantExpr::getTrunc(C, DestTy); 1346 1347 return C; 1348 } 1349 } 1350 case APValue::Int: 1351 return llvm::ConstantInt::get(VMContext, Value.getInt()); 1352 case APValue::ComplexInt: { 1353 llvm::Constant *Complex[2]; 1354 1355 Complex[0] = llvm::ConstantInt::get(VMContext, 1356 Value.getComplexIntReal()); 1357 Complex[1] = llvm::ConstantInt::get(VMContext, 1358 Value.getComplexIntImag()); 1359 1360 // FIXME: the target may want to specify that this is packed. 1361 llvm::StructType *STy = llvm::StructType::get(Complex[0]->getType(), 1362 Complex[1]->getType(), 1363 nullptr); 1364 return llvm::ConstantStruct::get(STy, Complex); 1365 } 1366 case APValue::Float: { 1367 const llvm::APFloat &Init = Value.getFloat(); 1368 if (&Init.getSemantics() == &llvm::APFloat::IEEEhalf && 1369 !Context.getLangOpts().NativeHalfType && 1370 !Context.getLangOpts().HalfArgsAndReturns) 1371 return llvm::ConstantInt::get(VMContext, Init.bitcastToAPInt()); 1372 else 1373 return llvm::ConstantFP::get(VMContext, Init); 1374 } 1375 case APValue::ComplexFloat: { 1376 llvm::Constant *Complex[2]; 1377 1378 Complex[0] = llvm::ConstantFP::get(VMContext, 1379 Value.getComplexFloatReal()); 1380 Complex[1] = llvm::ConstantFP::get(VMContext, 1381 Value.getComplexFloatImag()); 1382 1383 // FIXME: the target may want to specify that this is packed. 1384 llvm::StructType *STy = llvm::StructType::get(Complex[0]->getType(), 1385 Complex[1]->getType(), 1386 nullptr); 1387 return llvm::ConstantStruct::get(STy, Complex); 1388 } 1389 case APValue::Vector: { 1390 unsigned NumElts = Value.getVectorLength(); 1391 SmallVector<llvm::Constant *, 4> Inits(NumElts); 1392 1393 for (unsigned I = 0; I != NumElts; ++I) { 1394 const APValue &Elt = Value.getVectorElt(I); 1395 if (Elt.isInt()) 1396 Inits[I] = llvm::ConstantInt::get(VMContext, Elt.getInt()); 1397 else if (Elt.isFloat()) 1398 Inits[I] = llvm::ConstantFP::get(VMContext, Elt.getFloat()); 1399 else 1400 llvm_unreachable("unsupported vector element type"); 1401 } 1402 return llvm::ConstantVector::get(Inits); 1403 } 1404 case APValue::AddrLabelDiff: { 1405 const AddrLabelExpr *LHSExpr = Value.getAddrLabelDiffLHS(); 1406 const AddrLabelExpr *RHSExpr = Value.getAddrLabelDiffRHS(); 1407 llvm::Constant *LHS = EmitConstantExpr(LHSExpr, LHSExpr->getType(), CGF); 1408 llvm::Constant *RHS = EmitConstantExpr(RHSExpr, RHSExpr->getType(), CGF); 1409 1410 // Compute difference 1411 llvm::Type *ResultType = getTypes().ConvertType(DestType); 1412 LHS = llvm::ConstantExpr::getPtrToInt(LHS, IntPtrTy); 1413 RHS = llvm::ConstantExpr::getPtrToInt(RHS, IntPtrTy); 1414 llvm::Constant *AddrLabelDiff = llvm::ConstantExpr::getSub(LHS, RHS); 1415 1416 // LLVM is a bit sensitive about the exact format of the 1417 // address-of-label difference; make sure to truncate after 1418 // the subtraction. 1419 return llvm::ConstantExpr::getTruncOrBitCast(AddrLabelDiff, ResultType); 1420 } 1421 case APValue::Struct: 1422 case APValue::Union: 1423 return ConstStructBuilder::BuildStruct(*this, CGF, Value, DestType); 1424 case APValue::Array: { 1425 const ArrayType *CAT = Context.getAsArrayType(DestType); 1426 unsigned NumElements = Value.getArraySize(); 1427 unsigned NumInitElts = Value.getArrayInitializedElts(); 1428 1429 // Emit array filler, if there is one. 1430 llvm::Constant *Filler = nullptr; 1431 if (Value.hasArrayFiller()) 1432 Filler = EmitConstantValueForMemory(Value.getArrayFiller(), 1433 CAT->getElementType(), CGF); 1434 1435 // Emit initializer elements. 1436 llvm::Type *CommonElementType = 1437 getTypes().ConvertType(CAT->getElementType()); 1438 1439 // Try to use a ConstantAggregateZero if we can. 1440 if (Filler && Filler->isNullValue() && !NumInitElts) { 1441 llvm::ArrayType *AType = 1442 llvm::ArrayType::get(CommonElementType, NumElements); 1443 return llvm::ConstantAggregateZero::get(AType); 1444 } 1445 1446 std::vector<llvm::Constant*> Elts; 1447 Elts.reserve(NumElements); 1448 for (unsigned I = 0; I < NumElements; ++I) { 1449 llvm::Constant *C = Filler; 1450 if (I < NumInitElts) 1451 C = EmitConstantValueForMemory(Value.getArrayInitializedElt(I), 1452 CAT->getElementType(), CGF); 1453 else 1454 assert(Filler && "Missing filler for implicit elements of initializer"); 1455 if (I == 0) 1456 CommonElementType = C->getType(); 1457 else if (C->getType() != CommonElementType) 1458 CommonElementType = nullptr; 1459 Elts.push_back(C); 1460 } 1461 1462 if (!CommonElementType) { 1463 // FIXME: Try to avoid packing the array 1464 std::vector<llvm::Type*> Types; 1465 Types.reserve(NumElements); 1466 for (unsigned i = 0, e = Elts.size(); i < e; ++i) 1467 Types.push_back(Elts[i]->getType()); 1468 llvm::StructType *SType = llvm::StructType::get(VMContext, Types, true); 1469 return llvm::ConstantStruct::get(SType, Elts); 1470 } 1471 1472 llvm::ArrayType *AType = 1473 llvm::ArrayType::get(CommonElementType, NumElements); 1474 return llvm::ConstantArray::get(AType, Elts); 1475 } 1476 case APValue::MemberPointer: 1477 return getCXXABI().EmitMemberPointer(Value, DestType); 1478 } 1479 llvm_unreachable("Unknown APValue kind"); 1480 } 1481 1482 llvm::Constant * 1483 CodeGenModule::EmitConstantValueForMemory(const APValue &Value, 1484 QualType DestType, 1485 CodeGenFunction *CGF) { 1486 llvm::Constant *C = EmitConstantValue(Value, DestType, CGF); 1487 if (C->getType()->isIntegerTy(1)) { 1488 llvm::Type *BoolTy = getTypes().ConvertTypeForMem(DestType); 1489 C = llvm::ConstantExpr::getZExt(C, BoolTy); 1490 } 1491 return C; 1492 } 1493 1494 ConstantAddress 1495 CodeGenModule::GetAddrOfConstantCompoundLiteral(const CompoundLiteralExpr *E) { 1496 assert(E->isFileScope() && "not a file-scope compound literal expr"); 1497 return ConstExprEmitter(*this, nullptr).EmitLValue(E); 1498 } 1499 1500 llvm::Constant * 1501 CodeGenModule::getMemberPointerConstant(const UnaryOperator *uo) { 1502 // Member pointer constants always have a very particular form. 1503 const MemberPointerType *type = cast<MemberPointerType>(uo->getType()); 1504 const ValueDecl *decl = cast<DeclRefExpr>(uo->getSubExpr())->getDecl(); 1505 1506 // A member function pointer. 1507 if (const CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(decl)) 1508 return getCXXABI().EmitMemberFunctionPointer(method); 1509 1510 // Otherwise, a member data pointer. 1511 uint64_t fieldOffset = getContext().getFieldOffset(decl); 1512 CharUnits chars = getContext().toCharUnitsFromBits((int64_t) fieldOffset); 1513 return getCXXABI().EmitMemberDataPointer(type, chars); 1514 } 1515 1516 static llvm::Constant *EmitNullConstantForBase(CodeGenModule &CGM, 1517 llvm::Type *baseType, 1518 const CXXRecordDecl *base); 1519 1520 static llvm::Constant *EmitNullConstant(CodeGenModule &CGM, 1521 const RecordDecl *record, 1522 bool asCompleteObject) { 1523 const CGRecordLayout &layout = CGM.getTypes().getCGRecordLayout(record); 1524 llvm::StructType *structure = 1525 (asCompleteObject ? layout.getLLVMType() 1526 : layout.getBaseSubobjectLLVMType()); 1527 1528 unsigned numElements = structure->getNumElements(); 1529 std::vector<llvm::Constant *> elements(numElements); 1530 1531 auto CXXR = dyn_cast<CXXRecordDecl>(record); 1532 // Fill in all the bases. 1533 if (CXXR) { 1534 for (const auto &I : CXXR->bases()) { 1535 if (I.isVirtual()) { 1536 // Ignore virtual bases; if we're laying out for a complete 1537 // object, we'll lay these out later. 1538 continue; 1539 } 1540 1541 const CXXRecordDecl *base = 1542 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl()); 1543 1544 // Ignore empty bases. 1545 if (base->isEmpty() || 1546 CGM.getContext().getASTRecordLayout(base).getNonVirtualSize() 1547 .isZero()) 1548 continue; 1549 1550 unsigned fieldIndex = layout.getNonVirtualBaseLLVMFieldNo(base); 1551 llvm::Type *baseType = structure->getElementType(fieldIndex); 1552 elements[fieldIndex] = EmitNullConstantForBase(CGM, baseType, base); 1553 } 1554 } 1555 1556 // Fill in all the fields. 1557 for (const auto *Field : record->fields()) { 1558 // Fill in non-bitfields. (Bitfields always use a zero pattern, which we 1559 // will fill in later.) 1560 if (!Field->isBitField()) { 1561 unsigned fieldIndex = layout.getLLVMFieldNo(Field); 1562 elements[fieldIndex] = CGM.EmitNullConstant(Field->getType()); 1563 } 1564 1565 // For unions, stop after the first named field. 1566 if (record->isUnion()) { 1567 if (Field->getIdentifier()) 1568 break; 1569 if (const auto *FieldRD = 1570 dyn_cast_or_null<RecordDecl>(Field->getType()->getAsTagDecl())) 1571 if (FieldRD->findFirstNamedDataMember()) 1572 break; 1573 } 1574 } 1575 1576 // Fill in the virtual bases, if we're working with the complete object. 1577 if (CXXR && asCompleteObject) { 1578 for (const auto &I : CXXR->vbases()) { 1579 const CXXRecordDecl *base = 1580 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl()); 1581 1582 // Ignore empty bases. 1583 if (base->isEmpty()) 1584 continue; 1585 1586 unsigned fieldIndex = layout.getVirtualBaseIndex(base); 1587 1588 // We might have already laid this field out. 1589 if (elements[fieldIndex]) continue; 1590 1591 llvm::Type *baseType = structure->getElementType(fieldIndex); 1592 elements[fieldIndex] = EmitNullConstantForBase(CGM, baseType, base); 1593 } 1594 } 1595 1596 // Now go through all other fields and zero them out. 1597 for (unsigned i = 0; i != numElements; ++i) { 1598 if (!elements[i]) 1599 elements[i] = llvm::Constant::getNullValue(structure->getElementType(i)); 1600 } 1601 1602 return llvm::ConstantStruct::get(structure, elements); 1603 } 1604 1605 /// Emit the null constant for a base subobject. 1606 static llvm::Constant *EmitNullConstantForBase(CodeGenModule &CGM, 1607 llvm::Type *baseType, 1608 const CXXRecordDecl *base) { 1609 const CGRecordLayout &baseLayout = CGM.getTypes().getCGRecordLayout(base); 1610 1611 // Just zero out bases that don't have any pointer to data members. 1612 if (baseLayout.isZeroInitializableAsBase()) 1613 return llvm::Constant::getNullValue(baseType); 1614 1615 // Otherwise, we can just use its null constant. 1616 return EmitNullConstant(CGM, base, /*asCompleteObject=*/false); 1617 } 1618 1619 llvm::Constant *CodeGenModule::EmitNullConstant(QualType T) { 1620 if (T->getAs<PointerType>()) 1621 return getNullPointer( 1622 cast<llvm::PointerType>(getTypes().ConvertTypeForMem(T)), T); 1623 1624 if (getTypes().isZeroInitializable(T)) 1625 return llvm::Constant::getNullValue(getTypes().ConvertTypeForMem(T)); 1626 1627 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(T)) { 1628 llvm::ArrayType *ATy = 1629 cast<llvm::ArrayType>(getTypes().ConvertTypeForMem(T)); 1630 1631 QualType ElementTy = CAT->getElementType(); 1632 1633 llvm::Constant *Element = EmitNullConstant(ElementTy); 1634 unsigned NumElements = CAT->getSize().getZExtValue(); 1635 SmallVector<llvm::Constant *, 8> Array(NumElements, Element); 1636 return llvm::ConstantArray::get(ATy, Array); 1637 } 1638 1639 if (const RecordType *RT = T->getAs<RecordType>()) 1640 return ::EmitNullConstant(*this, RT->getDecl(), /*complete object*/ true); 1641 1642 assert(T->isMemberDataPointerType() && 1643 "Should only see pointers to data members here!"); 1644 1645 return getCXXABI().EmitNullMemberPointer(T->castAs<MemberPointerType>()); 1646 } 1647 1648 llvm::Constant * 1649 CodeGenModule::EmitNullConstantForBase(const CXXRecordDecl *Record) { 1650 return ::EmitNullConstant(*this, Record, false); 1651 } 1652