CodeGenFunction.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875
  1. //===--- CodeGenFunction.cpp - Emit LLVM Code from ASTs for a Function ----===//
  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 coordinates the per-function state used while generating code.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "CodeGenFunction.h"
  14. #include "CodeGenModule.h"
  15. #include "CGCXXABI.h"
  16. #include "CGDebugInfo.h"
  17. #include "CGException.h"
  18. #include "clang/Basic/TargetInfo.h"
  19. #include "clang/AST/APValue.h"
  20. #include "clang/AST/ASTContext.h"
  21. #include "clang/AST/Decl.h"
  22. #include "clang/AST/DeclCXX.h"
  23. #include "clang/AST/StmtCXX.h"
  24. #include "clang/Frontend/CodeGenOptions.h"
  25. #include "llvm/Target/TargetData.h"
  26. #include "llvm/Intrinsics.h"
  27. using namespace clang;
  28. using namespace CodeGen;
  29. CodeGenFunction::CodeGenFunction(CodeGenModule &cgm)
  30. : CodeGenTypeCache(cgm), CGM(cgm),
  31. Target(CGM.getContext().Target), Builder(cgm.getModule().getContext()),
  32. AutoreleaseResult(false), BlockInfo(0), BlockPointer(0),
  33. NormalCleanupDest(0), EHCleanupDest(0), NextCleanupDestIndex(1),
  34. ExceptionSlot(0), EHSelectorSlot(0),
  35. DebugInfo(0), DisableDebugInfo(false), DidCallStackSave(false),
  36. IndirectBranch(0), SwitchInsn(0), CaseRangeBlock(0), UnreachableBlock(0),
  37. CXXThisDecl(0), CXXThisValue(0), CXXVTTDecl(0), CXXVTTValue(0),
  38. OutermostConditional(0), TerminateLandingPad(0), TerminateHandler(0),
  39. TrapBB(0) {
  40. CatchUndefined = getContext().getLangOptions().CatchUndefined;
  41. CGM.getCXXABI().getMangleContext().startNewFunction();
  42. }
  43. const llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
  44. return CGM.getTypes().ConvertTypeForMem(T);
  45. }
  46. const llvm::Type *CodeGenFunction::ConvertType(QualType T) {
  47. return CGM.getTypes().ConvertType(T);
  48. }
  49. bool CodeGenFunction::hasAggregateLLVMType(QualType type) {
  50. switch (type.getCanonicalType()->getTypeClass()) {
  51. #define TYPE(name, parent)
  52. #define ABSTRACT_TYPE(name, parent)
  53. #define NON_CANONICAL_TYPE(name, parent) case Type::name:
  54. #define DEPENDENT_TYPE(name, parent) case Type::name:
  55. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(name, parent) case Type::name:
  56. #include "clang/AST/TypeNodes.def"
  57. llvm_unreachable("non-canonical or dependent type in IR-generation");
  58. case Type::Builtin:
  59. case Type::Pointer:
  60. case Type::BlockPointer:
  61. case Type::LValueReference:
  62. case Type::RValueReference:
  63. case Type::MemberPointer:
  64. case Type::Vector:
  65. case Type::ExtVector:
  66. case Type::FunctionProto:
  67. case Type::FunctionNoProto:
  68. case Type::Enum:
  69. case Type::ObjCObjectPointer:
  70. return false;
  71. // Complexes, arrays, records, and Objective-C objects.
  72. case Type::Complex:
  73. case Type::ConstantArray:
  74. case Type::IncompleteArray:
  75. case Type::VariableArray:
  76. case Type::Record:
  77. case Type::ObjCObject:
  78. case Type::ObjCInterface:
  79. return true;
  80. }
  81. llvm_unreachable("unknown type kind!");
  82. }
  83. void CodeGenFunction::EmitReturnBlock() {
  84. // For cleanliness, we try to avoid emitting the return block for
  85. // simple cases.
  86. llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
  87. if (CurBB) {
  88. assert(!CurBB->getTerminator() && "Unexpected terminated block.");
  89. // We have a valid insert point, reuse it if it is empty or there are no
  90. // explicit jumps to the return block.
  91. if (CurBB->empty() || ReturnBlock.getBlock()->use_empty()) {
  92. ReturnBlock.getBlock()->replaceAllUsesWith(CurBB);
  93. delete ReturnBlock.getBlock();
  94. } else
  95. EmitBlock(ReturnBlock.getBlock());
  96. return;
  97. }
  98. // Otherwise, if the return block is the target of a single direct
  99. // branch then we can just put the code in that block instead. This
  100. // cleans up functions which started with a unified return block.
  101. if (ReturnBlock.getBlock()->hasOneUse()) {
  102. llvm::BranchInst *BI =
  103. dyn_cast<llvm::BranchInst>(*ReturnBlock.getBlock()->use_begin());
  104. if (BI && BI->isUnconditional() &&
  105. BI->getSuccessor(0) == ReturnBlock.getBlock()) {
  106. // Reset insertion point and delete the branch.
  107. Builder.SetInsertPoint(BI->getParent());
  108. BI->eraseFromParent();
  109. delete ReturnBlock.getBlock();
  110. return;
  111. }
  112. }
  113. // FIXME: We are at an unreachable point, there is no reason to emit the block
  114. // unless it has uses. However, we still need a place to put the debug
  115. // region.end for now.
  116. EmitBlock(ReturnBlock.getBlock());
  117. }
  118. static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB) {
  119. if (!BB) return;
  120. if (!BB->use_empty())
  121. return CGF.CurFn->getBasicBlockList().push_back(BB);
  122. delete BB;
  123. }
  124. void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
  125. assert(BreakContinueStack.empty() &&
  126. "mismatched push/pop in break/continue stack!");
  127. // Pop any cleanups that might have been associated with the
  128. // parameters. Do this in whatever block we're currently in; it's
  129. // important to do this before we enter the return block or return
  130. // edges will be *really* confused.
  131. if (EHStack.stable_begin() != PrologueCleanupDepth)
  132. PopCleanupBlocks(PrologueCleanupDepth);
  133. // Emit function epilog (to return).
  134. EmitReturnBlock();
  135. if (ShouldInstrumentFunction())
  136. EmitFunctionInstrumentation("__cyg_profile_func_exit");
  137. // Emit debug descriptor for function end.
  138. if (CGDebugInfo *DI = getDebugInfo()) {
  139. DI->setLocation(EndLoc);
  140. DI->EmitFunctionEnd(Builder);
  141. }
  142. EmitFunctionEpilog(*CurFnInfo);
  143. EmitEndEHSpec(CurCodeDecl);
  144. assert(EHStack.empty() &&
  145. "did not remove all scopes from cleanup stack!");
  146. // If someone did an indirect goto, emit the indirect goto block at the end of
  147. // the function.
  148. if (IndirectBranch) {
  149. EmitBlock(IndirectBranch->getParent());
  150. Builder.ClearInsertionPoint();
  151. }
  152. // Remove the AllocaInsertPt instruction, which is just a convenience for us.
  153. llvm::Instruction *Ptr = AllocaInsertPt;
  154. AllocaInsertPt = 0;
  155. Ptr->eraseFromParent();
  156. // If someone took the address of a label but never did an indirect goto, we
  157. // made a zero entry PHI node, which is illegal, zap it now.
  158. if (IndirectBranch) {
  159. llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
  160. if (PN->getNumIncomingValues() == 0) {
  161. PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
  162. PN->eraseFromParent();
  163. }
  164. }
  165. EmitIfUsed(*this, RethrowBlock.getBlock());
  166. EmitIfUsed(*this, TerminateLandingPad);
  167. EmitIfUsed(*this, TerminateHandler);
  168. EmitIfUsed(*this, UnreachableBlock);
  169. if (CGM.getCodeGenOpts().EmitDeclMetadata)
  170. EmitDeclMetadata();
  171. }
  172. /// ShouldInstrumentFunction - Return true if the current function should be
  173. /// instrumented with __cyg_profile_func_* calls
  174. bool CodeGenFunction::ShouldInstrumentFunction() {
  175. if (!CGM.getCodeGenOpts().InstrumentFunctions)
  176. return false;
  177. if (!CurFuncDecl || CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>())
  178. return false;
  179. return true;
  180. }
  181. /// EmitFunctionInstrumentation - Emit LLVM code to call the specified
  182. /// instrumentation function with the current function and the call site, if
  183. /// function instrumentation is enabled.
  184. void CodeGenFunction::EmitFunctionInstrumentation(const char *Fn) {
  185. // void __cyg_profile_func_{enter,exit} (void *this_fn, void *call_site);
  186. const llvm::PointerType *PointerTy = Int8PtrTy;
  187. const llvm::Type *ProfileFuncArgs[] = { PointerTy, PointerTy };
  188. const llvm::FunctionType *FunctionTy =
  189. llvm::FunctionType::get(llvm::Type::getVoidTy(getLLVMContext()),
  190. ProfileFuncArgs, false);
  191. llvm::Constant *F = CGM.CreateRuntimeFunction(FunctionTy, Fn);
  192. llvm::CallInst *CallSite = Builder.CreateCall(
  193. CGM.getIntrinsic(llvm::Intrinsic::returnaddress, 0, 0),
  194. llvm::ConstantInt::get(Int32Ty, 0),
  195. "callsite");
  196. Builder.CreateCall2(F,
  197. llvm::ConstantExpr::getBitCast(CurFn, PointerTy),
  198. CallSite);
  199. }
  200. void CodeGenFunction::EmitMCountInstrumentation() {
  201. llvm::FunctionType *FTy =
  202. llvm::FunctionType::get(llvm::Type::getVoidTy(getLLVMContext()), false);
  203. llvm::Constant *MCountFn = CGM.CreateRuntimeFunction(FTy,
  204. Target.getMCountName());
  205. Builder.CreateCall(MCountFn);
  206. }
  207. void CodeGenFunction::StartFunction(GlobalDecl GD, QualType RetTy,
  208. llvm::Function *Fn,
  209. const CGFunctionInfo &FnInfo,
  210. const FunctionArgList &Args,
  211. SourceLocation StartLoc) {
  212. const Decl *D = GD.getDecl();
  213. DidCallStackSave = false;
  214. CurCodeDecl = CurFuncDecl = D;
  215. FnRetTy = RetTy;
  216. CurFn = Fn;
  217. CurFnInfo = &FnInfo;
  218. assert(CurFn->isDeclaration() && "Function already has body?");
  219. // Pass inline keyword to optimizer if it appears explicitly on any
  220. // declaration.
  221. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
  222. for (FunctionDecl::redecl_iterator RI = FD->redecls_begin(),
  223. RE = FD->redecls_end(); RI != RE; ++RI)
  224. if (RI->isInlineSpecified()) {
  225. Fn->addFnAttr(llvm::Attribute::InlineHint);
  226. break;
  227. }
  228. if (getContext().getLangOptions().OpenCL) {
  229. // Add metadata for a kernel function.
  230. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
  231. if (FD->hasAttr<OpenCLKernelAttr>()) {
  232. llvm::LLVMContext &Context = getLLVMContext();
  233. llvm::NamedMDNode *OpenCLMetadata =
  234. CGM.getModule().getOrInsertNamedMetadata("opencl.kernels");
  235. llvm::Value *Op = Fn;
  236. OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Op));
  237. }
  238. }
  239. llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
  240. // Create a marker to make it easy to insert allocas into the entryblock
  241. // later. Don't create this with the builder, because we don't want it
  242. // folded.
  243. llvm::Value *Undef = llvm::UndefValue::get(Int32Ty);
  244. AllocaInsertPt = new llvm::BitCastInst(Undef, Int32Ty, "", EntryBB);
  245. if (Builder.isNamePreserving())
  246. AllocaInsertPt->setName("allocapt");
  247. ReturnBlock = getJumpDestInCurrentScope("return");
  248. Builder.SetInsertPoint(EntryBB);
  249. // Emit subprogram debug descriptor.
  250. if (CGDebugInfo *DI = getDebugInfo()) {
  251. // FIXME: what is going on here and why does it ignore all these
  252. // interesting type properties?
  253. QualType FnType =
  254. getContext().getFunctionType(RetTy, 0, 0,
  255. FunctionProtoType::ExtProtoInfo());
  256. DI->setLocation(StartLoc);
  257. DI->EmitFunctionStart(GD, FnType, CurFn, Builder);
  258. }
  259. if (ShouldInstrumentFunction())
  260. EmitFunctionInstrumentation("__cyg_profile_func_enter");
  261. if (CGM.getCodeGenOpts().InstrumentForProfiling)
  262. EmitMCountInstrumentation();
  263. if (RetTy->isVoidType()) {
  264. // Void type; nothing to return.
  265. ReturnValue = 0;
  266. } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
  267. hasAggregateLLVMType(CurFnInfo->getReturnType())) {
  268. // Indirect aggregate return; emit returned value directly into sret slot.
  269. // This reduces code size, and affects correctness in C++.
  270. ReturnValue = CurFn->arg_begin();
  271. } else {
  272. ReturnValue = CreateIRTemp(RetTy, "retval");
  273. // Tell the epilog emitter to autorelease the result. We do this
  274. // now so that various specialized functions can suppress it
  275. // during their IR-generation.
  276. if (getLangOptions().ObjCAutoRefCount &&
  277. !CurFnInfo->isReturnsRetained() &&
  278. RetTy->isObjCRetainableType())
  279. AutoreleaseResult = true;
  280. }
  281. EmitStartEHSpec(CurCodeDecl);
  282. PrologueCleanupDepth = EHStack.stable_begin();
  283. EmitFunctionProlog(*CurFnInfo, CurFn, Args);
  284. if (D && isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance())
  285. CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
  286. // If any of the arguments have a variably modified type, make sure to
  287. // emit the type size.
  288. for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
  289. i != e; ++i) {
  290. QualType Ty = (*i)->getType();
  291. if (Ty->isVariablyModifiedType())
  292. EmitVLASize(Ty);
  293. }
  294. }
  295. void CodeGenFunction::EmitFunctionBody(FunctionArgList &Args) {
  296. const FunctionDecl *FD = cast<FunctionDecl>(CurGD.getDecl());
  297. assert(FD->getBody());
  298. EmitStmt(FD->getBody());
  299. }
  300. /// Tries to mark the given function nounwind based on the
  301. /// non-existence of any throwing calls within it. We believe this is
  302. /// lightweight enough to do at -O0.
  303. static void TryMarkNoThrow(llvm::Function *F) {
  304. // LLVM treats 'nounwind' on a function as part of the type, so we
  305. // can't do this on functions that can be overwritten.
  306. if (F->mayBeOverridden()) return;
  307. for (llvm::Function::iterator FI = F->begin(), FE = F->end(); FI != FE; ++FI)
  308. for (llvm::BasicBlock::iterator
  309. BI = FI->begin(), BE = FI->end(); BI != BE; ++BI)
  310. if (llvm::CallInst *Call = dyn_cast<llvm::CallInst>(&*BI))
  311. if (!Call->doesNotThrow())
  312. return;
  313. F->setDoesNotThrow(true);
  314. }
  315. void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn,
  316. const CGFunctionInfo &FnInfo) {
  317. const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
  318. // Check if we should generate debug info for this function.
  319. if (CGM.getModuleDebugInfo() && !FD->hasAttr<NoDebugAttr>())
  320. DebugInfo = CGM.getModuleDebugInfo();
  321. FunctionArgList Args;
  322. QualType ResTy = FD->getResultType();
  323. CurGD = GD;
  324. if (isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isInstance())
  325. CGM.getCXXABI().BuildInstanceFunctionParams(*this, ResTy, Args);
  326. if (FD->getNumParams())
  327. for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i)
  328. Args.push_back(FD->getParamDecl(i));
  329. SourceRange BodyRange;
  330. if (Stmt *Body = FD->getBody()) BodyRange = Body->getSourceRange();
  331. // Emit the standard function prologue.
  332. StartFunction(GD, ResTy, Fn, FnInfo, Args, BodyRange.getBegin());
  333. // Generate the body of the function.
  334. if (isa<CXXDestructorDecl>(FD))
  335. EmitDestructorBody(Args);
  336. else if (isa<CXXConstructorDecl>(FD))
  337. EmitConstructorBody(Args);
  338. else
  339. EmitFunctionBody(Args);
  340. // Emit the standard function epilogue.
  341. FinishFunction(BodyRange.getEnd());
  342. // If we haven't marked the function nothrow through other means, do
  343. // a quick pass now to see if we can.
  344. if (!CurFn->doesNotThrow())
  345. TryMarkNoThrow(CurFn);
  346. }
  347. /// ContainsLabel - Return true if the statement contains a label in it. If
  348. /// this statement is not executed normally, it not containing a label means
  349. /// that we can just remove the code.
  350. bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
  351. // Null statement, not a label!
  352. if (S == 0) return false;
  353. // If this is a label, we have to emit the code, consider something like:
  354. // if (0) { ... foo: bar(); } goto foo;
  355. //
  356. // TODO: If anyone cared, we could track __label__'s, since we know that you
  357. // can't jump to one from outside their declared region.
  358. if (isa<LabelStmt>(S))
  359. return true;
  360. // If this is a case/default statement, and we haven't seen a switch, we have
  361. // to emit the code.
  362. if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
  363. return true;
  364. // If this is a switch statement, we want to ignore cases below it.
  365. if (isa<SwitchStmt>(S))
  366. IgnoreCaseStmts = true;
  367. // Scan subexpressions for verboten labels.
  368. for (Stmt::const_child_range I = S->children(); I; ++I)
  369. if (ContainsLabel(*I, IgnoreCaseStmts))
  370. return true;
  371. return false;
  372. }
  373. /// containsBreak - Return true if the statement contains a break out of it.
  374. /// If the statement (recursively) contains a switch or loop with a break
  375. /// inside of it, this is fine.
  376. bool CodeGenFunction::containsBreak(const Stmt *S) {
  377. // Null statement, not a label!
  378. if (S == 0) return false;
  379. // If this is a switch or loop that defines its own break scope, then we can
  380. // include it and anything inside of it.
  381. if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S) ||
  382. isa<ForStmt>(S))
  383. return false;
  384. if (isa<BreakStmt>(S))
  385. return true;
  386. // Scan subexpressions for verboten breaks.
  387. for (Stmt::const_child_range I = S->children(); I; ++I)
  388. if (containsBreak(*I))
  389. return true;
  390. return false;
  391. }
  392. /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
  393. /// to a constant, or if it does but contains a label, return false. If it
  394. /// constant folds return true and set the boolean result in Result.
  395. bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
  396. bool &ResultBool) {
  397. llvm::APInt ResultInt;
  398. if (!ConstantFoldsToSimpleInteger(Cond, ResultInt))
  399. return false;
  400. ResultBool = ResultInt.getBoolValue();
  401. return true;
  402. }
  403. /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
  404. /// to a constant, or if it does but contains a label, return false. If it
  405. /// constant folds return true and set the folded value.
  406. bool CodeGenFunction::
  407. ConstantFoldsToSimpleInteger(const Expr *Cond, llvm::APInt &ResultInt) {
  408. // FIXME: Rename and handle conversion of other evaluatable things
  409. // to bool.
  410. Expr::EvalResult Result;
  411. if (!Cond->Evaluate(Result, getContext()) || !Result.Val.isInt() ||
  412. Result.HasSideEffects)
  413. return false; // Not foldable, not integer or not fully evaluatable.
  414. if (CodeGenFunction::ContainsLabel(Cond))
  415. return false; // Contains a label.
  416. ResultInt = Result.Val.getInt();
  417. return true;
  418. }
  419. /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
  420. /// statement) to the specified blocks. Based on the condition, this might try
  421. /// to simplify the codegen of the conditional based on the branch.
  422. ///
  423. void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
  424. llvm::BasicBlock *TrueBlock,
  425. llvm::BasicBlock *FalseBlock) {
  426. Cond = Cond->IgnoreParens();
  427. if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
  428. // Handle X && Y in a condition.
  429. if (CondBOp->getOpcode() == BO_LAnd) {
  430. // If we have "1 && X", simplify the code. "0 && X" would have constant
  431. // folded if the case was simple enough.
  432. bool ConstantBool = false;
  433. if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
  434. ConstantBool) {
  435. // br(1 && X) -> br(X).
  436. return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
  437. }
  438. // If we have "X && 1", simplify the code to use an uncond branch.
  439. // "X && 0" would have been constant folded to 0.
  440. if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
  441. ConstantBool) {
  442. // br(X && 1) -> br(X).
  443. return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
  444. }
  445. // Emit the LHS as a conditional. If the LHS conditional is false, we
  446. // want to jump to the FalseBlock.
  447. llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
  448. ConditionalEvaluation eval(*this);
  449. EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock);
  450. EmitBlock(LHSTrue);
  451. // Any temporaries created here are conditional.
  452. eval.begin(*this);
  453. EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
  454. eval.end(*this);
  455. return;
  456. }
  457. if (CondBOp->getOpcode() == BO_LOr) {
  458. // If we have "0 || X", simplify the code. "1 || X" would have constant
  459. // folded if the case was simple enough.
  460. bool ConstantBool = false;
  461. if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
  462. !ConstantBool) {
  463. // br(0 || X) -> br(X).
  464. return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
  465. }
  466. // If we have "X || 0", simplify the code to use an uncond branch.
  467. // "X || 1" would have been constant folded to 1.
  468. if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
  469. !ConstantBool) {
  470. // br(X || 0) -> br(X).
  471. return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
  472. }
  473. // Emit the LHS as a conditional. If the LHS conditional is true, we
  474. // want to jump to the TrueBlock.
  475. llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
  476. ConditionalEvaluation eval(*this);
  477. EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse);
  478. EmitBlock(LHSFalse);
  479. // Any temporaries created here are conditional.
  480. eval.begin(*this);
  481. EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
  482. eval.end(*this);
  483. return;
  484. }
  485. }
  486. if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
  487. // br(!x, t, f) -> br(x, f, t)
  488. if (CondUOp->getOpcode() == UO_LNot)
  489. return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock);
  490. }
  491. if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
  492. // Handle ?: operator.
  493. // Just ignore GNU ?: extension.
  494. if (CondOp->getLHS()) {
  495. // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
  496. llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
  497. llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
  498. ConditionalEvaluation cond(*this);
  499. EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock);
  500. cond.begin(*this);
  501. EmitBlock(LHSBlock);
  502. EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock);
  503. cond.end(*this);
  504. cond.begin(*this);
  505. EmitBlock(RHSBlock);
  506. EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock);
  507. cond.end(*this);
  508. return;
  509. }
  510. }
  511. // Emit the code with the fully general case.
  512. llvm::Value *CondV = EvaluateExprAsBool(Cond);
  513. Builder.CreateCondBr(CondV, TrueBlock, FalseBlock);
  514. }
  515. /// ErrorUnsupported - Print out an error that codegen doesn't support the
  516. /// specified stmt yet.
  517. void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type,
  518. bool OmitOnError) {
  519. CGM.ErrorUnsupported(S, Type, OmitOnError);
  520. }
  521. /// emitNonZeroVLAInit - Emit the "zero" initialization of a
  522. /// variable-length array whose elements have a non-zero bit-pattern.
  523. ///
  524. /// \param src - a char* pointing to the bit-pattern for a single
  525. /// base element of the array
  526. /// \param sizeInChars - the total size of the VLA, in chars
  527. /// \param align - the total alignment of the VLA
  528. static void emitNonZeroVLAInit(CodeGenFunction &CGF, QualType baseType,
  529. llvm::Value *dest, llvm::Value *src,
  530. llvm::Value *sizeInChars) {
  531. std::pair<CharUnits,CharUnits> baseSizeAndAlign
  532. = CGF.getContext().getTypeInfoInChars(baseType);
  533. CGBuilderTy &Builder = CGF.Builder;
  534. llvm::Value *baseSizeInChars
  535. = llvm::ConstantInt::get(CGF.IntPtrTy, baseSizeAndAlign.first.getQuantity());
  536. const llvm::Type *i8p = Builder.getInt8PtrTy();
  537. llvm::Value *begin = Builder.CreateBitCast(dest, i8p, "vla.begin");
  538. llvm::Value *end = Builder.CreateInBoundsGEP(dest, sizeInChars, "vla.end");
  539. llvm::BasicBlock *originBB = CGF.Builder.GetInsertBlock();
  540. llvm::BasicBlock *loopBB = CGF.createBasicBlock("vla-init.loop");
  541. llvm::BasicBlock *contBB = CGF.createBasicBlock("vla-init.cont");
  542. // Make a loop over the VLA. C99 guarantees that the VLA element
  543. // count must be nonzero.
  544. CGF.EmitBlock(loopBB);
  545. llvm::PHINode *cur = Builder.CreatePHI(i8p, 2, "vla.cur");
  546. cur->addIncoming(begin, originBB);
  547. // memcpy the individual element bit-pattern.
  548. Builder.CreateMemCpy(cur, src, baseSizeInChars,
  549. baseSizeAndAlign.second.getQuantity(),
  550. /*volatile*/ false);
  551. // Go to the next element.
  552. llvm::Value *next = Builder.CreateConstInBoundsGEP1_32(cur, 1, "vla.next");
  553. // Leave if that's the end of the VLA.
  554. llvm::Value *done = Builder.CreateICmpEQ(next, end, "vla-init.isdone");
  555. Builder.CreateCondBr(done, contBB, loopBB);
  556. cur->addIncoming(next, loopBB);
  557. CGF.EmitBlock(contBB);
  558. }
  559. void
  560. CodeGenFunction::EmitNullInitialization(llvm::Value *DestPtr, QualType Ty) {
  561. // Ignore empty classes in C++.
  562. if (getContext().getLangOptions().CPlusPlus) {
  563. if (const RecordType *RT = Ty->getAs<RecordType>()) {
  564. if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty())
  565. return;
  566. }
  567. }
  568. // Cast the dest ptr to the appropriate i8 pointer type.
  569. unsigned DestAS =
  570. cast<llvm::PointerType>(DestPtr->getType())->getAddressSpace();
  571. const llvm::Type *BP = Builder.getInt8PtrTy(DestAS);
  572. if (DestPtr->getType() != BP)
  573. DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
  574. // Get size and alignment info for this aggregate.
  575. std::pair<CharUnits, CharUnits> TypeInfo =
  576. getContext().getTypeInfoInChars(Ty);
  577. CharUnits Size = TypeInfo.first;
  578. CharUnits Align = TypeInfo.second;
  579. llvm::Value *SizeVal;
  580. const VariableArrayType *vla;
  581. // Don't bother emitting a zero-byte memset.
  582. if (Size.isZero()) {
  583. // But note that getTypeInfo returns 0 for a VLA.
  584. if (const VariableArrayType *vlaType =
  585. dyn_cast_or_null<VariableArrayType>(
  586. getContext().getAsArrayType(Ty))) {
  587. SizeVal = GetVLASize(vlaType);
  588. vla = vlaType;
  589. } else {
  590. return;
  591. }
  592. } else {
  593. SizeVal = llvm::ConstantInt::get(IntPtrTy, Size.getQuantity());
  594. vla = 0;
  595. }
  596. // If the type contains a pointer to data member we can't memset it to zero.
  597. // Instead, create a null constant and copy it to the destination.
  598. // TODO: there are other patterns besides zero that we can usefully memset,
  599. // like -1, which happens to be the pattern used by member-pointers.
  600. if (!CGM.getTypes().isZeroInitializable(Ty)) {
  601. // For a VLA, emit a single element, then splat that over the VLA.
  602. if (vla) Ty = getContext().getBaseElementType(vla);
  603. llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty);
  604. llvm::GlobalVariable *NullVariable =
  605. new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(),
  606. /*isConstant=*/true,
  607. llvm::GlobalVariable::PrivateLinkage,
  608. NullConstant, llvm::Twine());
  609. llvm::Value *SrcPtr =
  610. Builder.CreateBitCast(NullVariable, Builder.getInt8PtrTy());
  611. if (vla) return emitNonZeroVLAInit(*this, Ty, DestPtr, SrcPtr, SizeVal);
  612. // Get and call the appropriate llvm.memcpy overload.
  613. Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, Align.getQuantity(), false);
  614. return;
  615. }
  616. // Otherwise, just memset the whole thing to zero. This is legal
  617. // because in LLVM, all default initializers (other than the ones we just
  618. // handled above) are guaranteed to have a bit pattern of all zeros.
  619. Builder.CreateMemSet(DestPtr, Builder.getInt8(0), SizeVal,
  620. Align.getQuantity(), false);
  621. }
  622. llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelDecl *L) {
  623. // Make sure that there is a block for the indirect goto.
  624. if (IndirectBranch == 0)
  625. GetIndirectGotoBlock();
  626. llvm::BasicBlock *BB = getJumpDestForLabel(L).getBlock();
  627. // Make sure the indirect branch includes all of the address-taken blocks.
  628. IndirectBranch->addDestination(BB);
  629. return llvm::BlockAddress::get(CurFn, BB);
  630. }
  631. llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
  632. // If we already made the indirect branch for indirect goto, return its block.
  633. if (IndirectBranch) return IndirectBranch->getParent();
  634. CGBuilderTy TmpBuilder(createBasicBlock("indirectgoto"));
  635. // Create the PHI node that indirect gotos will add entries to.
  636. llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, 0,
  637. "indirect.goto.dest");
  638. // Create the indirect branch instruction.
  639. IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
  640. return IndirectBranch->getParent();
  641. }
  642. llvm::Value *CodeGenFunction::GetVLASize(const VariableArrayType *VAT) {
  643. llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
  644. assert(SizeEntry && "Did not emit size for type");
  645. return SizeEntry;
  646. }
  647. llvm::Value *CodeGenFunction::EmitVLASize(QualType Ty) {
  648. assert(Ty->isVariablyModifiedType() &&
  649. "Must pass variably modified type to EmitVLASizes!");
  650. EnsureInsertPoint();
  651. if (const VariableArrayType *VAT = getContext().getAsVariableArrayType(Ty)) {
  652. // unknown size indication requires no size computation.
  653. if (!VAT->getSizeExpr())
  654. return 0;
  655. llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
  656. if (!SizeEntry) {
  657. const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
  658. // Get the element size;
  659. QualType ElemTy = VAT->getElementType();
  660. llvm::Value *ElemSize;
  661. if (ElemTy->isVariableArrayType())
  662. ElemSize = EmitVLASize(ElemTy);
  663. else
  664. ElemSize = llvm::ConstantInt::get(SizeTy,
  665. getContext().getTypeSizeInChars(ElemTy).getQuantity());
  666. llvm::Value *NumElements = EmitScalarExpr(VAT->getSizeExpr());
  667. NumElements = Builder.CreateIntCast(NumElements, SizeTy, false, "tmp");
  668. SizeEntry = Builder.CreateMul(ElemSize, NumElements);
  669. }
  670. return SizeEntry;
  671. }
  672. if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
  673. EmitVLASize(AT->getElementType());
  674. return 0;
  675. }
  676. if (const ParenType *PT = dyn_cast<ParenType>(Ty)) {
  677. EmitVLASize(PT->getInnerType());
  678. return 0;
  679. }
  680. const PointerType *PT = Ty->getAs<PointerType>();
  681. assert(PT && "unknown VM type!");
  682. EmitVLASize(PT->getPointeeType());
  683. return 0;
  684. }
  685. llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) {
  686. if (getContext().getBuiltinVaListType()->isArrayType())
  687. return EmitScalarExpr(E);
  688. return EmitLValue(E).getAddress();
  689. }
  690. void CodeGenFunction::EmitDeclRefExprDbgValue(const DeclRefExpr *E,
  691. llvm::Constant *Init) {
  692. assert (Init && "Invalid DeclRefExpr initializer!");
  693. if (CGDebugInfo *Dbg = getDebugInfo())
  694. Dbg->EmitGlobalVariable(E->getDecl(), Init);
  695. }
  696. CodeGenFunction::PeepholeProtection
  697. CodeGenFunction::protectFromPeepholes(RValue rvalue) {
  698. // At the moment, the only aggressive peephole we do in IR gen
  699. // is trunc(zext) folding, but if we add more, we can easily
  700. // extend this protection.
  701. if (!rvalue.isScalar()) return PeepholeProtection();
  702. llvm::Value *value = rvalue.getScalarVal();
  703. if (!isa<llvm::ZExtInst>(value)) return PeepholeProtection();
  704. // Just make an extra bitcast.
  705. assert(HaveInsertPoint());
  706. llvm::Instruction *inst = new llvm::BitCastInst(value, value->getType(), "",
  707. Builder.GetInsertBlock());
  708. PeepholeProtection protection;
  709. protection.Inst = inst;
  710. return protection;
  711. }
  712. void CodeGenFunction::unprotectFromPeepholes(PeepholeProtection protection) {
  713. if (!protection.Inst) return;
  714. // In theory, we could try to duplicate the peepholes now, but whatever.
  715. protection.Inst->eraseFromParent();
  716. }