CGExpr.cpp 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211
  1. //===--- CGExpr.cpp - Emit LLVM Code from Expressions ---------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file was developed by Chris Lattner and is distributed under
  6. // the University of Illinois Open Source License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This contains code to emit Expr nodes as LLVM code.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "CodeGenFunction.h"
  14. #include "CodeGenModule.h"
  15. #include "clang/AST/AST.h"
  16. #include "llvm/Constants.h"
  17. #include "llvm/DerivedTypes.h"
  18. #include "llvm/Function.h"
  19. #include "llvm/GlobalVariable.h"
  20. using namespace clang;
  21. using namespace CodeGen;
  22. //===--------------------------------------------------------------------===//
  23. // Miscellaneous Helper Methods
  24. //===--------------------------------------------------------------------===//
  25. /// CreateTempAlloca - This creates a alloca and inserts it into the entry
  26. /// block.
  27. llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(const llvm::Type *Ty,
  28. const char *Name) {
  29. return new llvm::AllocaInst(Ty, 0, Name, AllocaInsertPt);
  30. }
  31. /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
  32. /// expression and compare the result against zero, returning an Int1Ty value.
  33. llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
  34. QualType Ty;
  35. RValue Val = EmitExprWithUsualUnaryConversions(E, Ty);
  36. return ConvertScalarValueToBool(Val, Ty);
  37. }
  38. /// EmitLoadOfComplex - Given an RValue reference for a complex, emit code to
  39. /// load the real and imaginary pieces, returning them as Real/Imag.
  40. void CodeGenFunction::EmitLoadOfComplex(RValue V,
  41. llvm::Value *&Real, llvm::Value *&Imag){
  42. llvm::Value *Ptr = V.getAggregateAddr();
  43. llvm::Constant *Zero = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
  44. llvm::Constant *One = llvm::ConstantInt::get(llvm::Type::Int32Ty, 1);
  45. llvm::Value *RealPtr = Builder.CreateGEP(Ptr, Zero, Zero, "realp");
  46. llvm::Value *ImagPtr = Builder.CreateGEP(Ptr, Zero, One, "imagp");
  47. // FIXME: Handle volatility.
  48. Real = Builder.CreateLoad(RealPtr, "real");
  49. Imag = Builder.CreateLoad(ImagPtr, "imag");
  50. }
  51. /// EmitStoreOfComplex - Store the specified real/imag parts into the
  52. /// specified value pointer.
  53. void CodeGenFunction::EmitStoreOfComplex(llvm::Value *Real, llvm::Value *Imag,
  54. llvm::Value *ResPtr) {
  55. llvm::Constant *Zero = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
  56. llvm::Constant *One = llvm::ConstantInt::get(llvm::Type::Int32Ty, 1);
  57. llvm::Value *RealPtr = Builder.CreateGEP(ResPtr, Zero, Zero, "real");
  58. llvm::Value *ImagPtr = Builder.CreateGEP(ResPtr, Zero, One, "imag");
  59. // FIXME: Handle volatility.
  60. Builder.CreateStore(Real, RealPtr);
  61. Builder.CreateStore(Imag, ImagPtr);
  62. }
  63. //===--------------------------------------------------------------------===//
  64. // Conversions
  65. //===--------------------------------------------------------------------===//
  66. /// EmitConversion - Convert the value specied by Val, whose type is ValTy, to
  67. /// the type specified by DstTy, following the rules of C99 6.3.
  68. RValue CodeGenFunction::EmitConversion(RValue Val, QualType ValTy,
  69. QualType DstTy) {
  70. ValTy = ValTy.getCanonicalType();
  71. DstTy = DstTy.getCanonicalType();
  72. if (ValTy == DstTy) return Val;
  73. // Handle conversions to bool first, they are special: comparisons against 0.
  74. if (const BuiltinType *DestBT = dyn_cast<BuiltinType>(DstTy))
  75. if (DestBT->getKind() == BuiltinType::Bool)
  76. return RValue::get(ConvertScalarValueToBool(Val, ValTy));
  77. // Handle pointer conversions next: pointers can only be converted to/from
  78. // other pointers and integers.
  79. if (isa<PointerType>(DstTy)) {
  80. const llvm::Type *DestTy = ConvertType(DstTy);
  81. // The source value may be an integer, or a pointer.
  82. assert(Val.isScalar() && "Can only convert from integer or pointer");
  83. if (isa<llvm::PointerType>(Val.getVal()->getType()))
  84. return RValue::get(Builder.CreateBitCast(Val.getVal(), DestTy, "conv"));
  85. assert(ValTy->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
  86. return RValue::get(Builder.CreatePtrToInt(Val.getVal(), DestTy, "conv"));
  87. }
  88. if (isa<PointerType>(ValTy)) {
  89. // Must be an ptr to int cast.
  90. const llvm::Type *DestTy = ConvertType(DstTy);
  91. assert(isa<llvm::IntegerType>(DestTy) && "not ptr->int?");
  92. return RValue::get(Builder.CreateIntToPtr(Val.getVal(), DestTy, "conv"));
  93. }
  94. // Finally, we have the arithmetic types: real int/float and complex
  95. // int/float. Handle real->real conversions first, they are the most
  96. // common.
  97. if (Val.isScalar() && DstTy->isRealType()) {
  98. // We know that these are representable as scalars in LLVM, convert to LLVM
  99. // types since they are easier to reason about.
  100. llvm::Value *SrcVal = Val.getVal();
  101. const llvm::Type *DestTy = ConvertType(DstTy);
  102. if (SrcVal->getType() == DestTy) return Val;
  103. llvm::Value *Result;
  104. if (isa<llvm::IntegerType>(SrcVal->getType())) {
  105. bool InputSigned = ValTy->isSignedIntegerType();
  106. if (isa<llvm::IntegerType>(DestTy))
  107. Result = Builder.CreateIntCast(SrcVal, DestTy, InputSigned, "conv");
  108. else if (InputSigned)
  109. Result = Builder.CreateSIToFP(SrcVal, DestTy, "conv");
  110. else
  111. Result = Builder.CreateUIToFP(SrcVal, DestTy, "conv");
  112. } else {
  113. assert(SrcVal->getType()->isFloatingPoint() && "Unknown real conversion");
  114. if (isa<llvm::IntegerType>(DestTy)) {
  115. if (DstTy->isSignedIntegerType())
  116. Result = Builder.CreateFPToSI(SrcVal, DestTy, "conv");
  117. else
  118. Result = Builder.CreateFPToUI(SrcVal, DestTy, "conv");
  119. } else {
  120. assert(DestTy->isFloatingPoint() && "Unknown real conversion");
  121. if (DestTy->getTypeID() < SrcVal->getType()->getTypeID())
  122. Result = Builder.CreateFPTrunc(SrcVal, DestTy, "conv");
  123. else
  124. Result = Builder.CreateFPExt(SrcVal, DestTy, "conv");
  125. }
  126. }
  127. return RValue::get(Result);
  128. }
  129. assert(0 && "FIXME: We don't support complex conversions yet!");
  130. }
  131. /// ConvertScalarValueToBool - Convert the specified expression value to a
  132. /// boolean (i1) truth value. This is equivalent to "Val == 0".
  133. llvm::Value *CodeGenFunction::ConvertScalarValueToBool(RValue Val, QualType Ty){
  134. Ty = Ty.getCanonicalType();
  135. llvm::Value *Result;
  136. if (const BuiltinType *BT = dyn_cast<BuiltinType>(Ty)) {
  137. switch (BT->getKind()) {
  138. default: assert(0 && "Unknown scalar value");
  139. case BuiltinType::Bool:
  140. Result = Val.getVal();
  141. // Bool is already evaluated right.
  142. assert(Result->getType() == llvm::Type::Int1Ty &&
  143. "Unexpected bool value type!");
  144. return Result;
  145. case BuiltinType::Char_S:
  146. case BuiltinType::Char_U:
  147. case BuiltinType::SChar:
  148. case BuiltinType::UChar:
  149. case BuiltinType::Short:
  150. case BuiltinType::UShort:
  151. case BuiltinType::Int:
  152. case BuiltinType::UInt:
  153. case BuiltinType::Long:
  154. case BuiltinType::ULong:
  155. case BuiltinType::LongLong:
  156. case BuiltinType::ULongLong:
  157. // Code below handles simple integers.
  158. break;
  159. case BuiltinType::Float:
  160. case BuiltinType::Double:
  161. case BuiltinType::LongDouble: {
  162. // Compare against 0.0 for fp scalars.
  163. Result = Val.getVal();
  164. llvm::Value *Zero = llvm::Constant::getNullValue(Result->getType());
  165. // FIXME: llvm-gcc produces a une comparison: validate this is right.
  166. Result = Builder.CreateFCmpUNE(Result, Zero, "tobool");
  167. return Result;
  168. }
  169. }
  170. } else if (isa<PointerType>(Ty) ||
  171. cast<TagType>(Ty)->getDecl()->getKind() == Decl::Enum) {
  172. // Code below handles this fine.
  173. } else {
  174. assert(isa<ComplexType>(Ty) && "Unknwon type!");
  175. assert(0 && "FIXME: comparisons against complex not implemented yet");
  176. }
  177. // Usual case for integers, pointers, and enums: compare against zero.
  178. Result = Val.getVal();
  179. // Because of the type rules of C, we often end up computing a logical value,
  180. // then zero extending it to int, then wanting it as a logical value again.
  181. // Optimize this common case.
  182. if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(Result)) {
  183. if (ZI->getOperand(0)->getType() == llvm::Type::Int1Ty) {
  184. Result = ZI->getOperand(0);
  185. ZI->eraseFromParent();
  186. return Result;
  187. }
  188. }
  189. llvm::Value *Zero = llvm::Constant::getNullValue(Result->getType());
  190. return Builder.CreateICmpNE(Result, Zero, "tobool");
  191. }
  192. //===----------------------------------------------------------------------===//
  193. // LValue Expression Emission
  194. //===----------------------------------------------------------------------===//
  195. /// EmitLValue - Emit code to compute a designator that specifies the location
  196. /// of the expression.
  197. ///
  198. /// This can return one of two things: a simple address or a bitfield
  199. /// reference. In either case, the LLVM Value* in the LValue structure is
  200. /// guaranteed to be an LLVM pointer type.
  201. ///
  202. /// If this returns a bitfield reference, nothing about the pointee type of
  203. /// the LLVM value is known: For example, it may not be a pointer to an
  204. /// integer.
  205. ///
  206. /// If this returns a normal address, and if the lvalue's C type is fixed
  207. /// size, this method guarantees that the returned pointer type will point to
  208. /// an LLVM type of the same size of the lvalue's type. If the lvalue has a
  209. /// variable length type, this is not possible.
  210. ///
  211. LValue CodeGenFunction::EmitLValue(const Expr *E) {
  212. switch (E->getStmtClass()) {
  213. default:
  214. fprintf(stderr, "Unimplemented lvalue expr!\n");
  215. E->dump();
  216. return LValue::MakeAddr(llvm::UndefValue::get(
  217. llvm::PointerType::get(llvm::Type::Int32Ty)));
  218. case Expr::DeclRefExprClass: return EmitDeclRefLValue(cast<DeclRefExpr>(E));
  219. case Expr::ParenExprClass:return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
  220. case Expr::StringLiteralClass:
  221. return EmitStringLiteralLValue(cast<StringLiteral>(E));
  222. case Expr::UnaryOperatorClass:
  223. return EmitUnaryOpLValue(cast<UnaryOperator>(E));
  224. case Expr::ArraySubscriptExprClass:
  225. return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
  226. }
  227. }
  228. /// EmitLoadOfLValue - Given an expression that represents a value lvalue,
  229. /// this method emits the address of the lvalue, then loads the result as an
  230. /// rvalue, returning the rvalue.
  231. RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, QualType ExprType) {
  232. ExprType = ExprType.getCanonicalType();
  233. if (LV.isSimple()) {
  234. llvm::Value *Ptr = LV.getAddress();
  235. const llvm::Type *EltTy =
  236. cast<llvm::PointerType>(Ptr->getType())->getElementType();
  237. // Simple scalar l-value.
  238. if (EltTy->isFirstClassType())
  239. return RValue::get(Builder.CreateLoad(Ptr, "tmp"));
  240. // Otherwise, we have an aggregate lvalue.
  241. return RValue::getAggregate(Ptr);
  242. }
  243. if (LV.isVectorElt()) {
  244. llvm::Value *Vec = Builder.CreateLoad(LV.getVectorAddr(), "tmp");
  245. return RValue::get(Builder.CreateExtractElement(Vec, LV.getVectorIdx(),
  246. "vecext"));
  247. }
  248. assert(0 && "Bitfield ref not impl!");
  249. }
  250. RValue CodeGenFunction::EmitLoadOfLValue(const Expr *E) {
  251. return EmitLoadOfLValue(EmitLValue(E), E->getType());
  252. }
  253. /// EmitStoreThroughLValue - Store the specified rvalue into the specified
  254. /// lvalue, where both are guaranteed to the have the same type, and that type
  255. /// is 'Ty'.
  256. void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
  257. QualType Ty) {
  258. if (Dst.isVectorElt()) {
  259. // Read/modify/write the vector, inserting the new element.
  260. // FIXME: Volatility.
  261. llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddr(), "tmp");
  262. Vec = Builder.CreateInsertElement(Vec, Src.getVal(),
  263. Dst.getVectorIdx(), "vecins");
  264. Builder.CreateStore(Vec, Dst.getVectorAddr());
  265. return;
  266. }
  267. assert(Dst.isSimple() && "FIXME: Don't support store to bitfield yet");
  268. llvm::Value *DstAddr = Dst.getAddress();
  269. if (Src.isScalar()) {
  270. // FIXME: Handle volatility etc.
  271. const llvm::Type *SrcTy = Src.getVal()->getType();
  272. const llvm::Type *AddrTy =
  273. cast<llvm::PointerType>(DstAddr->getType())->getElementType();
  274. if (AddrTy != SrcTy)
  275. DstAddr = Builder.CreateBitCast(DstAddr, llvm::PointerType::get(SrcTy),
  276. "storetmp");
  277. Builder.CreateStore(Src.getVal(), DstAddr);
  278. return;
  279. }
  280. // Don't use memcpy for complex numbers.
  281. if (Ty->isComplexType()) {
  282. llvm::Value *Real, *Imag;
  283. EmitLoadOfComplex(Src, Real, Imag);
  284. EmitStoreOfComplex(Real, Imag, Dst.getAddress());
  285. return;
  286. }
  287. // Aggregate assignment turns into llvm.memcpy.
  288. const llvm::Type *SBP = llvm::PointerType::get(llvm::Type::Int8Ty);
  289. llvm::Value *SrcAddr = Src.getAggregateAddr();
  290. if (DstAddr->getType() != SBP)
  291. DstAddr = Builder.CreateBitCast(DstAddr, SBP, "tmp");
  292. if (SrcAddr->getType() != SBP)
  293. SrcAddr = Builder.CreateBitCast(SrcAddr, SBP, "tmp");
  294. unsigned Align = 1; // FIXME: Compute type alignments.
  295. unsigned Size = 1234; // FIXME: Compute type sizes.
  296. // FIXME: Handle variable sized types.
  297. const llvm::Type *IntPtr = llvm::IntegerType::get(LLVMPointerWidth);
  298. llvm::Value *SizeVal = llvm::ConstantInt::get(IntPtr, Size);
  299. llvm::Value *MemCpyOps[4] = {
  300. DstAddr, SrcAddr, SizeVal,llvm::ConstantInt::get(llvm::Type::Int32Ty, Align)
  301. };
  302. Builder.CreateCall(CGM.getMemCpyFn(), MemCpyOps, 4);
  303. }
  304. LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
  305. const Decl *D = E->getDecl();
  306. if (isa<BlockVarDecl>(D) || isa<ParmVarDecl>(D)) {
  307. llvm::Value *V = LocalDeclMap[D];
  308. assert(V && "BlockVarDecl not entered in LocalDeclMap?");
  309. return LValue::MakeAddr(V);
  310. } else if (isa<FunctionDecl>(D) || isa<FileVarDecl>(D)) {
  311. return LValue::MakeAddr(CGM.GetAddrOfGlobalDecl(D));
  312. }
  313. assert(0 && "Unimp declref");
  314. }
  315. LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
  316. // __extension__ doesn't affect lvalue-ness.
  317. if (E->getOpcode() == UnaryOperator::Extension)
  318. return EmitLValue(E->getSubExpr());
  319. assert(E->getOpcode() == UnaryOperator::Deref &&
  320. "'*' is the only unary operator that produces an lvalue");
  321. return LValue::MakeAddr(EmitExpr(E->getSubExpr()).getVal());
  322. }
  323. LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
  324. assert(!E->isWide() && "FIXME: Wide strings not supported yet!");
  325. const char *StrData = E->getStrData();
  326. unsigned Len = E->getByteLength();
  327. // FIXME: Can cache/reuse these within the module.
  328. llvm::Constant *C=llvm::ConstantArray::get(std::string(StrData, StrData+Len));
  329. // Create a global variable for this.
  330. C = new llvm::GlobalVariable(C->getType(), true,
  331. llvm::GlobalValue::InternalLinkage,
  332. C, ".str", CurFn->getParent());
  333. llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
  334. llvm::Constant *Zeros[] = { Zero, Zero };
  335. C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
  336. return LValue::MakeAddr(C);
  337. }
  338. LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E) {
  339. // The index must always be a pointer or integer, neither of which is an
  340. // aggregate. Emit it.
  341. QualType IdxTy;
  342. llvm::Value *Idx =
  343. EmitExprWithUsualUnaryConversions(E->getIdx(), IdxTy).getVal();
  344. // If the base is a vector type, then we are forming a vector element lvalue
  345. // with this subscript.
  346. if (E->getBase()->getType()->isVectorType()) {
  347. // Emit the vector as an lvalue to get its address.
  348. LValue Base = EmitLValue(E->getBase());
  349. assert(Base.isSimple() && "Can only subscript lvalue vectors here!");
  350. // FIXME: This should properly sign/zero/extend or truncate Idx to i32.
  351. return LValue::MakeVectorElt(Base.getAddress(), Idx);
  352. }
  353. // At this point, the base must be a pointer or integer, neither of which are
  354. // aggregates. Emit it.
  355. QualType BaseTy;
  356. llvm::Value *Base =
  357. EmitExprWithUsualUnaryConversions(E->getBase(), BaseTy).getVal();
  358. // Usually the base is the pointer type, but sometimes it is the index.
  359. // Canonicalize to have the pointer as the base.
  360. if (isa<llvm::PointerType>(Idx->getType())) {
  361. std::swap(Base, Idx);
  362. std::swap(BaseTy, IdxTy);
  363. }
  364. // The pointer is now the base. Extend or truncate the index type to 32 or
  365. // 64-bits.
  366. bool IdxSigned = IdxTy->isSignedIntegerType();
  367. unsigned IdxBitwidth = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
  368. if (IdxBitwidth != LLVMPointerWidth)
  369. Idx = Builder.CreateIntCast(Idx, llvm::IntegerType::get(LLVMPointerWidth),
  370. IdxSigned, "idxprom");
  371. // We know that the pointer points to a type of the correct size, unless the
  372. // size is a VLA.
  373. if (!E->getType()->isConstantSizeType())
  374. assert(0 && "VLA idx not implemented");
  375. return LValue::MakeAddr(Builder.CreateGEP(Base, Idx, "arrayidx"));
  376. }
  377. //===--------------------------------------------------------------------===//
  378. // Expression Emission
  379. //===--------------------------------------------------------------------===//
  380. RValue CodeGenFunction::EmitExpr(const Expr *E) {
  381. assert(E && "Null expression?");
  382. switch (E->getStmtClass()) {
  383. default:
  384. fprintf(stderr, "Unimplemented expr!\n");
  385. E->dump();
  386. return RValue::get(llvm::UndefValue::get(llvm::Type::Int32Ty));
  387. // l-values.
  388. case Expr::DeclRefExprClass:
  389. // DeclRef's of EnumConstantDecl's are simple rvalues.
  390. if (const EnumConstantDecl *EC =
  391. dyn_cast<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
  392. return RValue::get(llvm::ConstantInt::get(EC->getInitVal()));
  393. return EmitLoadOfLValue(E);
  394. case Expr::ArraySubscriptExprClass:
  395. return EmitArraySubscriptExprRV(cast<ArraySubscriptExpr>(E));
  396. case Expr::StringLiteralClass:
  397. return RValue::get(EmitLValue(E).getAddress());
  398. // Leaf expressions.
  399. case Expr::IntegerLiteralClass:
  400. return EmitIntegerLiteral(cast<IntegerLiteral>(E));
  401. case Expr::FloatingLiteralClass:
  402. return EmitFloatingLiteral(cast<FloatingLiteral>(E));
  403. // Operators.
  404. case Expr::ParenExprClass:
  405. return EmitExpr(cast<ParenExpr>(E)->getSubExpr());
  406. case Expr::UnaryOperatorClass:
  407. return EmitUnaryOperator(cast<UnaryOperator>(E));
  408. case Expr::CastExprClass:
  409. return EmitCastExpr(cast<CastExpr>(E));
  410. case Expr::CallExprClass:
  411. return EmitCallExpr(cast<CallExpr>(E));
  412. case Expr::BinaryOperatorClass:
  413. return EmitBinaryOperator(cast<BinaryOperator>(E));
  414. }
  415. }
  416. RValue CodeGenFunction::EmitIntegerLiteral(const IntegerLiteral *E) {
  417. return RValue::get(llvm::ConstantInt::get(E->getValue()));
  418. }
  419. RValue CodeGenFunction::EmitFloatingLiteral(const FloatingLiteral *E) {
  420. return RValue::get(llvm::ConstantFP::get(ConvertType(E->getType()),
  421. E->getValue()));
  422. }
  423. RValue CodeGenFunction::EmitArraySubscriptExprRV(const ArraySubscriptExpr *E) {
  424. // Emit subscript expressions in rvalue context's. For most cases, this just
  425. // loads the lvalue formed by the subscript expr. However, we have to be
  426. // careful, because the base of a vector subscript is occasionally an rvalue,
  427. // so we can't get it as an lvalue.
  428. if (!E->getBase()->getType()->isVectorType())
  429. return EmitLoadOfLValue(E);
  430. // Handle the vector case. The base must be a vector, the index must be an
  431. // integer value.
  432. QualType BaseTy, IdxTy;
  433. llvm::Value *Base =
  434. EmitExprWithUsualUnaryConversions(E->getBase(), BaseTy).getVal();
  435. llvm::Value *Idx =
  436. EmitExprWithUsualUnaryConversions(E->getIdx(), IdxTy).getVal();
  437. // FIXME: Convert Idx to i32 type.
  438. return RValue::get(Builder.CreateExtractElement(Base, Idx, "vecext"));
  439. }
  440. RValue CodeGenFunction::EmitCastExpr(const CastExpr *E) {
  441. QualType SrcTy;
  442. RValue Src = EmitExprWithUsualUnaryConversions(E->getSubExpr(), SrcTy);
  443. // If the destination is void, just evaluate the source.
  444. if (E->getType()->isVoidType())
  445. return RValue::getAggregate(0);
  446. return EmitConversion(Src, SrcTy, E->getType());
  447. }
  448. RValue CodeGenFunction::EmitCallExpr(const CallExpr *E) {
  449. QualType CalleeTy;
  450. llvm::Value *Callee =
  451. EmitExprWithUsualUnaryConversions(E->getCallee(), CalleeTy).getVal();
  452. // The callee type will always be a pointer to function type, get the function
  453. // type.
  454. CalleeTy = cast<PointerType>(CalleeTy.getCanonicalType())->getPointeeType();
  455. // Get information about the argument types.
  456. FunctionTypeProto::arg_type_iterator ArgTyIt = 0, ArgTyEnd = 0;
  457. // Calling unprototyped functions provides no argument info.
  458. if (const FunctionTypeProto *FTP = dyn_cast<FunctionTypeProto>(CalleeTy)) {
  459. ArgTyIt = FTP->arg_type_begin();
  460. ArgTyEnd = FTP->arg_type_end();
  461. }
  462. llvm::SmallVector<llvm::Value*, 16> Args;
  463. // FIXME: Handle struct return.
  464. for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
  465. QualType ArgTy;
  466. RValue ArgVal = EmitExprWithUsualUnaryConversions(E->getArg(i), ArgTy);
  467. // If this argument has prototype information, convert it.
  468. if (ArgTyIt != ArgTyEnd) {
  469. ArgVal = EmitConversion(ArgVal, ArgTy, *ArgTyIt++);
  470. } else {
  471. // Otherwise, if passing through "..." or to a function with no prototype,
  472. // perform the "default argument promotions" (C99 6.5.2.2p6), which
  473. // includes the usual unary conversions, but also promotes float to
  474. // double.
  475. if (const BuiltinType *BT =
  476. dyn_cast<BuiltinType>(ArgTy.getCanonicalType())) {
  477. if (BT->getKind() == BuiltinType::Float)
  478. ArgVal = RValue::get(Builder.CreateFPExt(ArgVal.getVal(),
  479. llvm::Type::DoubleTy,"tmp"));
  480. }
  481. }
  482. if (ArgVal.isScalar())
  483. Args.push_back(ArgVal.getVal());
  484. else // Pass by-address. FIXME: Set attribute bit on call.
  485. Args.push_back(ArgVal.getAggregateAddr());
  486. }
  487. llvm::Value *V = Builder.CreateCall(Callee, &Args[0], Args.size());
  488. if (V->getType() != llvm::Type::VoidTy)
  489. V->setName("call");
  490. // FIXME: Struct return;
  491. return RValue::get(V);
  492. }
  493. //===----------------------------------------------------------------------===//
  494. // Unary Operator Emission
  495. //===----------------------------------------------------------------------===//
  496. RValue CodeGenFunction::EmitExprWithUsualUnaryConversions(const Expr *E,
  497. QualType &ResTy) {
  498. ResTy = E->getType().getCanonicalType();
  499. if (isa<FunctionType>(ResTy)) { // C99 6.3.2.1p4
  500. // Functions are promoted to their address.
  501. ResTy = getContext().getPointerType(ResTy);
  502. return RValue::get(EmitLValue(E).getAddress());
  503. } else if (const ArrayType *ary = dyn_cast<ArrayType>(ResTy)) {
  504. // C99 6.3.2.1p3
  505. ResTy = getContext().getPointerType(ary->getElementType());
  506. // FIXME: For now we assume that all source arrays map to LLVM arrays. This
  507. // will not true when we add support for VLAs.
  508. llvm::Value *V = EmitLValue(E).getAddress(); // Bitfields can't be arrays.
  509. assert(isa<llvm::PointerType>(V->getType()) &&
  510. isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
  511. ->getElementType()) &&
  512. "Doesn't support VLAs yet!");
  513. llvm::Constant *Idx0 = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
  514. return RValue::get(Builder.CreateGEP(V, Idx0, Idx0, "arraydecay"));
  515. } else if (ResTy->isPromotableIntegerType()) { // C99 6.3.1.1p2
  516. // FIXME: this probably isn't right, pending clarification from Steve.
  517. llvm::Value *Val = EmitExpr(E).getVal();
  518. // If the input is a signed integer, sign extend to the destination.
  519. if (ResTy->isSignedIntegerType()) {
  520. Val = Builder.CreateSExt(Val, LLVMIntTy, "promote");
  521. } else {
  522. // This handles unsigned types, including bool.
  523. Val = Builder.CreateZExt(Val, LLVMIntTy, "promote");
  524. }
  525. ResTy = getContext().IntTy;
  526. return RValue::get(Val);
  527. }
  528. // Otherwise, this is a float, double, int, struct, etc.
  529. return EmitExpr(E);
  530. }
  531. RValue CodeGenFunction::EmitUnaryOperator(const UnaryOperator *E) {
  532. switch (E->getOpcode()) {
  533. default:
  534. printf("Unimplemented unary expr!\n");
  535. E->dump();
  536. return RValue::get(llvm::UndefValue::get(llvm::Type::Int32Ty));
  537. // FIXME: pre/post inc/dec
  538. case UnaryOperator::AddrOf: return EmitUnaryAddrOf(E);
  539. case UnaryOperator::Deref : return EmitLoadOfLValue(E);
  540. case UnaryOperator::Plus : return EmitUnaryPlus(E);
  541. case UnaryOperator::Minus : return EmitUnaryMinus(E);
  542. case UnaryOperator::Not : return EmitUnaryNot(E);
  543. case UnaryOperator::LNot : return EmitUnaryLNot(E);
  544. // FIXME: SIZEOF/ALIGNOF(expr).
  545. // FIXME: real/imag
  546. case UnaryOperator::Extension: return EmitExpr(E->getSubExpr());
  547. }
  548. }
  549. /// C99 6.5.3.2
  550. RValue CodeGenFunction::EmitUnaryAddrOf(const UnaryOperator *E) {
  551. // The address of the operand is just its lvalue. It cannot be a bitfield.
  552. return RValue::get(EmitLValue(E->getSubExpr()).getAddress());
  553. }
  554. RValue CodeGenFunction::EmitUnaryPlus(const UnaryOperator *E) {
  555. // Unary plus just performs promotions on its arithmetic operand.
  556. QualType Ty;
  557. return EmitExprWithUsualUnaryConversions(E->getSubExpr(), Ty);
  558. }
  559. RValue CodeGenFunction::EmitUnaryMinus(const UnaryOperator *E) {
  560. // Unary minus performs promotions, then negates its arithmetic operand.
  561. QualType Ty;
  562. RValue V = EmitExprWithUsualUnaryConversions(E->getSubExpr(), Ty);
  563. if (V.isScalar())
  564. return RValue::get(Builder.CreateNeg(V.getVal(), "neg"));
  565. assert(0 && "FIXME: This doesn't handle complex operands yet");
  566. }
  567. RValue CodeGenFunction::EmitUnaryNot(const UnaryOperator *E) {
  568. // Unary not performs promotions, then complements its integer operand.
  569. QualType Ty;
  570. RValue V = EmitExprWithUsualUnaryConversions(E->getSubExpr(), Ty);
  571. if (V.isScalar())
  572. return RValue::get(Builder.CreateNot(V.getVal(), "neg"));
  573. assert(0 && "FIXME: This doesn't handle integer complex operands yet (GNU)");
  574. }
  575. /// C99 6.5.3.3
  576. RValue CodeGenFunction::EmitUnaryLNot(const UnaryOperator *E) {
  577. // Compare operand to zero.
  578. llvm::Value *BoolVal = EvaluateExprAsBool(E->getSubExpr());
  579. // Invert value.
  580. // TODO: Could dynamically modify easy computations here. For example, if
  581. // the operand is an icmp ne, turn into icmp eq.
  582. BoolVal = Builder.CreateNot(BoolVal, "lnot");
  583. // ZExt result to int.
  584. return RValue::get(Builder.CreateZExt(BoolVal, LLVMIntTy, "lnot.ext"));
  585. }
  586. //===--------------------------------------------------------------------===//
  587. // Binary Operator Emission
  588. //===--------------------------------------------------------------------===//
  589. // FIXME describe.
  590. QualType CodeGenFunction::
  591. EmitUsualArithmeticConversions(const BinaryOperator *E, RValue &LHS,
  592. RValue &RHS) {
  593. QualType LHSType, RHSType;
  594. LHS = EmitExprWithUsualUnaryConversions(E->getLHS(), LHSType);
  595. RHS = EmitExprWithUsualUnaryConversions(E->getRHS(), RHSType);
  596. // If both operands have the same source type, we're done already.
  597. if (LHSType == RHSType) return LHSType;
  598. // If either side is a non-arithmetic type (e.g. a pointer), we are done.
  599. // The caller can deal with this (e.g. pointer + int).
  600. if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
  601. return LHSType;
  602. // At this point, we have two different arithmetic types.
  603. // Handle complex types first (C99 6.3.1.8p1).
  604. if (LHSType->isComplexType() || RHSType->isComplexType()) {
  605. assert(0 && "FIXME: complex types unimp");
  606. #if 0
  607. // if we have an integer operand, the result is the complex type.
  608. if (rhs->isIntegerType())
  609. return lhs;
  610. if (lhs->isIntegerType())
  611. return rhs;
  612. return Context.maxComplexType(lhs, rhs);
  613. #endif
  614. }
  615. // If neither operand is complex, they must be scalars.
  616. llvm::Value *LHSV = LHS.getVal();
  617. llvm::Value *RHSV = RHS.getVal();
  618. // If the LLVM types are already equal, then they only differed in sign, or it
  619. // was something like char/signed char or double/long double.
  620. if (LHSV->getType() == RHSV->getType())
  621. return LHSType;
  622. // Now handle "real" floating types (i.e. float, double, long double).
  623. if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) {
  624. // if we have an integer operand, the result is the real floating type, and
  625. // the integer converts to FP.
  626. if (RHSType->isIntegerType()) {
  627. // Promote the RHS to an FP type of the LHS, with the sign following the
  628. // RHS.
  629. if (RHSType->isSignedIntegerType())
  630. RHS = RValue::get(Builder.CreateSIToFP(RHSV,LHSV->getType(),"promote"));
  631. else
  632. RHS = RValue::get(Builder.CreateUIToFP(RHSV,LHSV->getType(),"promote"));
  633. return LHSType;
  634. }
  635. if (LHSType->isIntegerType()) {
  636. // Promote the LHS to an FP type of the RHS, with the sign following the
  637. // LHS.
  638. if (LHSType->isSignedIntegerType())
  639. LHS = RValue::get(Builder.CreateSIToFP(LHSV,RHSV->getType(),"promote"));
  640. else
  641. LHS = RValue::get(Builder.CreateUIToFP(LHSV,RHSV->getType(),"promote"));
  642. return RHSType;
  643. }
  644. // Otherwise, they are two FP types. Promote the smaller operand to the
  645. // bigger result.
  646. QualType BiggerType = ASTContext::maxFloatingType(LHSType, RHSType);
  647. if (BiggerType == LHSType)
  648. RHS = RValue::get(Builder.CreateFPExt(RHSV, LHSV->getType(), "promote"));
  649. else
  650. LHS = RValue::get(Builder.CreateFPExt(LHSV, RHSV->getType(), "promote"));
  651. return BiggerType;
  652. }
  653. // Finally, we have two integer types that are different according to C. Do
  654. // a sign or zero extension if needed.
  655. // Otherwise, one type is smaller than the other.
  656. QualType ResTy = ASTContext::maxIntegerType(LHSType, RHSType);
  657. if (LHSType == ResTy) {
  658. if (RHSType->isSignedIntegerType())
  659. RHS = RValue::get(Builder.CreateSExt(RHSV, LHSV->getType(), "promote"));
  660. else
  661. RHS = RValue::get(Builder.CreateZExt(RHSV, LHSV->getType(), "promote"));
  662. } else {
  663. assert(RHSType == ResTy && "Unknown conversion");
  664. if (LHSType->isSignedIntegerType())
  665. LHS = RValue::get(Builder.CreateSExt(LHSV, RHSV->getType(), "promote"));
  666. else
  667. LHS = RValue::get(Builder.CreateZExt(LHSV, RHSV->getType(), "promote"));
  668. }
  669. return ResTy;
  670. }
  671. /// EmitCompoundAssignmentOperands - Compound assignment operations (like +=)
  672. /// are strange in that the result of the operation is not the same type as the
  673. /// intermediate computation. This function emits the LHS and RHS operands of
  674. /// the compound assignment, promoting them to their common computation type.
  675. ///
  676. /// Since the LHS is an lvalue, and the result is stored back through it, we
  677. /// return the lvalue as well as the LHS/RHS rvalues. On return, the LHS and
  678. /// RHS values are both in the computation type for the operator.
  679. void CodeGenFunction::
  680. EmitCompoundAssignmentOperands(const CompoundAssignOperator *E,
  681. LValue &LHSLV, RValue &LHS, RValue &RHS) {
  682. LHSLV = EmitLValue(E->getLHS());
  683. // Load the LHS and RHS operands.
  684. QualType LHSTy = E->getLHS()->getType();
  685. LHS = EmitLoadOfLValue(LHSLV, LHSTy);
  686. QualType RHSTy;
  687. RHS = EmitExprWithUsualUnaryConversions(E->getRHS(), RHSTy);
  688. // Shift operands do the usual unary conversions, but do not do the binary
  689. // conversions.
  690. if (E->isShiftAssignOp()) {
  691. // FIXME: This is broken. Implicit conversions should be made explicit,
  692. // so that this goes away. This causes us to reload the LHS.
  693. LHS = EmitExprWithUsualUnaryConversions(E->getLHS(), LHSTy);
  694. }
  695. // Convert the LHS and RHS to the common evaluation type.
  696. LHS = EmitConversion(LHS, LHSTy, E->getComputationType());
  697. RHS = EmitConversion(RHS, RHSTy, E->getComputationType());
  698. }
  699. /// EmitCompoundAssignmentResult - Given a result value in the computation type,
  700. /// truncate it down to the actual result type, store it through the LHS lvalue,
  701. /// and return it.
  702. RValue CodeGenFunction::
  703. EmitCompoundAssignmentResult(const CompoundAssignOperator *E,
  704. LValue LHSLV, RValue ResV) {
  705. // Truncate back to the destination type.
  706. if (E->getComputationType() != E->getType())
  707. ResV = EmitConversion(ResV, E->getComputationType(), E->getType());
  708. // Store the result value into the LHS.
  709. EmitStoreThroughLValue(ResV, LHSLV, E->getType());
  710. // Return the result.
  711. return ResV;
  712. }
  713. RValue CodeGenFunction::EmitBinaryOperator(const BinaryOperator *E) {
  714. RValue LHS, RHS;
  715. switch (E->getOpcode()) {
  716. default:
  717. fprintf(stderr, "Unimplemented binary expr!\n");
  718. E->dump();
  719. return RValue::get(llvm::UndefValue::get(llvm::Type::Int32Ty));
  720. case BinaryOperator::Mul:
  721. EmitUsualArithmeticConversions(E, LHS, RHS);
  722. return EmitMul(LHS, RHS, E->getType());
  723. case BinaryOperator::Div:
  724. EmitUsualArithmeticConversions(E, LHS, RHS);
  725. return EmitDiv(LHS, RHS, E->getType());
  726. case BinaryOperator::Rem:
  727. EmitUsualArithmeticConversions(E, LHS, RHS);
  728. return EmitRem(LHS, RHS, E->getType());
  729. case BinaryOperator::Add:
  730. // FIXME: This doesn't handle ptr+int etc yet.
  731. EmitUsualArithmeticConversions(E, LHS, RHS);
  732. return EmitAdd(LHS, RHS, E->getType());
  733. case BinaryOperator::Sub:
  734. // FIXME: This doesn't handle ptr-int etc yet.
  735. EmitUsualArithmeticConversions(E, LHS, RHS);
  736. return EmitSub(LHS, RHS, E->getType());
  737. case BinaryOperator::Shl:
  738. EmitShiftOperands(E, LHS, RHS);
  739. return EmitShl(LHS, RHS, E->getType());
  740. case BinaryOperator::Shr:
  741. EmitShiftOperands(E, LHS, RHS);
  742. return EmitShr(LHS, RHS, E->getType());
  743. case BinaryOperator::And:
  744. EmitUsualArithmeticConversions(E, LHS, RHS);
  745. return EmitAnd(LHS, RHS, E->getType());
  746. case BinaryOperator::Xor:
  747. EmitUsualArithmeticConversions(E, LHS, RHS);
  748. return EmitXor(LHS, RHS, E->getType());
  749. case BinaryOperator::Or :
  750. EmitUsualArithmeticConversions(E, LHS, RHS);
  751. return EmitOr(LHS, RHS, E->getType());
  752. case BinaryOperator::LAnd: return EmitBinaryLAnd(E);
  753. case BinaryOperator::LOr: return EmitBinaryLOr(E);
  754. case BinaryOperator::LT:
  755. return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_ULT,
  756. llvm::ICmpInst::ICMP_SLT,
  757. llvm::FCmpInst::FCMP_OLT);
  758. case BinaryOperator::GT:
  759. return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_UGT,
  760. llvm::ICmpInst::ICMP_SGT,
  761. llvm::FCmpInst::FCMP_OGT);
  762. case BinaryOperator::LE:
  763. return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_ULE,
  764. llvm::ICmpInst::ICMP_SLE,
  765. llvm::FCmpInst::FCMP_OLE);
  766. case BinaryOperator::GE:
  767. return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_UGE,
  768. llvm::ICmpInst::ICMP_SGE,
  769. llvm::FCmpInst::FCMP_OGE);
  770. case BinaryOperator::EQ:
  771. return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_EQ,
  772. llvm::ICmpInst::ICMP_EQ,
  773. llvm::FCmpInst::FCMP_OEQ);
  774. case BinaryOperator::NE:
  775. return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_NE,
  776. llvm::ICmpInst::ICMP_NE,
  777. llvm::FCmpInst::FCMP_UNE);
  778. case BinaryOperator::Assign:
  779. return EmitBinaryAssign(E);
  780. case BinaryOperator::MulAssign: {
  781. const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
  782. LValue LHSLV;
  783. EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
  784. LHS = EmitMul(LHS, RHS, CAO->getComputationType());
  785. return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
  786. }
  787. case BinaryOperator::DivAssign: {
  788. const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
  789. LValue LHSLV;
  790. EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
  791. LHS = EmitDiv(LHS, RHS, CAO->getComputationType());
  792. return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
  793. }
  794. case BinaryOperator::RemAssign: {
  795. const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
  796. LValue LHSLV;
  797. EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
  798. LHS = EmitRem(LHS, RHS, CAO->getComputationType());
  799. return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
  800. }
  801. case BinaryOperator::AddAssign: {
  802. const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
  803. LValue LHSLV;
  804. EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
  805. LHS = EmitAdd(LHS, RHS, CAO->getComputationType());
  806. return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
  807. }
  808. case BinaryOperator::SubAssign: {
  809. const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
  810. LValue LHSLV;
  811. EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
  812. LHS = EmitSub(LHS, RHS, CAO->getComputationType());
  813. return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
  814. }
  815. case BinaryOperator::ShlAssign: {
  816. const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
  817. LValue LHSLV;
  818. EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
  819. LHS = EmitShl(LHS, RHS, CAO->getComputationType());
  820. return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
  821. }
  822. case BinaryOperator::ShrAssign: {
  823. const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
  824. LValue LHSLV;
  825. EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
  826. LHS = EmitShr(LHS, RHS, CAO->getComputationType());
  827. return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
  828. }
  829. case BinaryOperator::AndAssign: {
  830. const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
  831. LValue LHSLV;
  832. EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
  833. LHS = EmitAnd(LHS, RHS, CAO->getComputationType());
  834. return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
  835. }
  836. case BinaryOperator::OrAssign: {
  837. const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
  838. LValue LHSLV;
  839. EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
  840. LHS = EmitOr(LHS, RHS, CAO->getComputationType());
  841. return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
  842. }
  843. case BinaryOperator::XorAssign: {
  844. const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
  845. LValue LHSLV;
  846. EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
  847. LHS = EmitXor(LHS, RHS, CAO->getComputationType());
  848. return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
  849. }
  850. case BinaryOperator::Comma: return EmitBinaryComma(E);
  851. }
  852. }
  853. RValue CodeGenFunction::EmitMul(RValue LHS, RValue RHS, QualType ResTy) {
  854. if (LHS.isScalar())
  855. return RValue::get(Builder.CreateMul(LHS.getVal(), RHS.getVal(), "mul"));
  856. assert(0 && "FIXME: This doesn't handle complex operands yet");
  857. }
  858. RValue CodeGenFunction::EmitDiv(RValue LHS, RValue RHS, QualType ResTy) {
  859. if (LHS.isScalar()) {
  860. llvm::Value *RV;
  861. if (LHS.getVal()->getType()->isFloatingPoint())
  862. RV = Builder.CreateFDiv(LHS.getVal(), RHS.getVal(), "div");
  863. else if (ResTy->isUnsignedIntegerType())
  864. RV = Builder.CreateUDiv(LHS.getVal(), RHS.getVal(), "div");
  865. else
  866. RV = Builder.CreateSDiv(LHS.getVal(), RHS.getVal(), "div");
  867. return RValue::get(RV);
  868. }
  869. assert(0 && "FIXME: This doesn't handle complex operands yet");
  870. }
  871. RValue CodeGenFunction::EmitRem(RValue LHS, RValue RHS, QualType ResTy) {
  872. if (LHS.isScalar()) {
  873. llvm::Value *RV;
  874. // Rem in C can't be a floating point type: C99 6.5.5p2.
  875. if (ResTy->isUnsignedIntegerType())
  876. RV = Builder.CreateURem(LHS.getVal(), RHS.getVal(), "rem");
  877. else
  878. RV = Builder.CreateSRem(LHS.getVal(), RHS.getVal(), "rem");
  879. return RValue::get(RV);
  880. }
  881. assert(0 && "FIXME: This doesn't handle complex operands yet");
  882. }
  883. RValue CodeGenFunction::EmitAdd(RValue LHS, RValue RHS, QualType ResTy) {
  884. if (LHS.isScalar())
  885. return RValue::get(Builder.CreateAdd(LHS.getVal(), RHS.getVal(), "add"));
  886. // Otherwise, this must be a complex number.
  887. llvm::Value *LHSR, *LHSI, *RHSR, *RHSI;
  888. EmitLoadOfComplex(LHS, LHSR, LHSI);
  889. EmitLoadOfComplex(RHS, RHSR, RHSI);
  890. llvm::Value *ResR = Builder.CreateAdd(LHSR, RHSR, "add.r");
  891. llvm::Value *ResI = Builder.CreateAdd(LHSI, RHSI, "add.i");
  892. llvm::Value *Res = CreateTempAlloca(ConvertType(ResTy));
  893. EmitStoreOfComplex(ResR, ResI, Res);
  894. return RValue::getAggregate(Res);
  895. }
  896. RValue CodeGenFunction::EmitSub(RValue LHS, RValue RHS, QualType ResTy) {
  897. if (LHS.isScalar())
  898. return RValue::get(Builder.CreateSub(LHS.getVal(), RHS.getVal(), "sub"));
  899. assert(0 && "FIXME: This doesn't handle complex operands yet");
  900. }
  901. void CodeGenFunction::EmitShiftOperands(const BinaryOperator *E,
  902. RValue &LHS, RValue &RHS) {
  903. // For shifts, integer promotions are performed, but the usual arithmetic
  904. // conversions are not. The LHS and RHS need not have the same type.
  905. QualType ResTy;
  906. LHS = EmitExprWithUsualUnaryConversions(E->getLHS(), ResTy);
  907. RHS = EmitExprWithUsualUnaryConversions(E->getRHS(), ResTy);
  908. }
  909. RValue CodeGenFunction::EmitShl(RValue LHSV, RValue RHSV, QualType ResTy) {
  910. llvm::Value *LHS = LHSV.getVal(), *RHS = RHSV.getVal();
  911. // LLVM requires the LHS and RHS to be the same type, promote or truncate the
  912. // RHS to the same size as the LHS.
  913. if (LHS->getType() != RHS->getType())
  914. RHS = Builder.CreateIntCast(RHS, LHS->getType(), false, "sh_prom");
  915. return RValue::get(Builder.CreateShl(LHS, RHS, "shl"));
  916. }
  917. RValue CodeGenFunction::EmitShr(RValue LHSV, RValue RHSV, QualType ResTy) {
  918. llvm::Value *LHS = LHSV.getVal(), *RHS = RHSV.getVal();
  919. // LLVM requires the LHS and RHS to be the same type, promote or truncate the
  920. // RHS to the same size as the LHS.
  921. if (LHS->getType() != RHS->getType())
  922. RHS = Builder.CreateIntCast(RHS, LHS->getType(), false, "sh_prom");
  923. if (ResTy->isUnsignedIntegerType())
  924. return RValue::get(Builder.CreateLShr(LHS, RHS, "shr"));
  925. else
  926. return RValue::get(Builder.CreateAShr(LHS, RHS, "shr"));
  927. }
  928. RValue CodeGenFunction::EmitBinaryCompare(const BinaryOperator *E,
  929. unsigned UICmpOpc, unsigned SICmpOpc,
  930. unsigned FCmpOpc) {
  931. RValue LHS, RHS;
  932. EmitUsualArithmeticConversions(E, LHS, RHS);
  933. llvm::Value *Result;
  934. if (LHS.isScalar()) {
  935. if (LHS.getVal()->getType()->isFloatingPoint()) {
  936. Result = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
  937. LHS.getVal(), RHS.getVal(), "cmp");
  938. } else if (E->getLHS()->getType()->isUnsignedIntegerType()) {
  939. // FIXME: This check isn't right for "unsigned short < int" where ushort
  940. // promotes to int and does a signed compare.
  941. Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
  942. LHS.getVal(), RHS.getVal(), "cmp");
  943. } else {
  944. // Signed integers and pointers.
  945. Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
  946. LHS.getVal(), RHS.getVal(), "cmp");
  947. }
  948. } else {
  949. // Struct/union/complex
  950. assert(0 && "Aggregate comparisons not implemented yet!");
  951. }
  952. // ZExt result to int.
  953. return RValue::get(Builder.CreateZExt(Result, LLVMIntTy, "cmp.ext"));
  954. }
  955. RValue CodeGenFunction::EmitAnd(RValue LHS, RValue RHS, QualType ResTy) {
  956. if (LHS.isScalar())
  957. return RValue::get(Builder.CreateAnd(LHS.getVal(), RHS.getVal(), "and"));
  958. assert(0 && "FIXME: This doesn't handle complex integer operands yet (GNU)");
  959. }
  960. RValue CodeGenFunction::EmitXor(RValue LHS, RValue RHS, QualType ResTy) {
  961. if (LHS.isScalar())
  962. return RValue::get(Builder.CreateXor(LHS.getVal(), RHS.getVal(), "xor"));
  963. assert(0 && "FIXME: This doesn't handle complex integer operands yet (GNU)");
  964. }
  965. RValue CodeGenFunction::EmitOr(RValue LHS, RValue RHS, QualType ResTy) {
  966. if (LHS.isScalar())
  967. return RValue::get(Builder.CreateOr(LHS.getVal(), RHS.getVal(), "or"));
  968. assert(0 && "FIXME: This doesn't handle complex integer operands yet (GNU)");
  969. }
  970. RValue CodeGenFunction::EmitBinaryLAnd(const BinaryOperator *E) {
  971. llvm::Value *LHSCond = EvaluateExprAsBool(E->getLHS());
  972. llvm::BasicBlock *ContBlock = new llvm::BasicBlock("land_cont");
  973. llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("land_rhs");
  974. llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
  975. Builder.CreateCondBr(LHSCond, RHSBlock, ContBlock);
  976. EmitBlock(RHSBlock);
  977. llvm::Value *RHSCond = EvaluateExprAsBool(E->getRHS());
  978. // Reaquire the RHS block, as there may be subblocks inserted.
  979. RHSBlock = Builder.GetInsertBlock();
  980. EmitBlock(ContBlock);
  981. // Create a PHI node. If we just evaluted the LHS condition, the result is
  982. // false. If we evaluated both, the result is the RHS condition.
  983. llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "land");
  984. PN->reserveOperandSpace(2);
  985. PN->addIncoming(llvm::ConstantInt::getFalse(), OrigBlock);
  986. PN->addIncoming(RHSCond, RHSBlock);
  987. // ZExt result to int.
  988. return RValue::get(Builder.CreateZExt(PN, LLVMIntTy, "land.ext"));
  989. }
  990. RValue CodeGenFunction::EmitBinaryLOr(const BinaryOperator *E) {
  991. llvm::Value *LHSCond = EvaluateExprAsBool(E->getLHS());
  992. llvm::BasicBlock *ContBlock = new llvm::BasicBlock("lor_cont");
  993. llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("lor_rhs");
  994. llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
  995. Builder.CreateCondBr(LHSCond, ContBlock, RHSBlock);
  996. EmitBlock(RHSBlock);
  997. llvm::Value *RHSCond = EvaluateExprAsBool(E->getRHS());
  998. // Reaquire the RHS block, as there may be subblocks inserted.
  999. RHSBlock = Builder.GetInsertBlock();
  1000. EmitBlock(ContBlock);
  1001. // Create a PHI node. If we just evaluted the LHS condition, the result is
  1002. // true. If we evaluated both, the result is the RHS condition.
  1003. llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "lor");
  1004. PN->reserveOperandSpace(2);
  1005. PN->addIncoming(llvm::ConstantInt::getTrue(), OrigBlock);
  1006. PN->addIncoming(RHSCond, RHSBlock);
  1007. // ZExt result to int.
  1008. return RValue::get(Builder.CreateZExt(PN, LLVMIntTy, "lor.ext"));
  1009. }
  1010. RValue CodeGenFunction::EmitBinaryAssign(const BinaryOperator *E) {
  1011. LValue LHS = EmitLValue(E->getLHS());
  1012. QualType RHSTy;
  1013. RValue RHS = EmitExprWithUsualUnaryConversions(E->getRHS(), RHSTy);
  1014. // Convert the RHS to the type of the LHS.
  1015. RHS = EmitConversion(RHS, RHSTy, E->getType());
  1016. // Store the value into the LHS.
  1017. EmitStoreThroughLValue(RHS, LHS, E->getType());
  1018. // Return the converted RHS.
  1019. return RHS;
  1020. }
  1021. RValue CodeGenFunction::EmitBinaryComma(const BinaryOperator *E) {
  1022. EmitExpr(E->getLHS());
  1023. return EmitExpr(E->getRHS());
  1024. }