1 //===--- CGExpr.cpp - Emit LLVM Code from 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 Expr nodes as LLVM code. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "CodeGenFunction.h" 15 #include "CodeGenModule.h" 16 #include "clang/AST/AST.h" 17 #include "clang/Basic/TargetInfo.h" 18 #include "llvm/Constants.h" 19 #include "llvm/DerivedTypes.h" 20 #include "llvm/Function.h" 21 #include "llvm/GlobalVariable.h" 22 #include "llvm/Support/MathExtras.h" 23 #include "llvm/Target/TargetData.h" 24 using namespace clang; 25 using namespace CodeGen; 26 27 //===--------------------------------------------------------------------===// 28 // Miscellaneous Helper Methods 29 //===--------------------------------------------------------------------===// 30 31 /// CreateTempAlloca - This creates a alloca and inserts it into the entry 32 /// block. 33 llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(const llvm::Type *Ty, 34 const char *Name) { 35 return new llvm::AllocaInst(Ty, 0, Name, AllocaInsertPt); 36 } 37 38 /// EvaluateExprAsBool - Perform the usual unary conversions on the specified 39 /// expression and compare the result against zero, returning an Int1Ty value. 40 llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) { 41 QualType BoolTy = getContext().BoolTy; 42 if (!E->getType()->isAnyComplexType()) 43 return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy); 44 45 return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(),BoolTy); 46 } 47 48 /// EmitAnyExpr - Emit code to compute the specified expression which can have 49 /// any type. The result is returned as an RValue struct. If this is an 50 /// aggregate expression, the aggloc/agglocvolatile arguments indicate where 51 /// the result should be returned. 52 RValue CodeGenFunction::EmitAnyExpr(const Expr *E, llvm::Value *AggLoc, 53 bool isAggLocVolatile) { 54 if (!hasAggregateLLVMType(E->getType())) 55 return RValue::get(EmitScalarExpr(E)); 56 else if (E->getType()->isAnyComplexType()) 57 return RValue::getComplex(EmitComplexExpr(E)); 58 59 EmitAggExpr(E, AggLoc, isAggLocVolatile); 60 return RValue::getAggregate(AggLoc); 61 } 62 63 64 //===----------------------------------------------------------------------===// 65 // LValue Expression Emission 66 //===----------------------------------------------------------------------===// 67 68 /// EmitLValue - Emit code to compute a designator that specifies the location 69 /// of the expression. 70 /// 71 /// This can return one of two things: a simple address or a bitfield 72 /// reference. In either case, the LLVM Value* in the LValue structure is 73 /// guaranteed to be an LLVM pointer type. 74 /// 75 /// If this returns a bitfield reference, nothing about the pointee type of 76 /// the LLVM value is known: For example, it may not be a pointer to an 77 /// integer. 78 /// 79 /// If this returns a normal address, and if the lvalue's C type is fixed 80 /// size, this method guarantees that the returned pointer type will point to 81 /// an LLVM type of the same size of the lvalue's type. If the lvalue has a 82 /// variable length type, this is not possible. 83 /// 84 LValue CodeGenFunction::EmitLValue(const Expr *E) { 85 switch (E->getStmtClass()) { 86 default: { 87 printf("Statement class: %d\n", E->getStmtClass()); 88 WarnUnsupported(E, "l-value expression"); 89 llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType())); 90 return LValue::MakeAddr(llvm::UndefValue::get(Ty)); 91 } 92 93 case Expr::CallExprClass: return EmitCallExprLValue(cast<CallExpr>(E)); 94 case Expr::DeclRefExprClass: return EmitDeclRefLValue(cast<DeclRefExpr>(E)); 95 case Expr::ParenExprClass:return EmitLValue(cast<ParenExpr>(E)->getSubExpr()); 96 case Expr::PreDefinedExprClass: 97 return EmitPreDefinedLValue(cast<PreDefinedExpr>(E)); 98 case Expr::StringLiteralClass: 99 return EmitStringLiteralLValue(cast<StringLiteral>(E)); 100 101 case Expr::ObjCIvarRefExprClass: 102 return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E)); 103 104 case Expr::UnaryOperatorClass: 105 return EmitUnaryOpLValue(cast<UnaryOperator>(E)); 106 case Expr::ArraySubscriptExprClass: 107 return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E)); 108 case Expr::ExtVectorElementExprClass: 109 return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E)); 110 case Expr::MemberExprClass: return EmitMemberExpr(cast<MemberExpr>(E)); 111 case Expr::CompoundLiteralExprClass: 112 return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E)); 113 } 114 } 115 116 /// EmitLoadOfLValue - Given an expression that represents a value lvalue, 117 /// this method emits the address of the lvalue, then loads the result as an 118 /// rvalue, returning the rvalue. 119 RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, QualType ExprType) { 120 if (LV.isSimple()) { 121 llvm::Value *Ptr = LV.getAddress(); 122 const llvm::Type *EltTy = 123 cast<llvm::PointerType>(Ptr->getType())->getElementType(); 124 125 // Simple scalar l-value. 126 if (EltTy->isFirstClassType()) { 127 llvm::Value *V = Builder.CreateLoad(Ptr, "tmp"); 128 129 // Bool can have different representation in memory than in registers. 130 if (ExprType->isBooleanType()) { 131 if (V->getType() != llvm::Type::Int1Ty) 132 V = Builder.CreateTrunc(V, llvm::Type::Int1Ty, "tobool"); 133 } 134 135 return RValue::get(V); 136 } 137 138 assert(ExprType->isFunctionType() && "Unknown scalar value"); 139 return RValue::get(Ptr); 140 } 141 142 if (LV.isVectorElt()) { 143 llvm::Value *Vec = Builder.CreateLoad(LV.getVectorAddr(), "tmp"); 144 return RValue::get(Builder.CreateExtractElement(Vec, LV.getVectorIdx(), 145 "vecext")); 146 } 147 148 // If this is a reference to a subset of the elements of a vector, either 149 // shuffle the input or extract/insert them as appropriate. 150 if (LV.isExtVectorElt()) 151 return EmitLoadOfExtVectorElementLValue(LV, ExprType); 152 153 if (LV.isBitfield()) 154 return EmitLoadOfBitfieldLValue(LV, ExprType); 155 156 assert(0 && "Unknown LValue type!"); 157 //an invalid RValue, but the assert will 158 //ensure that this point is never reached 159 return RValue(); 160 } 161 162 RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV, 163 QualType ExprType) { 164 llvm::Value *Ptr = LV.getBitfieldAddr(); 165 const llvm::Type *EltTy = 166 cast<llvm::PointerType>(Ptr->getType())->getElementType(); 167 unsigned EltTySize = EltTy->getPrimitiveSizeInBits(); 168 unsigned short BitfieldSize = LV.getBitfieldSize(); 169 unsigned short EndBit = LV.getBitfieldStartBit() + BitfieldSize; 170 171 llvm::Value *V = Builder.CreateLoad(Ptr, "tmp"); 172 173 llvm::Value *ShAmt = llvm::ConstantInt::get(EltTy, EltTySize - EndBit); 174 V = Builder.CreateShl(V, ShAmt, "tmp"); 175 176 ShAmt = llvm::ConstantInt::get(EltTy, EltTySize - BitfieldSize); 177 V = LV.isBitfieldSigned() ? 178 Builder.CreateAShr(V, ShAmt, "tmp") : 179 Builder.CreateLShr(V, ShAmt, "tmp"); 180 181 // The bitfield type and the normal type differ when the storage sizes 182 // differ (currently just _Bool). 183 V = Builder.CreateIntCast(V, ConvertType(ExprType), false, "tmp"); 184 185 return RValue::get(V); 186 } 187 188 // If this is a reference to a subset of the elements of a vector, either 189 // shuffle the input or extract/insert them as appropriate. 190 RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV, 191 QualType ExprType) { 192 llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddr(), "tmp"); 193 194 const llvm::Constant *Elts = LV.getExtVectorElts(); 195 196 // If the result of the expression is a non-vector type, we must be 197 // extracting a single element. Just codegen as an extractelement. 198 const VectorType *ExprVT = ExprType->getAsVectorType(); 199 if (!ExprVT) { 200 unsigned InIdx = ExtVectorElementExpr::getAccessedFieldNo(0, Elts); 201 llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx); 202 return RValue::get(Builder.CreateExtractElement(Vec, Elt, "tmp")); 203 } 204 205 // If the source and destination have the same number of elements, use a 206 // vector shuffle instead of insert/extracts. 207 unsigned NumResultElts = ExprVT->getNumElements(); 208 unsigned NumSourceElts = 209 cast<llvm::VectorType>(Vec->getType())->getNumElements(); 210 211 if (NumResultElts == NumSourceElts) { 212 llvm::SmallVector<llvm::Constant*, 4> Mask; 213 for (unsigned i = 0; i != NumResultElts; ++i) { 214 unsigned InIdx = ExtVectorElementExpr::getAccessedFieldNo(i, Elts); 215 Mask.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx)); 216 } 217 218 llvm::Value *MaskV = llvm::ConstantVector::get(&Mask[0], Mask.size()); 219 Vec = Builder.CreateShuffleVector(Vec, 220 llvm::UndefValue::get(Vec->getType()), 221 MaskV, "tmp"); 222 return RValue::get(Vec); 223 } 224 225 // Start out with an undef of the result type. 226 llvm::Value *Result = llvm::UndefValue::get(ConvertType(ExprType)); 227 228 // Extract/Insert each element of the result. 229 for (unsigned i = 0; i != NumResultElts; ++i) { 230 unsigned InIdx = ExtVectorElementExpr::getAccessedFieldNo(i, Elts); 231 llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx); 232 Elt = Builder.CreateExtractElement(Vec, Elt, "tmp"); 233 234 llvm::Value *OutIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i); 235 Result = Builder.CreateInsertElement(Result, Elt, OutIdx, "tmp"); 236 } 237 238 return RValue::get(Result); 239 } 240 241 242 243 /// EmitStoreThroughLValue - Store the specified rvalue into the specified 244 /// lvalue, where both are guaranteed to the have the same type, and that type 245 /// is 'Ty'. 246 void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst, 247 QualType Ty) { 248 if (!Dst.isSimple()) { 249 if (Dst.isVectorElt()) { 250 // Read/modify/write the vector, inserting the new element. 251 // FIXME: Volatility. 252 llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddr(), "tmp"); 253 Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(), 254 Dst.getVectorIdx(), "vecins"); 255 Builder.CreateStore(Vec, Dst.getVectorAddr()); 256 return; 257 } 258 259 // If this is an update of extended vector elements, insert them as 260 // appropriate. 261 if (Dst.isExtVectorElt()) 262 return EmitStoreThroughExtVectorComponentLValue(Src, Dst, Ty); 263 264 if (Dst.isBitfield()) 265 return EmitStoreThroughBitfieldLValue(Src, Dst, Ty); 266 267 assert(0 && "Unknown LValue type"); 268 } 269 270 llvm::Value *DstAddr = Dst.getAddress(); 271 assert(Src.isScalar() && "Can't emit an agg store with this method"); 272 // FIXME: Handle volatility etc. 273 const llvm::Type *SrcTy = Src.getScalarVal()->getType(); 274 const llvm::PointerType *DstPtr = cast<llvm::PointerType>(DstAddr->getType()); 275 const llvm::Type *AddrTy = DstPtr->getElementType(); 276 unsigned AS = DstPtr->getAddressSpace(); 277 278 if (AddrTy != SrcTy) 279 DstAddr = Builder.CreateBitCast(DstAddr, 280 llvm::PointerType::get(SrcTy, AS), 281 "storetmp"); 282 Builder.CreateStore(Src.getScalarVal(), DstAddr); 283 } 284 285 void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst, 286 QualType Ty) { 287 unsigned short StartBit = Dst.getBitfieldStartBit(); 288 unsigned short BitfieldSize = Dst.getBitfieldSize(); 289 llvm::Value *Ptr = Dst.getBitfieldAddr(); 290 291 llvm::Value *NewVal = Src.getScalarVal(); 292 llvm::Value *OldVal = Builder.CreateLoad(Ptr, "tmp"); 293 294 // The bitfield type and the normal type differ when the storage sizes 295 // differ (currently just _Bool). 296 const llvm::Type *EltTy = OldVal->getType(); 297 unsigned EltTySize = CGM.getTargetData().getABITypeSizeInBits(EltTy); 298 299 NewVal = Builder.CreateIntCast(NewVal, EltTy, false, "tmp"); 300 301 // Move the bits into the appropriate location 302 llvm::Value *ShAmt = llvm::ConstantInt::get(EltTy, StartBit); 303 NewVal = Builder.CreateShl(NewVal, ShAmt, "tmp"); 304 305 llvm::Constant *Mask = llvm::ConstantInt::get( 306 llvm::APInt::getBitsSet(EltTySize, StartBit, 307 StartBit + BitfieldSize)); 308 309 // Mask out any bits that shouldn't be set in the result. 310 NewVal = Builder.CreateAnd(NewVal, Mask, "tmp"); 311 312 // Next, mask out the bits this bit-field should include from the old value. 313 Mask = llvm::ConstantExpr::getNot(Mask); 314 OldVal = Builder.CreateAnd(OldVal, Mask, "tmp"); 315 316 // Finally, merge the two together and store it. 317 NewVal = Builder.CreateOr(OldVal, NewVal, "tmp"); 318 319 Builder.CreateStore(NewVal, Ptr); 320 } 321 322 void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src, 323 LValue Dst, 324 QualType Ty) { 325 // This access turns into a read/modify/write of the vector. Load the input 326 // value now. 327 llvm::Value *Vec = Builder.CreateLoad(Dst.getExtVectorAddr(), "tmp"); 328 // FIXME: Volatility. 329 const llvm::Constant *Elts = Dst.getExtVectorElts(); 330 331 llvm::Value *SrcVal = Src.getScalarVal(); 332 333 if (const VectorType *VTy = Ty->getAsVectorType()) { 334 unsigned NumSrcElts = VTy->getNumElements(); 335 336 // Extract/Insert each element. 337 for (unsigned i = 0; i != NumSrcElts; ++i) { 338 llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, i); 339 Elt = Builder.CreateExtractElement(SrcVal, Elt, "tmp"); 340 341 unsigned Idx = ExtVectorElementExpr::getAccessedFieldNo(i, Elts); 342 llvm::Value *OutIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, Idx); 343 Vec = Builder.CreateInsertElement(Vec, Elt, OutIdx, "tmp"); 344 } 345 } else { 346 // If the Src is a scalar (not a vector) it must be updating one element. 347 unsigned InIdx = ExtVectorElementExpr::getAccessedFieldNo(0, Elts); 348 llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx); 349 Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt, "tmp"); 350 } 351 352 Builder.CreateStore(Vec, Dst.getExtVectorAddr()); 353 } 354 355 356 LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) { 357 const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()); 358 359 if (VD && (VD->isBlockVarDecl() || isa<ParmVarDecl>(VD))) { 360 if (VD->getStorageClass() == VarDecl::Extern) 361 return LValue::MakeAddr(CGM.GetAddrOfGlobalVar(VD, false)); 362 else { 363 llvm::Value *V = LocalDeclMap[VD]; 364 assert(V && "BlockVarDecl not entered in LocalDeclMap?"); 365 return LValue::MakeAddr(V); 366 } 367 } else if (VD && VD->isFileVarDecl()) { 368 return LValue::MakeAddr(CGM.GetAddrOfGlobalVar(VD, false)); 369 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl())) { 370 return LValue::MakeAddr(CGM.GetAddrOfFunctionDecl(FD, false)); 371 } 372 assert(0 && "Unimp declref"); 373 //an invalid LValue, but the assert will 374 //ensure that this point is never reached. 375 return LValue(); 376 } 377 378 LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) { 379 // __extension__ doesn't affect lvalue-ness. 380 if (E->getOpcode() == UnaryOperator::Extension) 381 return EmitLValue(E->getSubExpr()); 382 383 switch (E->getOpcode()) { 384 default: assert(0 && "Unknown unary operator lvalue!"); 385 case UnaryOperator::Deref: 386 return LValue::MakeAddr(EmitScalarExpr(E->getSubExpr())); 387 case UnaryOperator::Real: 388 case UnaryOperator::Imag: 389 LValue LV = EmitLValue(E->getSubExpr()); 390 unsigned Idx = E->getOpcode() == UnaryOperator::Imag; 391 return LValue::MakeAddr(Builder.CreateStructGEP(LV.getAddress(), 392 Idx, "idx")); 393 } 394 } 395 396 LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) { 397 assert(!E->isWide() && "FIXME: Wide strings not supported yet!"); 398 const char *StrData = E->getStrData(); 399 unsigned Len = E->getByteLength(); 400 std::string StringLiteral(StrData, StrData+Len); 401 return LValue::MakeAddr(CGM.GetAddrOfConstantString(StringLiteral)); 402 } 403 404 LValue CodeGenFunction::EmitPreDefinedLValue(const PreDefinedExpr *E) { 405 std::string FunctionName; 406 if(const FunctionDecl *FD = dyn_cast<FunctionDecl>(CurFuncDecl)) { 407 FunctionName = FD->getName(); 408 } 409 else { 410 assert(0 && "Attempting to load predefined constant for invalid decl type"); 411 } 412 std::string GlobalVarName; 413 414 switch (E->getIdentType()) { 415 default: 416 assert(0 && "unknown pre-defined ident type"); 417 case PreDefinedExpr::Func: 418 GlobalVarName = "__func__."; 419 break; 420 case PreDefinedExpr::Function: 421 GlobalVarName = "__FUNCTION__."; 422 break; 423 case PreDefinedExpr::PrettyFunction: 424 // FIXME:: Demangle C++ method names 425 GlobalVarName = "__PRETTY_FUNCTION__."; 426 break; 427 } 428 429 GlobalVarName += FunctionName; 430 431 // FIXME: Can cache/reuse these within the module. 432 llvm::Constant *C=llvm::ConstantArray::get(FunctionName); 433 434 // Create a global variable for this. 435 C = new llvm::GlobalVariable(C->getType(), true, 436 llvm::GlobalValue::InternalLinkage, 437 C, GlobalVarName, CurFn->getParent()); 438 return LValue::MakeAddr(C); 439 } 440 441 LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E) { 442 // The index must always be an integer, which is not an aggregate. Emit it. 443 llvm::Value *Idx = EmitScalarExpr(E->getIdx()); 444 445 // If the base is a vector type, then we are forming a vector element lvalue 446 // with this subscript. 447 if (E->getLHS()->getType()->isVectorType()) { 448 // Emit the vector as an lvalue to get its address. 449 LValue LHS = EmitLValue(E->getLHS()); 450 assert(LHS.isSimple() && "Can only subscript lvalue vectors here!"); 451 // FIXME: This should properly sign/zero/extend or truncate Idx to i32. 452 return LValue::MakeVectorElt(LHS.getAddress(), Idx); 453 } 454 455 // The base must be a pointer, which is not an aggregate. Emit it. 456 llvm::Value *Base = EmitScalarExpr(E->getBase()); 457 458 // Extend or truncate the index type to 32 or 64-bits. 459 QualType IdxTy = E->getIdx()->getType(); 460 bool IdxSigned = IdxTy->isSignedIntegerType(); 461 unsigned IdxBitwidth = cast<llvm::IntegerType>(Idx->getType())->getBitWidth(); 462 if (IdxBitwidth != LLVMPointerWidth) 463 Idx = Builder.CreateIntCast(Idx, llvm::IntegerType::get(LLVMPointerWidth), 464 IdxSigned, "idxprom"); 465 466 // We know that the pointer points to a type of the correct size, unless the 467 // size is a VLA. 468 if (!E->getType()->isConstantSizeType()) 469 assert(0 && "VLA idx not implemented"); 470 return LValue::MakeAddr(Builder.CreateGEP(Base, Idx, "arrayidx")); 471 } 472 473 static 474 llvm::Constant *GenerateConstantVector(llvm::SmallVector<unsigned, 4> &Elts) { 475 llvm::SmallVector<llvm::Constant *, 4> CElts; 476 477 for (unsigned i = 0, e = Elts.size(); i != e; ++i) 478 CElts.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, Elts[i])); 479 480 return llvm::ConstantVector::get(&CElts[0], CElts.size()); 481 } 482 483 LValue CodeGenFunction:: 484 EmitExtVectorElementExpr(const ExtVectorElementExpr *E) { 485 // Emit the base vector as an l-value. 486 LValue Base = EmitLValue(E->getBase()); 487 488 // Encode the element access list into a vector of unsigned indices. 489 llvm::SmallVector<unsigned, 4> Indices; 490 E->getEncodedElementAccess(Indices); 491 492 if (Base.isSimple()) { 493 llvm::Constant *CV = GenerateConstantVector(Indices); 494 return LValue::MakeExtVectorElt(Base.getAddress(), CV); 495 } 496 assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!"); 497 498 llvm::Constant *BaseElts = Base.getExtVectorElts(); 499 llvm::SmallVector<llvm::Constant *, 4> CElts; 500 501 for (unsigned i = 0, e = Indices.size(); i != e; ++i) { 502 if (isa<llvm::ConstantAggregateZero>(BaseElts)) 503 CElts.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0)); 504 else 505 CElts.push_back(BaseElts->getOperand(Indices[i])); 506 } 507 llvm::Constant *CV = llvm::ConstantVector::get(&CElts[0], CElts.size()); 508 return LValue::MakeExtVectorElt(Base.getExtVectorAddr(), CV); 509 } 510 511 LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) { 512 bool isUnion = false; 513 Expr *BaseExpr = E->getBase(); 514 llvm::Value *BaseValue = NULL; 515 516 // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar. 517 if (E->isArrow()) { 518 BaseValue = EmitScalarExpr(BaseExpr); 519 const PointerType *PTy = 520 cast<PointerType>(BaseExpr->getType().getCanonicalType()); 521 if (PTy->getPointeeType()->isUnionType()) 522 isUnion = true; 523 } 524 else { 525 LValue BaseLV = EmitLValue(BaseExpr); 526 // FIXME: this isn't right for bitfields. 527 BaseValue = BaseLV.getAddress(); 528 if (BaseExpr->getType()->isUnionType()) 529 isUnion = true; 530 } 531 532 FieldDecl *Field = E->getMemberDecl(); 533 return EmitLValueForField(BaseValue, Field, isUnion); 534 } 535 536 LValue CodeGenFunction::EmitLValueForField(llvm::Value* BaseValue, 537 FieldDecl* Field, 538 bool isUnion) 539 { 540 llvm::Value *V; 541 unsigned idx = CGM.getTypes().getLLVMFieldNo(Field); 542 543 if (!Field->isBitField()) { 544 V = Builder.CreateStructGEP(BaseValue, idx, "tmp"); 545 } else { 546 // FIXME: CodeGenTypes should expose a method to get the appropriate 547 // type for FieldTy (the appropriate type is ABI-dependent). 548 unsigned EltTySize = 549 CGM.getTargetData().getABITypeSizeInBits(ConvertType(Field->getType())); 550 const llvm::Type *FieldTy = llvm::IntegerType::get(EltTySize); 551 const llvm::PointerType *BaseTy = 552 cast<llvm::PointerType>(BaseValue->getType()); 553 unsigned AS = BaseTy->getAddressSpace(); 554 BaseValue = Builder.CreateBitCast(BaseValue, 555 llvm::PointerType::get(FieldTy, AS), 556 "tmp"); 557 V = Builder.CreateGEP(BaseValue, 558 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx), 559 "tmp"); 560 } 561 562 // Match union field type. 563 if (isUnion) { 564 const llvm::Type * FieldTy = ConvertType(Field->getType()); 565 const llvm::PointerType * BaseTy = 566 cast<llvm::PointerType>(BaseValue->getType()); 567 if (FieldTy != BaseTy->getElementType()) { 568 unsigned AS = BaseTy->getAddressSpace(); 569 V = Builder.CreateBitCast(V, 570 llvm::PointerType::get(FieldTy, AS), 571 "tmp"); 572 } 573 } 574 575 if (!Field->isBitField()) 576 return LValue::MakeAddr(V); 577 578 CodeGenTypes::BitFieldInfo bitFieldInfo = 579 CGM.getTypes().getBitFieldInfo(Field); 580 return LValue::MakeBitfield(V, bitFieldInfo.Begin, bitFieldInfo.Size, 581 Field->getType()->isSignedIntegerType()); 582 } 583 584 LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr* E) { 585 const llvm::Type *LTy = ConvertType(E->getType()); 586 llvm::Value *DeclPtr = CreateTempAlloca(LTy, ".compoundliteral"); 587 588 const Expr* InitExpr = E->getInitializer(); 589 LValue Result = LValue::MakeAddr(DeclPtr); 590 591 if (E->getType()->isComplexType()) { 592 EmitComplexExprIntoAddr(InitExpr, DeclPtr, false); 593 } else if (hasAggregateLLVMType(E->getType())) { 594 EmitAnyExpr(InitExpr, DeclPtr, false); 595 } else { 596 EmitStoreThroughLValue(EmitAnyExpr(InitExpr), Result, E->getType()); 597 } 598 599 return Result; 600 } 601 602 //===--------------------------------------------------------------------===// 603 // Expression Emission 604 //===--------------------------------------------------------------------===// 605 606 607 RValue CodeGenFunction::EmitCallExpr(const CallExpr *E) { 608 if (const ImplicitCastExpr *IcExpr = 609 dyn_cast<const ImplicitCastExpr>(E->getCallee())) 610 if (const DeclRefExpr *DRExpr = 611 dyn_cast<const DeclRefExpr>(IcExpr->getSubExpr())) 612 if (const FunctionDecl *FDecl = 613 dyn_cast<const FunctionDecl>(DRExpr->getDecl())) 614 if (unsigned builtinID = FDecl->getIdentifier()->getBuiltinID()) 615 return EmitBuiltinExpr(builtinID, E); 616 617 llvm::Value *Callee = EmitScalarExpr(E->getCallee()); 618 return EmitCallExpr(Callee, E->getCallee()->getType(), 619 E->arg_begin(), E->getNumArgs()); 620 } 621 622 RValue CodeGenFunction::EmitCallExpr(Expr *FnExpr, Expr *const *Args, 623 unsigned NumArgs) { 624 llvm::Value *Callee = EmitScalarExpr(FnExpr); 625 return EmitCallExpr(Callee, FnExpr->getType(), Args, NumArgs); 626 } 627 628 LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) { 629 // Can only get l-value for call expression returning aggregate type 630 RValue RV = EmitCallExpr(E); 631 return LValue::MakeAddr(RV.getAggregateAddr()); 632 } 633 634 LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) { 635 // Objective-C objects are traditionally C structures with their layout 636 // defined at compile-time. In some implementations, their layout is not 637 // defined until run time in order to allow instance variables to be added to 638 // a class without recompiling all of the subclasses. If this is the case 639 // then the CGObjCRuntime subclass must return true to LateBoundIvars and 640 // implement the lookup itself. 641 if (CGM.getObjCRuntime()->LateBoundIVars()) { 642 assert(0 && "FIXME: Implement support for late-bound instance variables"); 643 return LValue(); // Not reached. 644 } 645 646 // Get a structure type for the object 647 QualType ExprTy = E->getBase()->getType(); 648 const llvm::Type *ObjectType = ConvertType(ExprTy); 649 // TODO: Add a special case for isa (index 0) 650 // Work out which index the ivar is 651 const ObjCIvarDecl *Decl = E->getDecl(); 652 unsigned Index = CGM.getTypes().getLLVMFieldNo(Decl); 653 654 // Get object pointer and coerce object pointer to correct type. 655 llvm::Value *Object = EmitLValue(E->getBase()).getAddress(); 656 Object = Builder.CreateLoad(Object, E->getDecl()->getName()); 657 if (Object->getType() != ObjectType) 658 Object = Builder.CreateBitCast(Object, ObjectType); 659 660 661 // Return a pointer to the right element. 662 return LValue::MakeAddr(Builder.CreateStructGEP(Object, Index, 663 Decl->getName())); 664 } 665 666 RValue CodeGenFunction::EmitCallExpr(llvm::Value *Callee, QualType FnType, 667 Expr *const *ArgExprs, unsigned NumArgs) { 668 // The callee type will always be a pointer to function type, get the function 669 // type. 670 FnType = cast<PointerType>(FnType.getCanonicalType())->getPointeeType(); 671 QualType ResultType = cast<FunctionType>(FnType)->getResultType(); 672 673 llvm::SmallVector<llvm::Value*, 16> Args; 674 675 // Handle struct-return functions by passing a pointer to the location that 676 // we would like to return into. 677 if (hasAggregateLLVMType(ResultType)) { 678 // Create a temporary alloca to hold the result of the call. :( 679 Args.push_back(CreateTempAlloca(ConvertType(ResultType))); 680 // FIXME: set the stret attribute on the argument. 681 } 682 683 for (unsigned i = 0, e = NumArgs; i != e; ++i) { 684 QualType ArgTy = ArgExprs[i]->getType(); 685 686 if (!hasAggregateLLVMType(ArgTy)) { 687 // Scalar argument is passed by-value. 688 Args.push_back(EmitScalarExpr(ArgExprs[i])); 689 } else if (ArgTy->isAnyComplexType()) { 690 // Make a temporary alloca to pass the argument. 691 llvm::Value *DestMem = CreateTempAlloca(ConvertType(ArgTy)); 692 EmitComplexExprIntoAddr(ArgExprs[i], DestMem, false); 693 Args.push_back(DestMem); 694 } else { 695 llvm::Value *DestMem = CreateTempAlloca(ConvertType(ArgTy)); 696 EmitAggExpr(ArgExprs[i], DestMem, false); 697 Args.push_back(DestMem); 698 } 699 } 700 701 llvm::CallInst *CI = Builder.CreateCall(Callee,&Args[0],&Args[0]+Args.size()); 702 if (const llvm::Function *F = dyn_cast<llvm::Function>(Callee)) 703 CI->setCallingConv(F->getCallingConv()); 704 if (CI->getType() != llvm::Type::VoidTy) 705 CI->setName("call"); 706 else if (ResultType->isAnyComplexType()) 707 return RValue::getComplex(LoadComplexFromAddr(Args[0], false)); 708 else if (hasAggregateLLVMType(ResultType)) 709 // Struct return. 710 return RValue::getAggregate(Args[0]); 711 else { 712 // void return. 713 assert(ResultType->isVoidType() && "Should only have a void expr here"); 714 CI = 0; 715 } 716 717 return RValue::get(CI); 718 } 719