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 "CodeGenModule.h" 16 #include "CGObjCRuntime.h" 17 #include "clang/AST/APValue.h" 18 #include "clang/AST/ASTContext.h" 19 #include "clang/AST/RecordLayout.h" 20 #include "clang/AST/StmtVisitor.h" 21 #include "clang/Basic/Builtins.h" 22 #include "llvm/Constants.h" 23 #include "llvm/Function.h" 24 #include "llvm/GlobalVariable.h" 25 #include "llvm/Target/TargetData.h" 26 using namespace clang; 27 using namespace CodeGen; 28 29 namespace { 30 class ConstStructBuilder { 31 CodeGenModule &CGM; 32 CodeGenFunction *CGF; 33 34 bool Packed; 35 36 unsigned NextFieldOffsetInBytes; 37 38 unsigned LLVMStructAlignment; 39 40 std::vector<llvm::Constant *> Elements; 41 42 ConstStructBuilder(CodeGenModule &CGM, CodeGenFunction *CGF) 43 : CGM(CGM), CGF(CGF), Packed(false), NextFieldOffsetInBytes(0), 44 LLVMStructAlignment(1) { } 45 46 bool AppendField(const FieldDecl *Field, uint64_t FieldOffset, 47 const Expr *InitExpr) { 48 uint64_t FieldOffsetInBytes = FieldOffset / 8; 49 50 assert(NextFieldOffsetInBytes <= FieldOffsetInBytes 51 && "Field offset mismatch!"); 52 53 // Emit the field. 54 llvm::Constant *C = CGM.EmitConstantExpr(InitExpr, Field->getType(), CGF); 55 if (!C) 56 return false; 57 58 unsigned FieldAlignment = getAlignment(C); 59 60 // Round up the field offset to the alignment of the field type. 61 uint64_t AlignedNextFieldOffsetInBytes = 62 llvm::RoundUpToAlignment(NextFieldOffsetInBytes, FieldAlignment); 63 64 if (AlignedNextFieldOffsetInBytes > FieldOffsetInBytes) { 65 assert(!Packed && "Alignment is wrong even with a packed struct!"); 66 67 // Convert the struct to a packed struct. 68 ConvertStructToPacked(); 69 70 AlignedNextFieldOffsetInBytes = NextFieldOffsetInBytes; 71 } 72 73 if (AlignedNextFieldOffsetInBytes < FieldOffsetInBytes) { 74 // We need to append padding. 75 AppendPadding(FieldOffsetInBytes - NextFieldOffsetInBytes); 76 77 assert(NextFieldOffsetInBytes == FieldOffsetInBytes && 78 "Did not add enough padding!"); 79 80 AlignedNextFieldOffsetInBytes = NextFieldOffsetInBytes; 81 } 82 83 // Add the field. 84 Elements.push_back(C); 85 NextFieldOffsetInBytes = AlignedNextFieldOffsetInBytes + getSizeInBytes(C); 86 87 if (Packed) 88 assert(LLVMStructAlignment == 1 && "Packed struct not byte-aligned!"); 89 else 90 LLVMStructAlignment = std::max(LLVMStructAlignment, FieldAlignment); 91 92 return true; 93 } 94 95 bool AppendBitField(const FieldDecl *Field, uint64_t FieldOffset, 96 const Expr *InitExpr) { 97 llvm::ConstantInt *CI = 98 cast_or_null<llvm::ConstantInt>(CGM.EmitConstantExpr(InitExpr, 99 Field->getType(), 100 CGF)); 101 // FIXME: Can this ever happen? 102 if (!CI) 103 return false; 104 105 if (FieldOffset > NextFieldOffsetInBytes * 8) { 106 // We need to add padding. 107 uint64_t NumBytes = 108 llvm::RoundUpToAlignment(FieldOffset - 109 NextFieldOffsetInBytes * 8, 8) / 8; 110 111 AppendPadding(NumBytes); 112 } 113 114 uint64_t FieldSize = 115 Field->getBitWidth()->EvaluateAsInt(CGM.getContext()).getZExtValue(); 116 117 llvm::APInt FieldValue = CI->getValue(); 118 119 // Promote the size of FieldValue if necessary 120 // FIXME: This should never occur, but currently it can because initializer 121 // constants are cast to bool, and because clang is not enforcing bitfield 122 // width limits. 123 if (FieldSize > FieldValue.getBitWidth()) 124 FieldValue.zext(FieldSize); 125 126 // Truncate the size of FieldValue to the bit field size. 127 if (FieldSize < FieldValue.getBitWidth()) 128 FieldValue.trunc(FieldSize); 129 130 if (FieldOffset < NextFieldOffsetInBytes * 8) { 131 // Either part of the field or the entire field can go into the previous 132 // byte. 133 assert(!Elements.empty() && "Elements can't be empty!"); 134 135 unsigned BitsInPreviousByte = 136 NextFieldOffsetInBytes * 8 - FieldOffset; 137 138 bool FitsCompletelyInPreviousByte = 139 BitsInPreviousByte >= FieldValue.getBitWidth(); 140 141 llvm::APInt Tmp = FieldValue; 142 143 if (!FitsCompletelyInPreviousByte) { 144 unsigned NewFieldWidth = FieldSize - BitsInPreviousByte; 145 146 if (CGM.getTargetData().isBigEndian()) { 147 Tmp = Tmp.lshr(NewFieldWidth); 148 Tmp.trunc(BitsInPreviousByte); 149 150 // We want the remaining high bits. 151 FieldValue.trunc(NewFieldWidth); 152 } else { 153 Tmp.trunc(BitsInPreviousByte); 154 155 // We want the remaining low bits. 156 FieldValue = FieldValue.lshr(BitsInPreviousByte); 157 FieldValue.trunc(NewFieldWidth); 158 } 159 } 160 161 Tmp.zext(8); 162 if (CGM.getTargetData().isBigEndian()) { 163 if (FitsCompletelyInPreviousByte) 164 Tmp = Tmp.shl(BitsInPreviousByte - FieldValue.getBitWidth()); 165 } else { 166 Tmp = Tmp.shl(8 - BitsInPreviousByte); 167 } 168 169 // Or in the bits that go into the previous byte. 170 if (llvm::ConstantInt *Val = dyn_cast<llvm::ConstantInt>(Elements.back())) 171 Tmp |= Val->getValue(); 172 else 173 assert(isa<llvm::UndefValue>(Elements.back())); 174 175 Elements.back() = llvm::ConstantInt::get(CGM.getLLVMContext(), Tmp); 176 177 if (FitsCompletelyInPreviousByte) 178 return true; 179 } 180 181 while (FieldValue.getBitWidth() > 8) { 182 llvm::APInt Tmp; 183 184 if (CGM.getTargetData().isBigEndian()) { 185 // We want the high bits. 186 Tmp = FieldValue; 187 Tmp = Tmp.lshr(Tmp.getBitWidth() - 8); 188 Tmp.trunc(8); 189 } else { 190 // We want the low bits. 191 Tmp = FieldValue; 192 Tmp.trunc(8); 193 194 FieldValue = FieldValue.lshr(8); 195 } 196 197 Elements.push_back(llvm::ConstantInt::get(CGM.getLLVMContext(), Tmp)); 198 NextFieldOffsetInBytes++; 199 200 FieldValue.trunc(FieldValue.getBitWidth() - 8); 201 } 202 203 assert(FieldValue.getBitWidth() > 0 && 204 "Should have at least one bit left!"); 205 assert(FieldValue.getBitWidth() <= 8 && 206 "Should not have more than a byte left!"); 207 208 if (FieldValue.getBitWidth() < 8) { 209 if (CGM.getTargetData().isBigEndian()) { 210 unsigned BitWidth = FieldValue.getBitWidth(); 211 212 FieldValue.zext(8); 213 FieldValue = FieldValue << (8 - BitWidth); 214 } else 215 FieldValue.zext(8); 216 } 217 218 // Append the last element. 219 Elements.push_back(llvm::ConstantInt::get(CGM.getLLVMContext(), 220 FieldValue)); 221 NextFieldOffsetInBytes++; 222 return true; 223 } 224 225 void AppendPadding(uint64_t NumBytes) { 226 if (!NumBytes) 227 return; 228 229 const llvm::Type *Ty = llvm::Type::getInt8Ty(CGM.getLLVMContext()); 230 if (NumBytes > 1) 231 Ty = llvm::ArrayType::get(Ty, NumBytes); 232 233 llvm::Constant *C = llvm::UndefValue::get(Ty); 234 Elements.push_back(C); 235 assert(getAlignment(C) == 1 && "Padding must have 1 byte alignment!"); 236 237 NextFieldOffsetInBytes += getSizeInBytes(C); 238 } 239 240 void AppendTailPadding(uint64_t RecordSize) { 241 assert(RecordSize % 8 == 0 && "Invalid record size!"); 242 243 uint64_t RecordSizeInBytes = RecordSize / 8; 244 assert(NextFieldOffsetInBytes <= RecordSizeInBytes && "Size mismatch!"); 245 246 unsigned NumPadBytes = RecordSizeInBytes - NextFieldOffsetInBytes; 247 AppendPadding(NumPadBytes); 248 } 249 250 void ConvertStructToPacked() { 251 std::vector<llvm::Constant *> PackedElements; 252 uint64_t ElementOffsetInBytes = 0; 253 254 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 255 llvm::Constant *C = Elements[i]; 256 257 unsigned ElementAlign = 258 CGM.getTargetData().getABITypeAlignment(C->getType()); 259 uint64_t AlignedElementOffsetInBytes = 260 llvm::RoundUpToAlignment(ElementOffsetInBytes, ElementAlign); 261 262 if (AlignedElementOffsetInBytes > ElementOffsetInBytes) { 263 // We need some padding. 264 uint64_t NumBytes = 265 AlignedElementOffsetInBytes - ElementOffsetInBytes; 266 267 const llvm::Type *Ty = llvm::Type::getInt8Ty(CGM.getLLVMContext()); 268 if (NumBytes > 1) 269 Ty = llvm::ArrayType::get(Ty, NumBytes); 270 271 llvm::Constant *Padding = llvm::UndefValue::get(Ty); 272 PackedElements.push_back(Padding); 273 ElementOffsetInBytes += getSizeInBytes(Padding); 274 } 275 276 PackedElements.push_back(C); 277 ElementOffsetInBytes += getSizeInBytes(C); 278 } 279 280 assert(ElementOffsetInBytes == NextFieldOffsetInBytes && 281 "Packing the struct changed its size!"); 282 283 Elements = PackedElements; 284 LLVMStructAlignment = 1; 285 Packed = true; 286 } 287 288 bool Build(InitListExpr *ILE) { 289 RecordDecl *RD = ILE->getType()->getAs<RecordType>()->getDecl(); 290 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD); 291 292 unsigned FieldNo = 0; 293 unsigned ElementNo = 0; 294 for (RecordDecl::field_iterator Field = RD->field_begin(), 295 FieldEnd = RD->field_end(); 296 ElementNo < ILE->getNumInits() && Field != FieldEnd; 297 ++Field, ++FieldNo) { 298 if (RD->isUnion() && ILE->getInitializedFieldInUnion() != *Field) 299 continue; 300 301 if (Field->isBitField()) { 302 if (!Field->getIdentifier()) 303 continue; 304 305 if (!AppendBitField(*Field, Layout.getFieldOffset(FieldNo), 306 ILE->getInit(ElementNo))) 307 return false; 308 } else { 309 if (!AppendField(*Field, Layout.getFieldOffset(FieldNo), 310 ILE->getInit(ElementNo))) 311 return false; 312 } 313 314 ElementNo++; 315 } 316 317 uint64_t LayoutSizeInBytes = Layout.getSize() / 8; 318 319 if (NextFieldOffsetInBytes > LayoutSizeInBytes) { 320 // If the struct is bigger than the size of the record type, 321 // we must have a flexible array member at the end. 322 assert(RD->hasFlexibleArrayMember() && 323 "Must have flexible array member if struct is bigger than type!"); 324 325 // No tail padding is necessary. 326 return true; 327 } 328 329 uint64_t LLVMSizeInBytes = llvm::RoundUpToAlignment(NextFieldOffsetInBytes, 330 LLVMStructAlignment); 331 332 // Check if we need to convert the struct to a packed struct. 333 if (NextFieldOffsetInBytes <= LayoutSizeInBytes && 334 LLVMSizeInBytes > LayoutSizeInBytes) { 335 assert(!Packed && "Size mismatch!"); 336 337 ConvertStructToPacked(); 338 assert(NextFieldOffsetInBytes == LayoutSizeInBytes && 339 "Converting to packed did not help!"); 340 } 341 342 // Append tail padding if necessary. 343 AppendTailPadding(Layout.getSize()); 344 345 assert(Layout.getSize() / 8 == NextFieldOffsetInBytes && 346 "Tail padding mismatch!"); 347 348 return true; 349 } 350 351 unsigned getAlignment(const llvm::Constant *C) const { 352 if (Packed) 353 return 1; 354 355 return CGM.getTargetData().getABITypeAlignment(C->getType()); 356 } 357 358 uint64_t getSizeInBytes(const llvm::Constant *C) const { 359 return CGM.getTargetData().getTypeAllocSize(C->getType()); 360 } 361 362 public: 363 static llvm::Constant *BuildStruct(CodeGenModule &CGM, CodeGenFunction *CGF, 364 InitListExpr *ILE) { 365 ConstStructBuilder Builder(CGM, CGF); 366 367 if (!Builder.Build(ILE)) 368 return 0; 369 370 llvm::Constant *Result = 371 llvm::ConstantStruct::get(CGM.getLLVMContext(), 372 Builder.Elements, Builder.Packed); 373 374 assert(llvm::RoundUpToAlignment(Builder.NextFieldOffsetInBytes, 375 Builder.getAlignment(Result)) == 376 Builder.getSizeInBytes(Result) && "Size mismatch!"); 377 378 return Result; 379 } 380 }; 381 382 class ConstExprEmitter : 383 public StmtVisitor<ConstExprEmitter, llvm::Constant*> { 384 CodeGenModule &CGM; 385 CodeGenFunction *CGF; 386 llvm::LLVMContext &VMContext; 387 public: 388 ConstExprEmitter(CodeGenModule &cgm, CodeGenFunction *cgf) 389 : CGM(cgm), CGF(cgf), VMContext(cgm.getLLVMContext()) { 390 } 391 392 //===--------------------------------------------------------------------===// 393 // Visitor Methods 394 //===--------------------------------------------------------------------===// 395 396 llvm::Constant *VisitStmt(Stmt *S) { 397 return 0; 398 } 399 400 llvm::Constant *VisitParenExpr(ParenExpr *PE) { 401 return Visit(PE->getSubExpr()); 402 } 403 404 llvm::Constant *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) { 405 return Visit(E->getInitializer()); 406 } 407 408 llvm::Constant *EmitMemberFunctionPointer(CXXMethodDecl *MD) { 409 assert(MD->isInstance() && "Member function must not be static!"); 410 411 const llvm::Type *PtrDiffTy = 412 CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType()); 413 414 llvm::Constant *Values[2]; 415 416 // Get the function pointer (or index if this is a virtual function). 417 if (MD->isVirtual()) { 418 uint64_t Index = CGM.getVtableInfo().getMethodVtableIndex(MD); 419 420 // The pointer is 1 + the virtual table offset in bytes. 421 Values[0] = llvm::ConstantInt::get(PtrDiffTy, (Index * 8) + 1); 422 } else { 423 llvm::Constant *FuncPtr = CGM.GetAddrOfFunction(MD); 424 425 Values[0] = llvm::ConstantExpr::getPtrToInt(FuncPtr, PtrDiffTy); 426 } 427 428 // The adjustment will always be 0. 429 Values[1] = llvm::ConstantInt::get(PtrDiffTy, 0); 430 431 return llvm::ConstantStruct::get(CGM.getLLVMContext(), 432 Values, 2, /*Packed=*/false); 433 } 434 435 llvm::Constant *VisitUnaryAddrOf(UnaryOperator *E) { 436 if (const MemberPointerType *MPT = 437 E->getType()->getAs<MemberPointerType>()) { 438 QualType T = MPT->getPointeeType(); 439 if (T->isFunctionProtoType()) { 440 DeclRefExpr *DRE = cast<DeclRefExpr>(E->getSubExpr()); 441 442 return EmitMemberFunctionPointer(cast<CXXMethodDecl>(DRE->getDecl())); 443 } 444 445 // FIXME: Should we handle other member pointer types here too, 446 // or should they be handled by Expr::Evaluate? 447 } 448 449 return 0; 450 } 451 452 llvm::Constant *VisitBinSub(BinaryOperator *E) { 453 // This must be a pointer/pointer subtraction. This only happens for 454 // address of label. 455 if (!isa<AddrLabelExpr>(E->getLHS()->IgnoreParenNoopCasts(CGM.getContext())) || 456 !isa<AddrLabelExpr>(E->getRHS()->IgnoreParenNoopCasts(CGM.getContext()))) 457 return 0; 458 459 llvm::Constant *LHS = CGM.EmitConstantExpr(E->getLHS(), 460 E->getLHS()->getType(), CGF); 461 llvm::Constant *RHS = CGM.EmitConstantExpr(E->getRHS(), 462 E->getRHS()->getType(), CGF); 463 464 const llvm::Type *ResultType = ConvertType(E->getType()); 465 LHS = llvm::ConstantExpr::getPtrToInt(LHS, ResultType); 466 RHS = llvm::ConstantExpr::getPtrToInt(RHS, ResultType); 467 468 // No need to divide by element size, since addr of label is always void*, 469 // which has size 1 in GNUish. 470 return llvm::ConstantExpr::getSub(LHS, RHS); 471 } 472 473 llvm::Constant *VisitCastExpr(CastExpr* E) { 474 switch (E->getCastKind()) { 475 case CastExpr::CK_ToUnion: { 476 // GCC cast to union extension 477 assert(E->getType()->isUnionType() && 478 "Destination type is not union type!"); 479 const llvm::Type *Ty = ConvertType(E->getType()); 480 Expr *SubExpr = E->getSubExpr(); 481 482 llvm::Constant *C = 483 CGM.EmitConstantExpr(SubExpr, SubExpr->getType(), CGF); 484 if (!C) 485 return 0; 486 487 // Build a struct with the union sub-element as the first member, 488 // and padded to the appropriate size 489 std::vector<llvm::Constant*> Elts; 490 std::vector<const llvm::Type*> Types; 491 Elts.push_back(C); 492 Types.push_back(C->getType()); 493 unsigned CurSize = CGM.getTargetData().getTypeAllocSize(C->getType()); 494 unsigned TotalSize = CGM.getTargetData().getTypeAllocSize(Ty); 495 496 assert(CurSize <= TotalSize && "Union size mismatch!"); 497 if (unsigned NumPadBytes = TotalSize - CurSize) { 498 const llvm::Type *Ty = llvm::Type::getInt8Ty(VMContext); 499 if (NumPadBytes > 1) 500 Ty = llvm::ArrayType::get(Ty, NumPadBytes); 501 502 Elts.push_back(llvm::UndefValue::get(Ty)); 503 Types.push_back(Ty); 504 } 505 506 llvm::StructType* STy = 507 llvm::StructType::get(C->getType()->getContext(), Types, false); 508 return llvm::ConstantStruct::get(STy, Elts); 509 } 510 case CastExpr::CK_NullToMemberPointer: 511 return CGM.EmitNullConstant(E->getType()); 512 513 case CastExpr::CK_BaseToDerivedMemberPointer: { 514 Expr *SubExpr = E->getSubExpr(); 515 516 const MemberPointerType *SrcTy = 517 SubExpr->getType()->getAs<MemberPointerType>(); 518 const MemberPointerType *DestTy = 519 E->getType()->getAs<MemberPointerType>(); 520 521 const CXXRecordDecl *BaseClass = 522 cast<CXXRecordDecl>(cast<RecordType>(SrcTy->getClass())->getDecl()); 523 const CXXRecordDecl *DerivedClass = 524 cast<CXXRecordDecl>(cast<RecordType>(DestTy->getClass())->getDecl()); 525 526 if (SrcTy->getPointeeType()->isFunctionProtoType()) { 527 llvm::Constant *C = 528 CGM.EmitConstantExpr(SubExpr, SubExpr->getType(), CGF); 529 if (!C) 530 return 0; 531 532 llvm::ConstantStruct *CS = cast<llvm::ConstantStruct>(C); 533 534 // Check if we need to update the adjustment. 535 if (llvm::Constant *Offset = CGM.GetCXXBaseClassOffset(DerivedClass, 536 BaseClass)) { 537 llvm::Constant *Values[2]; 538 539 Values[0] = CS->getOperand(0); 540 Values[1] = llvm::ConstantExpr::getAdd(CS->getOperand(1), Offset); 541 return llvm::ConstantStruct::get(CGM.getLLVMContext(), Values, 2, 542 /*Packed=*/false); 543 } 544 545 return CS; 546 } 547 } 548 549 case CastExpr::CK_BitCast: 550 // This must be a member function pointer cast. 551 return Visit(E->getSubExpr()); 552 553 default: { 554 // FIXME: This should be handled by the CK_NoOp cast kind. 555 // Explicit and implicit no-op casts 556 QualType Ty = E->getType(), SubTy = E->getSubExpr()->getType(); 557 if (CGM.getContext().hasSameUnqualifiedType(Ty, SubTy)) 558 return Visit(E->getSubExpr()); 559 560 // Handle integer->integer casts for address-of-label differences. 561 if (Ty->isIntegerType() && SubTy->isIntegerType() && 562 CGF) { 563 llvm::Value *Src = Visit(E->getSubExpr()); 564 if (Src == 0) return 0; 565 566 // Use EmitScalarConversion to perform the conversion. 567 return cast<llvm::Constant>(CGF->EmitScalarConversion(Src, SubTy, Ty)); 568 } 569 570 return 0; 571 } 572 } 573 } 574 575 llvm::Constant *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) { 576 return Visit(DAE->getExpr()); 577 } 578 579 llvm::Constant *EmitArrayInitialization(InitListExpr *ILE) { 580 std::vector<llvm::Constant*> Elts; 581 const llvm::ArrayType *AType = 582 cast<llvm::ArrayType>(ConvertType(ILE->getType())); 583 unsigned NumInitElements = ILE->getNumInits(); 584 // FIXME: Check for wide strings 585 // FIXME: Check for NumInitElements exactly equal to 1?? 586 if (NumInitElements > 0 && 587 (isa<StringLiteral>(ILE->getInit(0)) || 588 isa<ObjCEncodeExpr>(ILE->getInit(0))) && 589 ILE->getType()->getArrayElementTypeNoTypeQual()->isCharType()) 590 return Visit(ILE->getInit(0)); 591 const llvm::Type *ElemTy = AType->getElementType(); 592 unsigned NumElements = AType->getNumElements(); 593 594 // Initialising an array requires us to automatically 595 // initialise any elements that have not been initialised explicitly 596 unsigned NumInitableElts = std::min(NumInitElements, NumElements); 597 598 // Copy initializer elements. 599 unsigned i = 0; 600 bool RewriteType = false; 601 for (; i < NumInitableElts; ++i) { 602 Expr *Init = ILE->getInit(i); 603 llvm::Constant *C = CGM.EmitConstantExpr(Init, Init->getType(), CGF); 604 if (!C) 605 return 0; 606 RewriteType |= (C->getType() != ElemTy); 607 Elts.push_back(C); 608 } 609 610 // Initialize remaining array elements. 611 // FIXME: This doesn't handle member pointers correctly! 612 for (; i < NumElements; ++i) 613 Elts.push_back(llvm::Constant::getNullValue(ElemTy)); 614 615 if (RewriteType) { 616 // FIXME: Try to avoid packing the array 617 std::vector<const llvm::Type*> Types; 618 for (unsigned i = 0; i < Elts.size(); ++i) 619 Types.push_back(Elts[i]->getType()); 620 const llvm::StructType *SType = llvm::StructType::get(AType->getContext(), 621 Types, true); 622 return llvm::ConstantStruct::get(SType, Elts); 623 } 624 625 return llvm::ConstantArray::get(AType, Elts); 626 } 627 628 llvm::Constant *EmitStructInitialization(InitListExpr *ILE) { 629 return ConstStructBuilder::BuildStruct(CGM, CGF, ILE); 630 } 631 632 llvm::Constant *EmitUnionInitialization(InitListExpr *ILE) { 633 return ConstStructBuilder::BuildStruct(CGM, CGF, ILE); 634 } 635 636 llvm::Constant *VisitImplicitValueInitExpr(ImplicitValueInitExpr* E) { 637 return CGM.EmitNullConstant(E->getType()); 638 } 639 640 llvm::Constant *VisitInitListExpr(InitListExpr *ILE) { 641 if (ILE->getType()->isScalarType()) { 642 // We have a scalar in braces. Just use the first element. 643 if (ILE->getNumInits() > 0) { 644 Expr *Init = ILE->getInit(0); 645 return CGM.EmitConstantExpr(Init, Init->getType(), CGF); 646 } 647 return CGM.EmitNullConstant(ILE->getType()); 648 } 649 650 if (ILE->getType()->isArrayType()) 651 return EmitArrayInitialization(ILE); 652 653 if (ILE->getType()->isRecordType()) 654 return EmitStructInitialization(ILE); 655 656 if (ILE->getType()->isUnionType()) 657 return EmitUnionInitialization(ILE); 658 659 // If ILE was a constant vector, we would have handled it already. 660 if (ILE->getType()->isVectorType()) 661 return 0; 662 663 assert(0 && "Unable to handle InitListExpr"); 664 // Get rid of control reaches end of void function warning. 665 // Not reached. 666 return 0; 667 } 668 669 llvm::Constant *VisitStringLiteral(StringLiteral *E) { 670 assert(!E->getType()->isPointerType() && "Strings are always arrays"); 671 672 // This must be a string initializing an array in a static initializer. 673 // Don't emit it as the address of the string, emit the string data itself 674 // as an inline array. 675 return llvm::ConstantArray::get(VMContext, 676 CGM.GetStringForStringLiteral(E), false); 677 } 678 679 llvm::Constant *VisitObjCEncodeExpr(ObjCEncodeExpr *E) { 680 // This must be an @encode initializing an array in a static initializer. 681 // Don't emit it as the address of the string, emit the string data itself 682 // as an inline array. 683 std::string Str; 684 CGM.getContext().getObjCEncodingForType(E->getEncodedType(), Str); 685 const ConstantArrayType *CAT = cast<ConstantArrayType>(E->getType()); 686 687 // Resize the string to the right size, adding zeros at the end, or 688 // truncating as needed. 689 Str.resize(CAT->getSize().getZExtValue(), '\0'); 690 return llvm::ConstantArray::get(VMContext, Str, false); 691 } 692 693 llvm::Constant *VisitUnaryExtension(const UnaryOperator *E) { 694 return Visit(E->getSubExpr()); 695 } 696 697 // Utility methods 698 const llvm::Type *ConvertType(QualType T) { 699 return CGM.getTypes().ConvertType(T); 700 } 701 702 public: 703 llvm::Constant *EmitLValue(Expr *E) { 704 switch (E->getStmtClass()) { 705 default: break; 706 case Expr::CompoundLiteralExprClass: { 707 // Note that due to the nature of compound literals, this is guaranteed 708 // to be the only use of the variable, so we just generate it here. 709 CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E); 710 llvm::Constant* C = Visit(CLE->getInitializer()); 711 // FIXME: "Leaked" on failure. 712 if (C) 713 C = new llvm::GlobalVariable(CGM.getModule(), C->getType(), 714 E->getType().isConstant(CGM.getContext()), 715 llvm::GlobalValue::InternalLinkage, 716 C, ".compoundliteral", 0, false, 717 E->getType().getAddressSpace()); 718 return C; 719 } 720 case Expr::DeclRefExprClass: { 721 NamedDecl *Decl = cast<DeclRefExpr>(E)->getDecl(); 722 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Decl)) 723 return CGM.GetAddrOfFunction(FD); 724 if (const VarDecl* VD = dyn_cast<VarDecl>(Decl)) { 725 // We can never refer to a variable with local storage. 726 if (!VD->hasLocalStorage()) { 727 if (VD->isFileVarDecl() || VD->hasExternalStorage()) 728 return CGM.GetAddrOfGlobalVar(VD); 729 else if (VD->isBlockVarDecl()) { 730 assert(CGF && "Can't access static local vars without CGF"); 731 return CGF->GetAddrOfStaticLocalVar(VD); 732 } 733 } 734 } 735 break; 736 } 737 case Expr::StringLiteralClass: 738 return CGM.GetAddrOfConstantStringFromLiteral(cast<StringLiteral>(E)); 739 case Expr::ObjCEncodeExprClass: 740 return CGM.GetAddrOfConstantStringFromObjCEncode(cast<ObjCEncodeExpr>(E)); 741 case Expr::ObjCStringLiteralClass: { 742 ObjCStringLiteral* SL = cast<ObjCStringLiteral>(E); 743 llvm::Constant *C = CGM.getObjCRuntime().GenerateConstantString(SL); 744 return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType())); 745 } 746 case Expr::PredefinedExprClass: { 747 unsigned Type = cast<PredefinedExpr>(E)->getIdentType(); 748 if (CGF) { 749 LValue Res = CGF->EmitPredefinedFunctionName(Type); 750 return cast<llvm::Constant>(Res.getAddress()); 751 } else if (Type == PredefinedExpr::PrettyFunction) { 752 return CGM.GetAddrOfConstantCString("top level", ".tmp"); 753 } 754 755 return CGM.GetAddrOfConstantCString("", ".tmp"); 756 } 757 case Expr::AddrLabelExprClass: { 758 assert(CGF && "Invalid address of label expression outside function."); 759 llvm::Constant *Ptr = 760 CGF->GetAddrOfLabel(cast<AddrLabelExpr>(E)->getLabel()); 761 return llvm::ConstantExpr::getBitCast(Ptr, ConvertType(E->getType())); 762 } 763 case Expr::CallExprClass: { 764 CallExpr* CE = cast<CallExpr>(E); 765 if (CE->isBuiltinCall(CGM.getContext()) != 766 Builtin::BI__builtin___CFStringMakeConstantString) 767 break; 768 const Expr *Arg = CE->getArg(0)->IgnoreParenCasts(); 769 const StringLiteral *Literal = cast<StringLiteral>(Arg); 770 // FIXME: need to deal with UCN conversion issues. 771 return CGM.GetAddrOfConstantCFString(Literal); 772 } 773 case Expr::BlockExprClass: { 774 std::string FunctionName; 775 if (CGF) 776 FunctionName = CGF->CurFn->getName(); 777 else 778 FunctionName = "global"; 779 780 return CGM.GetAddrOfGlobalBlock(cast<BlockExpr>(E), FunctionName.c_str()); 781 } 782 } 783 784 return 0; 785 } 786 }; 787 788 } // end anonymous namespace. 789 790 llvm::Constant *CodeGenModule::EmitConstantExpr(const Expr *E, 791 QualType DestType, 792 CodeGenFunction *CGF) { 793 Expr::EvalResult Result; 794 795 bool Success = false; 796 797 if (DestType->isReferenceType()) 798 Success = E->EvaluateAsLValue(Result, Context); 799 else 800 Success = E->Evaluate(Result, Context); 801 802 if (Success && !Result.HasSideEffects) { 803 switch (Result.Val.getKind()) { 804 case APValue::Uninitialized: 805 assert(0 && "Constant expressions should be initialized."); 806 return 0; 807 case APValue::LValue: { 808 const llvm::Type *DestTy = getTypes().ConvertTypeForMem(DestType); 809 llvm::Constant *Offset = 810 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), 811 Result.Val.getLValueOffset()); 812 813 llvm::Constant *C; 814 if (const Expr *LVBase = Result.Val.getLValueBase()) { 815 C = ConstExprEmitter(*this, CGF).EmitLValue(const_cast<Expr*>(LVBase)); 816 817 // Apply offset if necessary. 818 if (!Offset->isNullValue()) { 819 const llvm::Type *Type = llvm::Type::getInt8PtrTy(VMContext); 820 llvm::Constant *Casted = llvm::ConstantExpr::getBitCast(C, Type); 821 Casted = llvm::ConstantExpr::getGetElementPtr(Casted, &Offset, 1); 822 C = llvm::ConstantExpr::getBitCast(Casted, C->getType()); 823 } 824 825 // Convert to the appropriate type; this could be an lvalue for 826 // an integer. 827 if (isa<llvm::PointerType>(DestTy)) 828 return llvm::ConstantExpr::getBitCast(C, DestTy); 829 830 return llvm::ConstantExpr::getPtrToInt(C, DestTy); 831 } else { 832 C = Offset; 833 834 // Convert to the appropriate type; this could be an lvalue for 835 // an integer. 836 if (isa<llvm::PointerType>(DestTy)) 837 return llvm::ConstantExpr::getIntToPtr(C, DestTy); 838 839 // If the types don't match this should only be a truncate. 840 if (C->getType() != DestTy) 841 return llvm::ConstantExpr::getTrunc(C, DestTy); 842 843 return C; 844 } 845 } 846 case APValue::Int: { 847 llvm::Constant *C = llvm::ConstantInt::get(VMContext, 848 Result.Val.getInt()); 849 850 if (C->getType() == llvm::Type::getInt1Ty(VMContext)) { 851 const llvm::Type *BoolTy = getTypes().ConvertTypeForMem(E->getType()); 852 C = llvm::ConstantExpr::getZExt(C, BoolTy); 853 } 854 return C; 855 } 856 case APValue::ComplexInt: { 857 llvm::Constant *Complex[2]; 858 859 Complex[0] = llvm::ConstantInt::get(VMContext, 860 Result.Val.getComplexIntReal()); 861 Complex[1] = llvm::ConstantInt::get(VMContext, 862 Result.Val.getComplexIntImag()); 863 864 // FIXME: the target may want to specify that this is packed. 865 return llvm::ConstantStruct::get(VMContext, Complex, 2, false); 866 } 867 case APValue::Float: 868 return llvm::ConstantFP::get(VMContext, Result.Val.getFloat()); 869 case APValue::ComplexFloat: { 870 llvm::Constant *Complex[2]; 871 872 Complex[0] = llvm::ConstantFP::get(VMContext, 873 Result.Val.getComplexFloatReal()); 874 Complex[1] = llvm::ConstantFP::get(VMContext, 875 Result.Val.getComplexFloatImag()); 876 877 // FIXME: the target may want to specify that this is packed. 878 return llvm::ConstantStruct::get(VMContext, Complex, 2, false); 879 } 880 case APValue::Vector: { 881 llvm::SmallVector<llvm::Constant *, 4> Inits; 882 unsigned NumElts = Result.Val.getVectorLength(); 883 884 for (unsigned i = 0; i != NumElts; ++i) { 885 APValue &Elt = Result.Val.getVectorElt(i); 886 if (Elt.isInt()) 887 Inits.push_back(llvm::ConstantInt::get(VMContext, Elt.getInt())); 888 else 889 Inits.push_back(llvm::ConstantFP::get(VMContext, Elt.getFloat())); 890 } 891 return llvm::ConstantVector::get(&Inits[0], Inits.size()); 892 } 893 } 894 } 895 896 llvm::Constant* C = ConstExprEmitter(*this, CGF).Visit(const_cast<Expr*>(E)); 897 if (C && C->getType() == llvm::Type::getInt1Ty(VMContext)) { 898 const llvm::Type *BoolTy = getTypes().ConvertTypeForMem(E->getType()); 899 C = llvm::ConstantExpr::getZExt(C, BoolTy); 900 } 901 return C; 902 } 903 904 static inline bool isDataMemberPointerType(QualType T) { 905 if (const MemberPointerType *MPT = T->getAs<MemberPointerType>()) 906 return !MPT->getPointeeType()->isFunctionType(); 907 908 return false; 909 } 910 911 llvm::Constant *CodeGenModule::EmitNullConstant(QualType T) { 912 // No need to check for member pointers when not compiling C++. 913 if (!getContext().getLangOptions().CPlusPlus) 914 return llvm::Constant::getNullValue(getTypes().ConvertTypeForMem(T)); 915 916 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(T)) { 917 918 QualType ElementTy = CAT->getElementType(); 919 920 // FIXME: Handle arrays of structs that contain member pointers. 921 if (isDataMemberPointerType(Context.getBaseElementType(ElementTy))) { 922 llvm::Constant *Element = EmitNullConstant(ElementTy); 923 uint64_t NumElements = CAT->getSize().getZExtValue(); 924 std::vector<llvm::Constant *> Array(NumElements); 925 for (uint64_t i = 0; i != NumElements; ++i) 926 Array[i] = Element; 927 928 const llvm::ArrayType *ATy = 929 cast<llvm::ArrayType>(getTypes().ConvertTypeForMem(T)); 930 return llvm::ConstantArray::get(ATy, Array); 931 } 932 } 933 934 if (const RecordType *RT = T->getAs<RecordType>()) { 935 const RecordDecl *RD = RT->getDecl(); 936 // FIXME: It would be better if there was a way to explicitly compute the 937 // record layout instead of converting to a type. 938 Types.ConvertTagDeclType(RD); 939 940 const CGRecordLayout &Layout = Types.getCGRecordLayout(RD); 941 if (Layout.containsMemberPointer()) { 942 assert(0 && "FIXME: No support for structs with member pointers yet!"); 943 } 944 } 945 946 // FIXME: Handle structs that contain member pointers. 947 if (isDataMemberPointerType(T)) 948 return llvm::Constant::getAllOnesValue(getTypes().ConvertTypeForMem(T)); 949 950 return llvm::Constant::getNullValue(getTypes().ConvertTypeForMem(T)); 951 } 952