clang API Documentation

CodeGenFunction.cpp
Go to the documentation of this file.
00001 //===--- CodeGenFunction.cpp - Emit LLVM Code from ASTs for a Function ----===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This coordinates the per-function state used while generating code.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "CodeGenFunction.h"
00015 #include "CodeGenModule.h"
00016 #include "CGCUDARuntime.h"
00017 #include "CGCXXABI.h"
00018 #include "CGDebugInfo.h"
00019 #include "clang/Basic/TargetInfo.h"
00020 #include "clang/AST/ASTContext.h"
00021 #include "clang/AST/Decl.h"
00022 #include "clang/AST/DeclCXX.h"
00023 #include "clang/AST/StmtCXX.h"
00024 #include "clang/Frontend/CodeGenOptions.h"
00025 #include "llvm/Intrinsics.h"
00026 #include "llvm/Support/MDBuilder.h"
00027 #include "llvm/Target/TargetData.h"
00028 using namespace clang;
00029 using namespace CodeGen;
00030 
00031 CodeGenFunction::CodeGenFunction(CodeGenModule &cgm)
00032   : CodeGenTypeCache(cgm), CGM(cgm),
00033     Target(CGM.getContext().getTargetInfo()),
00034     Builder(cgm.getModule().getContext()),
00035     AutoreleaseResult(false), BlockInfo(0), BlockPointer(0),
00036     LambdaThisCaptureField(0), NormalCleanupDest(0), NextCleanupDestIndex(1),
00037     FirstBlockInfo(0), EHResumeBlock(0), ExceptionSlot(0), EHSelectorSlot(0),
00038     DebugInfo(0), DisableDebugInfo(false), DidCallStackSave(false),
00039     IndirectBranch(0), SwitchInsn(0), CaseRangeBlock(0), UnreachableBlock(0),
00040     CXXABIThisDecl(0), CXXABIThisValue(0), CXXThisValue(0), CXXVTTDecl(0),
00041     CXXVTTValue(0), OutermostConditional(0), TerminateLandingPad(0),
00042     TerminateHandler(0), TrapBB(0) {
00043 
00044   BoundsChecking = getContext().getLangOpts().BoundsChecking;
00045   CatchUndefined = getContext().getLangOpts().CatchUndefined;
00046   CGM.getCXXABI().getMangleContext().startNewFunction();
00047 }
00048 
00049 CodeGenFunction::~CodeGenFunction() {
00050   // If there are any unclaimed block infos, go ahead and destroy them
00051   // now.  This can happen if IR-gen gets clever and skips evaluating
00052   // something.
00053   if (FirstBlockInfo)
00054     destroyBlockInfos(FirstBlockInfo);
00055 }
00056 
00057 
00058 llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
00059   return CGM.getTypes().ConvertTypeForMem(T);
00060 }
00061 
00062 llvm::Type *CodeGenFunction::ConvertType(QualType T) {
00063   return CGM.getTypes().ConvertType(T);
00064 }
00065 
00066 bool CodeGenFunction::hasAggregateLLVMType(QualType type) {
00067   switch (type.getCanonicalType()->getTypeClass()) {
00068 #define TYPE(name, parent)
00069 #define ABSTRACT_TYPE(name, parent)
00070 #define NON_CANONICAL_TYPE(name, parent) case Type::name:
00071 #define DEPENDENT_TYPE(name, parent) case Type::name:
00072 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(name, parent) case Type::name:
00073 #include "clang/AST/TypeNodes.def"
00074     llvm_unreachable("non-canonical or dependent type in IR-generation");
00075 
00076   case Type::Builtin:
00077   case Type::Pointer:
00078   case Type::BlockPointer:
00079   case Type::LValueReference:
00080   case Type::RValueReference:
00081   case Type::MemberPointer:
00082   case Type::Vector:
00083   case Type::ExtVector:
00084   case Type::FunctionProto:
00085   case Type::FunctionNoProto:
00086   case Type::Enum:
00087   case Type::ObjCObjectPointer:
00088     return false;
00089 
00090   // Complexes, arrays, records, and Objective-C objects.
00091   case Type::Complex:
00092   case Type::ConstantArray:
00093   case Type::IncompleteArray:
00094   case Type::VariableArray:
00095   case Type::Record:
00096   case Type::ObjCObject:
00097   case Type::ObjCInterface:
00098     return true;
00099 
00100   // In IRGen, atomic types are just the underlying type
00101   case Type::Atomic:
00102     return hasAggregateLLVMType(type->getAs<AtomicType>()->getValueType());
00103   }
00104   llvm_unreachable("unknown type kind!");
00105 }
00106 
00107 void CodeGenFunction::EmitReturnBlock() {
00108   // For cleanliness, we try to avoid emitting the return block for
00109   // simple cases.
00110   llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
00111 
00112   if (CurBB) {
00113     assert(!CurBB->getTerminator() && "Unexpected terminated block.");
00114 
00115     // We have a valid insert point, reuse it if it is empty or there are no
00116     // explicit jumps to the return block.
00117     if (CurBB->empty() || ReturnBlock.getBlock()->use_empty()) {
00118       ReturnBlock.getBlock()->replaceAllUsesWith(CurBB);
00119       delete ReturnBlock.getBlock();
00120     } else
00121       EmitBlock(ReturnBlock.getBlock());
00122     return;
00123   }
00124 
00125   // Otherwise, if the return block is the target of a single direct
00126   // branch then we can just put the code in that block instead. This
00127   // cleans up functions which started with a unified return block.
00128   if (ReturnBlock.getBlock()->hasOneUse()) {
00129     llvm::BranchInst *BI =
00130       dyn_cast<llvm::BranchInst>(*ReturnBlock.getBlock()->use_begin());
00131     if (BI && BI->isUnconditional() &&
00132         BI->getSuccessor(0) == ReturnBlock.getBlock()) {
00133       // Reset insertion point, including debug location, and delete the branch.
00134       Builder.SetCurrentDebugLocation(BI->getDebugLoc());
00135       Builder.SetInsertPoint(BI->getParent());
00136       BI->eraseFromParent();
00137       delete ReturnBlock.getBlock();
00138       return;
00139     }
00140   }
00141 
00142   // FIXME: We are at an unreachable point, there is no reason to emit the block
00143   // unless it has uses. However, we still need a place to put the debug
00144   // region.end for now.
00145 
00146   EmitBlock(ReturnBlock.getBlock());
00147 }
00148 
00149 static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB) {
00150   if (!BB) return;
00151   if (!BB->use_empty())
00152     return CGF.CurFn->getBasicBlockList().push_back(BB);
00153   delete BB;
00154 }
00155 
00156 void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
00157   assert(BreakContinueStack.empty() &&
00158          "mismatched push/pop in break/continue stack!");
00159 
00160   // Pop any cleanups that might have been associated with the
00161   // parameters.  Do this in whatever block we're currently in; it's
00162   // important to do this before we enter the return block or return
00163   // edges will be *really* confused.
00164   if (EHStack.stable_begin() != PrologueCleanupDepth)
00165     PopCleanupBlocks(PrologueCleanupDepth);
00166 
00167   // Emit function epilog (to return).
00168   EmitReturnBlock();
00169 
00170   if (ShouldInstrumentFunction())
00171     EmitFunctionInstrumentation("__cyg_profile_func_exit");
00172 
00173   // Emit debug descriptor for function end.
00174   if (CGDebugInfo *DI = getDebugInfo()) {
00175     DI->setLocation(EndLoc);
00176     DI->EmitFunctionEnd(Builder);
00177   }
00178 
00179   EmitFunctionEpilog(*CurFnInfo);
00180   EmitEndEHSpec(CurCodeDecl);
00181 
00182   assert(EHStack.empty() &&
00183          "did not remove all scopes from cleanup stack!");
00184 
00185   // If someone did an indirect goto, emit the indirect goto block at the end of
00186   // the function.
00187   if (IndirectBranch) {
00188     EmitBlock(IndirectBranch->getParent());
00189     Builder.ClearInsertionPoint();
00190   }
00191   
00192   // Remove the AllocaInsertPt instruction, which is just a convenience for us.
00193   llvm::Instruction *Ptr = AllocaInsertPt;
00194   AllocaInsertPt = 0;
00195   Ptr->eraseFromParent();
00196   
00197   // If someone took the address of a label but never did an indirect goto, we
00198   // made a zero entry PHI node, which is illegal, zap it now.
00199   if (IndirectBranch) {
00200     llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
00201     if (PN->getNumIncomingValues() == 0) {
00202       PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
00203       PN->eraseFromParent();
00204     }
00205   }
00206 
00207   EmitIfUsed(*this, EHResumeBlock);
00208   EmitIfUsed(*this, TerminateLandingPad);
00209   EmitIfUsed(*this, TerminateHandler);
00210   EmitIfUsed(*this, UnreachableBlock);
00211 
00212   if (CGM.getCodeGenOpts().EmitDeclMetadata)
00213     EmitDeclMetadata();
00214 }
00215 
00216 /// ShouldInstrumentFunction - Return true if the current function should be
00217 /// instrumented with __cyg_profile_func_* calls
00218 bool CodeGenFunction::ShouldInstrumentFunction() {
00219   if (!CGM.getCodeGenOpts().InstrumentFunctions)
00220     return false;
00221   if (!CurFuncDecl || CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>())
00222     return false;
00223   return true;
00224 }
00225 
00226 /// EmitFunctionInstrumentation - Emit LLVM code to call the specified
00227 /// instrumentation function with the current function and the call site, if
00228 /// function instrumentation is enabled.
00229 void CodeGenFunction::EmitFunctionInstrumentation(const char *Fn) {
00230   // void __cyg_profile_func_{enter,exit} (void *this_fn, void *call_site);
00231   llvm::PointerType *PointerTy = Int8PtrTy;
00232   llvm::Type *ProfileFuncArgs[] = { PointerTy, PointerTy };
00233   llvm::FunctionType *FunctionTy =
00234     llvm::FunctionType::get(VoidTy, ProfileFuncArgs, false);
00235 
00236   llvm::Constant *F = CGM.CreateRuntimeFunction(FunctionTy, Fn);
00237   llvm::CallInst *CallSite = Builder.CreateCall(
00238     CGM.getIntrinsic(llvm::Intrinsic::returnaddress),
00239     llvm::ConstantInt::get(Int32Ty, 0),
00240     "callsite");
00241 
00242   Builder.CreateCall2(F,
00243                       llvm::ConstantExpr::getBitCast(CurFn, PointerTy),
00244                       CallSite);
00245 }
00246 
00247 void CodeGenFunction::EmitMCountInstrumentation() {
00248   llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
00249 
00250   llvm::Constant *MCountFn = CGM.CreateRuntimeFunction(FTy,
00251                                                        Target.getMCountName());
00252   Builder.CreateCall(MCountFn);
00253 }
00254 
00255 void CodeGenFunction::StartFunction(GlobalDecl GD, QualType RetTy,
00256                                     llvm::Function *Fn,
00257                                     const CGFunctionInfo &FnInfo,
00258                                     const FunctionArgList &Args,
00259                                     SourceLocation StartLoc) {
00260   const Decl *D = GD.getDecl();
00261   
00262   DidCallStackSave = false;
00263   CurCodeDecl = CurFuncDecl = D;
00264   FnRetTy = RetTy;
00265   CurFn = Fn;
00266   CurFnInfo = &FnInfo;
00267   assert(CurFn->isDeclaration() && "Function already has body?");
00268 
00269   // Pass inline keyword to optimizer if it appears explicitly on any
00270   // declaration.
00271   if (!CGM.getCodeGenOpts().NoInline) 
00272     if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
00273       for (FunctionDecl::redecl_iterator RI = FD->redecls_begin(),
00274              RE = FD->redecls_end(); RI != RE; ++RI)
00275         if (RI->isInlineSpecified()) {
00276           Fn->addFnAttr(llvm::Attribute::InlineHint);
00277           break;
00278         }
00279 
00280   if (getContext().getLangOpts().OpenCL) {
00281     // Add metadata for a kernel function.
00282     if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
00283       if (FD->hasAttr<OpenCLKernelAttr>()) {
00284         llvm::LLVMContext &Context = getLLVMContext();
00285         llvm::NamedMDNode *OpenCLMetadata = 
00286           CGM.getModule().getOrInsertNamedMetadata("opencl.kernels");
00287           
00288         llvm::Value *Op = Fn;
00289         OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Op));
00290       }
00291   }
00292 
00293   llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
00294 
00295   // Create a marker to make it easy to insert allocas into the entryblock
00296   // later.  Don't create this with the builder, because we don't want it
00297   // folded.
00298   llvm::Value *Undef = llvm::UndefValue::get(Int32Ty);
00299   AllocaInsertPt = new llvm::BitCastInst(Undef, Int32Ty, "", EntryBB);
00300   if (Builder.isNamePreserving())
00301     AllocaInsertPt->setName("allocapt");
00302 
00303   ReturnBlock = getJumpDestInCurrentScope("return");
00304 
00305   Builder.SetInsertPoint(EntryBB);
00306 
00307   // Emit subprogram debug descriptor.
00308   if (CGDebugInfo *DI = getDebugInfo()) {
00309     unsigned NumArgs = 0;
00310     QualType *ArgsArray = new QualType[Args.size()];
00311     for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
00312    i != e; ++i) {
00313       ArgsArray[NumArgs++] = (*i)->getType();
00314     }
00315 
00316     QualType FnType =
00317       getContext().getFunctionType(RetTy, ArgsArray, NumArgs,
00318                                    FunctionProtoType::ExtProtoInfo());
00319 
00320     delete[] ArgsArray;
00321 
00322     DI->setLocation(StartLoc);
00323     DI->EmitFunctionStart(GD, FnType, CurFn, Builder);
00324   }
00325 
00326   if (ShouldInstrumentFunction())
00327     EmitFunctionInstrumentation("__cyg_profile_func_enter");
00328 
00329   if (CGM.getCodeGenOpts().InstrumentForProfiling)
00330     EmitMCountInstrumentation();
00331 
00332   if (RetTy->isVoidType()) {
00333     // Void type; nothing to return.
00334     ReturnValue = 0;
00335   } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
00336              hasAggregateLLVMType(CurFnInfo->getReturnType())) {
00337     // Indirect aggregate return; emit returned value directly into sret slot.
00338     // This reduces code size, and affects correctness in C++.
00339     ReturnValue = CurFn->arg_begin();
00340   } else {
00341     ReturnValue = CreateIRTemp(RetTy, "retval");
00342 
00343     // Tell the epilog emitter to autorelease the result.  We do this
00344     // now so that various specialized functions can suppress it
00345     // during their IR-generation.
00346     if (getLangOpts().ObjCAutoRefCount &&
00347         !CurFnInfo->isReturnsRetained() &&
00348         RetTy->isObjCRetainableType())
00349       AutoreleaseResult = true;
00350   }
00351 
00352   EmitStartEHSpec(CurCodeDecl);
00353 
00354   PrologueCleanupDepth = EHStack.stable_begin();
00355   EmitFunctionProlog(*CurFnInfo, CurFn, Args);
00356 
00357   if (D && isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance()) {
00358     CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
00359     const CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
00360     if (MD->getParent()->isLambda() &&
00361         MD->getOverloadedOperator() == OO_Call) {
00362       // We're in a lambda; figure out the captures.
00363       MD->getParent()->getCaptureFields(LambdaCaptureFields,
00364                                         LambdaThisCaptureField);
00365       if (LambdaThisCaptureField) {
00366         // If this lambda captures this, load it.
00367         QualType LambdaTagType =
00368             getContext().getTagDeclType(LambdaThisCaptureField->getParent());
00369         LValue LambdaLV = MakeNaturalAlignAddrLValue(CXXABIThisValue,
00370                                                      LambdaTagType);
00371         LValue ThisLValue = EmitLValueForField(LambdaLV,
00372                                                LambdaThisCaptureField);
00373         CXXThisValue = EmitLoadOfLValue(ThisLValue).getScalarVal();
00374       }
00375     } else {
00376       // Not in a lambda; just use 'this' from the method.
00377       // FIXME: Should we generate a new load for each use of 'this'?  The
00378       // fast register allocator would be happier...
00379       CXXThisValue = CXXABIThisValue;
00380     }
00381   }
00382 
00383   // If any of the arguments have a variably modified type, make sure to
00384   // emit the type size.
00385   for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
00386        i != e; ++i) {
00387     QualType Ty = (*i)->getType();
00388 
00389     if (Ty->isVariablyModifiedType())
00390       EmitVariablyModifiedType(Ty);
00391   }
00392   // Emit a location at the end of the prologue.
00393   if (CGDebugInfo *DI = getDebugInfo())
00394     DI->EmitLocation(Builder, StartLoc);
00395 }
00396 
00397 void CodeGenFunction::EmitFunctionBody(FunctionArgList &Args) {
00398   const FunctionDecl *FD = cast<FunctionDecl>(CurGD.getDecl());
00399   assert(FD->getBody());
00400   EmitStmt(FD->getBody());
00401 }
00402 
00403 /// Tries to mark the given function nounwind based on the
00404 /// non-existence of any throwing calls within it.  We believe this is
00405 /// lightweight enough to do at -O0.
00406 static void TryMarkNoThrow(llvm::Function *F) {
00407   // LLVM treats 'nounwind' on a function as part of the type, so we
00408   // can't do this on functions that can be overwritten.
00409   if (F->mayBeOverridden()) return;
00410 
00411   for (llvm::Function::iterator FI = F->begin(), FE = F->end(); FI != FE; ++FI)
00412     for (llvm::BasicBlock::iterator
00413            BI = FI->begin(), BE = FI->end(); BI != BE; ++BI)
00414       if (llvm::CallInst *Call = dyn_cast<llvm::CallInst>(&*BI)) {
00415         if (!Call->doesNotThrow())
00416           return;
00417       } else if (isa<llvm::ResumeInst>(&*BI)) {
00418         return;
00419       }
00420   F->setDoesNotThrow(true);
00421 }
00422 
00423 void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn,
00424                                    const CGFunctionInfo &FnInfo) {
00425   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
00426   
00427   // Check if we should generate debug info for this function.
00428   if (CGM.getModuleDebugInfo() && !FD->hasAttr<NoDebugAttr>())
00429     DebugInfo = CGM.getModuleDebugInfo();
00430 
00431   FunctionArgList Args;
00432   QualType ResTy = FD->getResultType();
00433 
00434   CurGD = GD;
00435   if (isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isInstance())
00436     CGM.getCXXABI().BuildInstanceFunctionParams(*this, ResTy, Args);
00437 
00438   for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i)
00439     Args.push_back(FD->getParamDecl(i));
00440 
00441   SourceRange BodyRange;
00442   if (Stmt *Body = FD->getBody()) BodyRange = Body->getSourceRange();
00443 
00444   // Emit the standard function prologue.
00445   StartFunction(GD, ResTy, Fn, FnInfo, Args, BodyRange.getBegin());
00446 
00447   // Generate the body of the function.
00448   if (isa<CXXDestructorDecl>(FD))
00449     EmitDestructorBody(Args);
00450   else if (isa<CXXConstructorDecl>(FD))
00451     EmitConstructorBody(Args);
00452   else if (getContext().getLangOpts().CUDA &&
00453            !CGM.getCodeGenOpts().CUDAIsDevice &&
00454            FD->hasAttr<CUDAGlobalAttr>())
00455     CGM.getCUDARuntime().EmitDeviceStubBody(*this, Args);
00456   else if (isa<CXXConversionDecl>(FD) &&
00457            cast<CXXConversionDecl>(FD)->isLambdaToBlockPointerConversion()) {
00458     // The lambda conversion to block pointer is special; the semantics can't be
00459     // expressed in the AST, so IRGen needs to special-case it.
00460     EmitLambdaToBlockPointerBody(Args);
00461   } else if (isa<CXXMethodDecl>(FD) &&
00462              cast<CXXMethodDecl>(FD)->isLambdaStaticInvoker()) {
00463     // The lambda "__invoke" function is special, because it forwards or
00464     // clones the body of the function call operator (but is actually static).
00465     EmitLambdaStaticInvokeFunction(cast<CXXMethodDecl>(FD));
00466   }
00467   else
00468     EmitFunctionBody(Args);
00469 
00470   // Emit the standard function epilogue.
00471   FinishFunction(BodyRange.getEnd());
00472 
00473   // If we haven't marked the function nothrow through other means, do
00474   // a quick pass now to see if we can.
00475   if (!CurFn->doesNotThrow())
00476     TryMarkNoThrow(CurFn);
00477 }
00478 
00479 /// ContainsLabel - Return true if the statement contains a label in it.  If
00480 /// this statement is not executed normally, it not containing a label means
00481 /// that we can just remove the code.
00482 bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
00483   // Null statement, not a label!
00484   if (S == 0) return false;
00485 
00486   // If this is a label, we have to emit the code, consider something like:
00487   // if (0) {  ...  foo:  bar(); }  goto foo;
00488   //
00489   // TODO: If anyone cared, we could track __label__'s, since we know that you
00490   // can't jump to one from outside their declared region.
00491   if (isa<LabelStmt>(S))
00492     return true;
00493   
00494   // If this is a case/default statement, and we haven't seen a switch, we have
00495   // to emit the code.
00496   if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
00497     return true;
00498 
00499   // If this is a switch statement, we want to ignore cases below it.
00500   if (isa<SwitchStmt>(S))
00501     IgnoreCaseStmts = true;
00502 
00503   // Scan subexpressions for verboten labels.
00504   for (Stmt::const_child_range I = S->children(); I; ++I)
00505     if (ContainsLabel(*I, IgnoreCaseStmts))
00506       return true;
00507 
00508   return false;
00509 }
00510 
00511 /// containsBreak - Return true if the statement contains a break out of it.
00512 /// If the statement (recursively) contains a switch or loop with a break
00513 /// inside of it, this is fine.
00514 bool CodeGenFunction::containsBreak(const Stmt *S) {
00515   // Null statement, not a label!
00516   if (S == 0) return false;
00517 
00518   // If this is a switch or loop that defines its own break scope, then we can
00519   // include it and anything inside of it.
00520   if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S) ||
00521       isa<ForStmt>(S))
00522     return false;
00523   
00524   if (isa<BreakStmt>(S))
00525     return true;
00526   
00527   // Scan subexpressions for verboten breaks.
00528   for (Stmt::const_child_range I = S->children(); I; ++I)
00529     if (containsBreak(*I))
00530       return true;
00531   
00532   return false;
00533 }
00534 
00535 
00536 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
00537 /// to a constant, or if it does but contains a label, return false.  If it
00538 /// constant folds return true and set the boolean result in Result.
00539 bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
00540                                                    bool &ResultBool) {
00541   llvm::APInt ResultInt;
00542   if (!ConstantFoldsToSimpleInteger(Cond, ResultInt))
00543     return false;
00544   
00545   ResultBool = ResultInt.getBoolValue();
00546   return true;
00547 }
00548 
00549 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
00550 /// to a constant, or if it does but contains a label, return false.  If it
00551 /// constant folds return true and set the folded value.
00552 bool CodeGenFunction::
00553 ConstantFoldsToSimpleInteger(const Expr *Cond, llvm::APInt &ResultInt) {
00554   // FIXME: Rename and handle conversion of other evaluatable things
00555   // to bool.
00556   llvm::APSInt Int;
00557   if (!Cond->EvaluateAsInt(Int, getContext()))
00558     return false;  // Not foldable, not integer or not fully evaluatable.
00559 
00560   if (CodeGenFunction::ContainsLabel(Cond))
00561     return false;  // Contains a label.
00562 
00563   ResultInt = Int;
00564   return true;
00565 }
00566 
00567 
00568 
00569 /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
00570 /// statement) to the specified blocks.  Based on the condition, this might try
00571 /// to simplify the codegen of the conditional based on the branch.
00572 ///
00573 void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
00574                                            llvm::BasicBlock *TrueBlock,
00575                                            llvm::BasicBlock *FalseBlock) {
00576   Cond = Cond->IgnoreParens();
00577 
00578   if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
00579     // Handle X && Y in a condition.
00580     if (CondBOp->getOpcode() == BO_LAnd) {
00581       // If we have "1 && X", simplify the code.  "0 && X" would have constant
00582       // folded if the case was simple enough.
00583       bool ConstantBool = false;
00584       if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
00585           ConstantBool) {
00586         // br(1 && X) -> br(X).
00587         return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
00588       }
00589 
00590       // If we have "X && 1", simplify the code to use an uncond branch.
00591       // "X && 0" would have been constant folded to 0.
00592       if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
00593           ConstantBool) {
00594         // br(X && 1) -> br(X).
00595         return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
00596       }
00597 
00598       // Emit the LHS as a conditional.  If the LHS conditional is false, we
00599       // want to jump to the FalseBlock.
00600       llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
00601 
00602       ConditionalEvaluation eval(*this);
00603       EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock);
00604       EmitBlock(LHSTrue);
00605 
00606       // Any temporaries created here are conditional.
00607       eval.begin(*this);
00608       EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
00609       eval.end(*this);
00610 
00611       return;
00612     }
00613     
00614     if (CondBOp->getOpcode() == BO_LOr) {
00615       // If we have "0 || X", simplify the code.  "1 || X" would have constant
00616       // folded if the case was simple enough.
00617       bool ConstantBool = false;
00618       if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
00619           !ConstantBool) {
00620         // br(0 || X) -> br(X).
00621         return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
00622       }
00623 
00624       // If we have "X || 0", simplify the code to use an uncond branch.
00625       // "X || 1" would have been constant folded to 1.
00626       if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
00627           !ConstantBool) {
00628         // br(X || 0) -> br(X).
00629         return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
00630       }
00631 
00632       // Emit the LHS as a conditional.  If the LHS conditional is true, we
00633       // want to jump to the TrueBlock.
00634       llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
00635 
00636       ConditionalEvaluation eval(*this);
00637       EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse);
00638       EmitBlock(LHSFalse);
00639 
00640       // Any temporaries created here are conditional.
00641       eval.begin(*this);
00642       EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
00643       eval.end(*this);
00644 
00645       return;
00646     }
00647   }
00648 
00649   if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
00650     // br(!x, t, f) -> br(x, f, t)
00651     if (CondUOp->getOpcode() == UO_LNot)
00652       return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock);
00653   }
00654 
00655   if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
00656     // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
00657     llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
00658     llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
00659 
00660     ConditionalEvaluation cond(*this);
00661     EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock);
00662 
00663     cond.begin(*this);
00664     EmitBlock(LHSBlock);
00665     EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock);
00666     cond.end(*this);
00667 
00668     cond.begin(*this);
00669     EmitBlock(RHSBlock);
00670     EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock);
00671     cond.end(*this);
00672 
00673     return;
00674   }
00675 
00676   // Emit the code with the fully general case.
00677   llvm::Value *CondV = EvaluateExprAsBool(Cond);
00678   Builder.CreateCondBr(CondV, TrueBlock, FalseBlock);
00679 }
00680 
00681 /// ErrorUnsupported - Print out an error that codegen doesn't support the
00682 /// specified stmt yet.
00683 void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type,
00684                                        bool OmitOnError) {
00685   CGM.ErrorUnsupported(S, Type, OmitOnError);
00686 }
00687 
00688 /// emitNonZeroVLAInit - Emit the "zero" initialization of a
00689 /// variable-length array whose elements have a non-zero bit-pattern.
00690 ///
00691 /// \param src - a char* pointing to the bit-pattern for a single
00692 /// base element of the array
00693 /// \param sizeInChars - the total size of the VLA, in chars
00694 /// \param align - the total alignment of the VLA
00695 static void emitNonZeroVLAInit(CodeGenFunction &CGF, QualType baseType,
00696                                llvm::Value *dest, llvm::Value *src, 
00697                                llvm::Value *sizeInChars) {
00698   std::pair<CharUnits,CharUnits> baseSizeAndAlign
00699     = CGF.getContext().getTypeInfoInChars(baseType);
00700 
00701   CGBuilderTy &Builder = CGF.Builder;
00702 
00703   llvm::Value *baseSizeInChars
00704     = llvm::ConstantInt::get(CGF.IntPtrTy, baseSizeAndAlign.first.getQuantity());
00705 
00706   llvm::Type *i8p = Builder.getInt8PtrTy();
00707 
00708   llvm::Value *begin = Builder.CreateBitCast(dest, i8p, "vla.begin");
00709   llvm::Value *end = Builder.CreateInBoundsGEP(dest, sizeInChars, "vla.end");
00710 
00711   llvm::BasicBlock *originBB = CGF.Builder.GetInsertBlock();
00712   llvm::BasicBlock *loopBB = CGF.createBasicBlock("vla-init.loop");
00713   llvm::BasicBlock *contBB = CGF.createBasicBlock("vla-init.cont");
00714 
00715   // Make a loop over the VLA.  C99 guarantees that the VLA element
00716   // count must be nonzero.
00717   CGF.EmitBlock(loopBB);
00718 
00719   llvm::PHINode *cur = Builder.CreatePHI(i8p, 2, "vla.cur");
00720   cur->addIncoming(begin, originBB);
00721 
00722   // memcpy the individual element bit-pattern.
00723   Builder.CreateMemCpy(cur, src, baseSizeInChars,
00724                        baseSizeAndAlign.second.getQuantity(),
00725                        /*volatile*/ false);
00726 
00727   // Go to the next element.
00728   llvm::Value *next = Builder.CreateConstInBoundsGEP1_32(cur, 1, "vla.next");
00729 
00730   // Leave if that's the end of the VLA.
00731   llvm::Value *done = Builder.CreateICmpEQ(next, end, "vla-init.isdone");
00732   Builder.CreateCondBr(done, contBB, loopBB);
00733   cur->addIncoming(next, loopBB);
00734 
00735   CGF.EmitBlock(contBB);
00736 } 
00737 
00738 void
00739 CodeGenFunction::EmitNullInitialization(llvm::Value *DestPtr, QualType Ty) {
00740   // Ignore empty classes in C++.
00741   if (getContext().getLangOpts().CPlusPlus) {
00742     if (const RecordType *RT = Ty->getAs<RecordType>()) {
00743       if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty())
00744         return;
00745     }
00746   }
00747 
00748   // Cast the dest ptr to the appropriate i8 pointer type.
00749   unsigned DestAS =
00750     cast<llvm::PointerType>(DestPtr->getType())->getAddressSpace();
00751   llvm::Type *BP = Builder.getInt8PtrTy(DestAS);
00752   if (DestPtr->getType() != BP)
00753     DestPtr = Builder.CreateBitCast(DestPtr, BP);
00754 
00755   // Get size and alignment info for this aggregate.
00756   std::pair<CharUnits, CharUnits> TypeInfo = 
00757     getContext().getTypeInfoInChars(Ty);
00758   CharUnits Size = TypeInfo.first;
00759   CharUnits Align = TypeInfo.second;
00760 
00761   llvm::Value *SizeVal;
00762   const VariableArrayType *vla;
00763 
00764   // Don't bother emitting a zero-byte memset.
00765   if (Size.isZero()) {
00766     // But note that getTypeInfo returns 0 for a VLA.
00767     if (const VariableArrayType *vlaType =
00768           dyn_cast_or_null<VariableArrayType>(
00769                                           getContext().getAsArrayType(Ty))) {
00770       QualType eltType;
00771       llvm::Value *numElts;
00772       llvm::tie(numElts, eltType) = getVLASize(vlaType);
00773 
00774       SizeVal = numElts;
00775       CharUnits eltSize = getContext().getTypeSizeInChars(eltType);
00776       if (!eltSize.isOne())
00777         SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(eltSize));
00778       vla = vlaType;
00779     } else {
00780       return;
00781     }
00782   } else {
00783     SizeVal = CGM.getSize(Size);
00784     vla = 0;
00785   }
00786 
00787   // If the type contains a pointer to data member we can't memset it to zero.
00788   // Instead, create a null constant and copy it to the destination.
00789   // TODO: there are other patterns besides zero that we can usefully memset,
00790   // like -1, which happens to be the pattern used by member-pointers.
00791   if (!CGM.getTypes().isZeroInitializable(Ty)) {
00792     // For a VLA, emit a single element, then splat that over the VLA.
00793     if (vla) Ty = getContext().getBaseElementType(vla);
00794 
00795     llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty);
00796 
00797     llvm::GlobalVariable *NullVariable = 
00798       new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(),
00799                                /*isConstant=*/true, 
00800                                llvm::GlobalVariable::PrivateLinkage,
00801                                NullConstant, Twine());
00802     llvm::Value *SrcPtr =
00803       Builder.CreateBitCast(NullVariable, Builder.getInt8PtrTy());
00804 
00805     if (vla) return emitNonZeroVLAInit(*this, Ty, DestPtr, SrcPtr, SizeVal);
00806 
00807     // Get and call the appropriate llvm.memcpy overload.
00808     Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, Align.getQuantity(), false);
00809     return;
00810   } 
00811   
00812   // Otherwise, just memset the whole thing to zero.  This is legal
00813   // because in LLVM, all default initializers (other than the ones we just
00814   // handled above) are guaranteed to have a bit pattern of all zeros.
00815   Builder.CreateMemSet(DestPtr, Builder.getInt8(0), SizeVal, 
00816                        Align.getQuantity(), false);
00817 }
00818 
00819 llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelDecl *L) {
00820   // Make sure that there is a block for the indirect goto.
00821   if (IndirectBranch == 0)
00822     GetIndirectGotoBlock();
00823   
00824   llvm::BasicBlock *BB = getJumpDestForLabel(L).getBlock();
00825   
00826   // Make sure the indirect branch includes all of the address-taken blocks.
00827   IndirectBranch->addDestination(BB);
00828   return llvm::BlockAddress::get(CurFn, BB);
00829 }
00830 
00831 llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
00832   // If we already made the indirect branch for indirect goto, return its block.
00833   if (IndirectBranch) return IndirectBranch->getParent();
00834   
00835   CGBuilderTy TmpBuilder(createBasicBlock("indirectgoto"));
00836   
00837   // Create the PHI node that indirect gotos will add entries to.
00838   llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, 0,
00839                                               "indirect.goto.dest");
00840   
00841   // Create the indirect branch instruction.
00842   IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
00843   return IndirectBranch->getParent();
00844 }
00845 
00846 /// Computes the length of an array in elements, as well as the base
00847 /// element type and a properly-typed first element pointer.
00848 llvm::Value *CodeGenFunction::emitArrayLength(const ArrayType *origArrayType,
00849                                               QualType &baseType,
00850                                               llvm::Value *&addr) {
00851   const ArrayType *arrayType = origArrayType;
00852 
00853   // If it's a VLA, we have to load the stored size.  Note that
00854   // this is the size of the VLA in bytes, not its size in elements.
00855   llvm::Value *numVLAElements = 0;
00856   if (isa<VariableArrayType>(arrayType)) {
00857     numVLAElements = getVLASize(cast<VariableArrayType>(arrayType)).first;
00858 
00859     // Walk into all VLAs.  This doesn't require changes to addr,
00860     // which has type T* where T is the first non-VLA element type.
00861     do {
00862       QualType elementType = arrayType->getElementType();
00863       arrayType = getContext().getAsArrayType(elementType);
00864 
00865       // If we only have VLA components, 'addr' requires no adjustment.
00866       if (!arrayType) {
00867         baseType = elementType;
00868         return numVLAElements;
00869       }
00870     } while (isa<VariableArrayType>(arrayType));
00871 
00872     // We get out here only if we find a constant array type
00873     // inside the VLA.
00874   }
00875 
00876   // We have some number of constant-length arrays, so addr should
00877   // have LLVM type [M x [N x [...]]]*.  Build a GEP that walks
00878   // down to the first element of addr.
00879   SmallVector<llvm::Value*, 8> gepIndices;
00880 
00881   // GEP down to the array type.
00882   llvm::ConstantInt *zero = Builder.getInt32(0);
00883   gepIndices.push_back(zero);
00884 
00885   uint64_t countFromCLAs = 1;
00886   QualType eltType;
00887 
00888   llvm::ArrayType *llvmArrayType =
00889     dyn_cast<llvm::ArrayType>(
00890       cast<llvm::PointerType>(addr->getType())->getElementType());
00891   while (llvmArrayType) {
00892     assert(isa<ConstantArrayType>(arrayType));
00893     assert(cast<ConstantArrayType>(arrayType)->getSize().getZExtValue()
00894              == llvmArrayType->getNumElements());
00895 
00896     gepIndices.push_back(zero);
00897     countFromCLAs *= llvmArrayType->getNumElements();
00898     eltType = arrayType->getElementType();
00899 
00900     llvmArrayType =
00901       dyn_cast<llvm::ArrayType>(llvmArrayType->getElementType());
00902     arrayType = getContext().getAsArrayType(arrayType->getElementType());
00903     assert((!llvmArrayType || arrayType) &&
00904            "LLVM and Clang types are out-of-synch");
00905   }
00906 
00907   if (arrayType) {
00908     // From this point onwards, the Clang array type has been emitted
00909     // as some other type (probably a packed struct). Compute the array
00910     // size, and just emit the 'begin' expression as a bitcast.
00911     while (arrayType) {
00912       countFromCLAs *=
00913           cast<ConstantArrayType>(arrayType)->getSize().getZExtValue();
00914       eltType = arrayType->getElementType();
00915       arrayType = getContext().getAsArrayType(eltType);
00916     }
00917 
00918     unsigned AddressSpace =
00919         cast<llvm::PointerType>(addr->getType())->getAddressSpace();
00920     llvm::Type *BaseType = ConvertType(eltType)->getPointerTo(AddressSpace);
00921     addr = Builder.CreateBitCast(addr, BaseType, "array.begin");
00922   } else {
00923     // Create the actual GEP.
00924     addr = Builder.CreateInBoundsGEP(addr, gepIndices, "array.begin");
00925   }
00926 
00927   baseType = eltType;
00928 
00929   llvm::Value *numElements
00930     = llvm::ConstantInt::get(SizeTy, countFromCLAs);
00931 
00932   // If we had any VLA dimensions, factor them in.
00933   if (numVLAElements)
00934     numElements = Builder.CreateNUWMul(numVLAElements, numElements);
00935 
00936   return numElements;
00937 }
00938 
00939 std::pair<llvm::Value*, QualType>
00940 CodeGenFunction::getVLASize(QualType type) {
00941   const VariableArrayType *vla = getContext().getAsVariableArrayType(type);
00942   assert(vla && "type was not a variable array type!");
00943   return getVLASize(vla);
00944 }
00945 
00946 std::pair<llvm::Value*, QualType>
00947 CodeGenFunction::getVLASize(const VariableArrayType *type) {
00948   // The number of elements so far; always size_t.
00949   llvm::Value *numElements = 0;
00950 
00951   QualType elementType;
00952   do {
00953     elementType = type->getElementType();
00954     llvm::Value *vlaSize = VLASizeMap[type->getSizeExpr()];
00955     assert(vlaSize && "no size for VLA!");
00956     assert(vlaSize->getType() == SizeTy);
00957 
00958     if (!numElements) {
00959       numElements = vlaSize;
00960     } else {
00961       // It's undefined behavior if this wraps around, so mark it that way.
00962       numElements = Builder.CreateNUWMul(numElements, vlaSize);
00963     }
00964   } while ((type = getContext().getAsVariableArrayType(elementType)));
00965 
00966   return std::pair<llvm::Value*,QualType>(numElements, elementType);
00967 }
00968 
00969 void CodeGenFunction::EmitVariablyModifiedType(QualType type) {
00970   assert(type->isVariablyModifiedType() &&
00971          "Must pass variably modified type to EmitVLASizes!");
00972 
00973   EnsureInsertPoint();
00974 
00975   // We're going to walk down into the type and look for VLA
00976   // expressions.
00977   do {
00978     assert(type->isVariablyModifiedType());
00979 
00980     const Type *ty = type.getTypePtr();
00981     switch (ty->getTypeClass()) {
00982 
00983 #define TYPE(Class, Base)
00984 #define ABSTRACT_TYPE(Class, Base)
00985 #define NON_CANONICAL_TYPE(Class, Base)
00986 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
00987 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
00988 #include "clang/AST/TypeNodes.def"
00989       llvm_unreachable("unexpected dependent type!");
00990 
00991     // These types are never variably-modified.
00992     case Type::Builtin:
00993     case Type::Complex:
00994     case Type::Vector:
00995     case Type::ExtVector:
00996     case Type::Record:
00997     case Type::Enum:
00998     case Type::Elaborated:
00999     case Type::TemplateSpecialization:
01000     case Type::ObjCObject:
01001     case Type::ObjCInterface:
01002     case Type::ObjCObjectPointer:
01003       llvm_unreachable("type class is never variably-modified!");
01004 
01005     case Type::Pointer:
01006       type = cast<PointerType>(ty)->getPointeeType();
01007       break;
01008 
01009     case Type::BlockPointer:
01010       type = cast<BlockPointerType>(ty)->getPointeeType();
01011       break;
01012 
01013     case Type::LValueReference:
01014     case Type::RValueReference:
01015       type = cast<ReferenceType>(ty)->getPointeeType();
01016       break;
01017 
01018     case Type::MemberPointer:
01019       type = cast<MemberPointerType>(ty)->getPointeeType();
01020       break;
01021 
01022     case Type::ConstantArray:
01023     case Type::IncompleteArray:
01024       // Losing element qualification here is fine.
01025       type = cast<ArrayType>(ty)->getElementType();
01026       break;
01027 
01028     case Type::VariableArray: {
01029       // Losing element qualification here is fine.
01030       const VariableArrayType *vat = cast<VariableArrayType>(ty);
01031 
01032       // Unknown size indication requires no size computation.
01033       // Otherwise, evaluate and record it.
01034       if (const Expr *size = vat->getSizeExpr()) {
01035         // It's possible that we might have emitted this already,
01036         // e.g. with a typedef and a pointer to it.
01037         llvm::Value *&entry = VLASizeMap[size];
01038         if (!entry) {
01039           // Always zexting here would be wrong if it weren't
01040           // undefined behavior to have a negative bound.
01041           entry = Builder.CreateIntCast(EmitScalarExpr(size), SizeTy,
01042                                         /*signed*/ false);
01043         }
01044       }
01045       type = vat->getElementType();
01046       break;
01047     }
01048 
01049     case Type::FunctionProto:
01050     case Type::FunctionNoProto:
01051       type = cast<FunctionType>(ty)->getResultType();
01052       break;
01053 
01054     case Type::Paren:
01055     case Type::TypeOf:
01056     case Type::UnaryTransform:
01057     case Type::Attributed:
01058     case Type::SubstTemplateTypeParm:
01059       // Keep walking after single level desugaring.
01060       type = type.getSingleStepDesugaredType(getContext());
01061       break;
01062 
01063     case Type::Typedef:
01064     case Type::Decltype:
01065     case Type::Auto:
01066       // Stop walking: nothing to do.
01067       return;
01068 
01069     case Type::TypeOfExpr:
01070       // Stop walking: emit typeof expression.
01071       EmitIgnoredExpr(cast<TypeOfExprType>(ty)->getUnderlyingExpr());
01072       return;
01073 
01074     case Type::Atomic:
01075       type = cast<AtomicType>(ty)->getValueType();
01076       break;
01077     }
01078   } while (type->isVariablyModifiedType());
01079 }
01080 
01081 llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) {
01082   if (getContext().getBuiltinVaListType()->isArrayType())
01083     return EmitScalarExpr(E);
01084   return EmitLValue(E).getAddress();
01085 }
01086 
01087 void CodeGenFunction::EmitDeclRefExprDbgValue(const DeclRefExpr *E, 
01088                                               llvm::Constant *Init) {
01089   assert (Init && "Invalid DeclRefExpr initializer!");
01090   if (CGDebugInfo *Dbg = getDebugInfo())
01091     if (CGM.getCodeGenOpts().DebugInfo >= CodeGenOptions::LimitedDebugInfo)
01092       Dbg->EmitGlobalVariable(E->getDecl(), Init);
01093 }
01094 
01095 CodeGenFunction::PeepholeProtection
01096 CodeGenFunction::protectFromPeepholes(RValue rvalue) {
01097   // At the moment, the only aggressive peephole we do in IR gen
01098   // is trunc(zext) folding, but if we add more, we can easily
01099   // extend this protection.
01100 
01101   if (!rvalue.isScalar()) return PeepholeProtection();
01102   llvm::Value *value = rvalue.getScalarVal();
01103   if (!isa<llvm::ZExtInst>(value)) return PeepholeProtection();
01104 
01105   // Just make an extra bitcast.
01106   assert(HaveInsertPoint());
01107   llvm::Instruction *inst = new llvm::BitCastInst(value, value->getType(), "",
01108                                                   Builder.GetInsertBlock());
01109 
01110   PeepholeProtection protection;
01111   protection.Inst = inst;
01112   return protection;
01113 }
01114 
01115 void CodeGenFunction::unprotectFromPeepholes(PeepholeProtection protection) {
01116   if (!protection.Inst) return;
01117 
01118   // In theory, we could try to duplicate the peepholes now, but whatever.
01119   protection.Inst->eraseFromParent();
01120 }
01121 
01122 llvm::Value *CodeGenFunction::EmitAnnotationCall(llvm::Value *AnnotationFn,
01123                                                  llvm::Value *AnnotatedVal,
01124                                                  llvm::StringRef AnnotationStr,
01125                                                  SourceLocation Location) {
01126   llvm::Value *Args[4] = {
01127     AnnotatedVal,
01128     Builder.CreateBitCast(CGM.EmitAnnotationString(AnnotationStr), Int8PtrTy),
01129     Builder.CreateBitCast(CGM.EmitAnnotationUnit(Location), Int8PtrTy),
01130     CGM.EmitAnnotationLineNo(Location)
01131   };
01132   return Builder.CreateCall(AnnotationFn, Args);
01133 }
01134 
01135 void CodeGenFunction::EmitVarAnnotations(const VarDecl *D, llvm::Value *V) {
01136   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
01137   // FIXME We create a new bitcast for every annotation because that's what
01138   // llvm-gcc was doing.
01139   for (specific_attr_iterator<AnnotateAttr>
01140        ai = D->specific_attr_begin<AnnotateAttr>(),
01141        ae = D->specific_attr_end<AnnotateAttr>(); ai != ae; ++ai)
01142     EmitAnnotationCall(CGM.getIntrinsic(llvm::Intrinsic::var_annotation),
01143                        Builder.CreateBitCast(V, CGM.Int8PtrTy, V->getName()),
01144                        (*ai)->getAnnotation(), D->getLocation());
01145 }
01146 
01147 llvm::Value *CodeGenFunction::EmitFieldAnnotations(const FieldDecl *D,
01148                                                    llvm::Value *V) {
01149   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
01150   llvm::Type *VTy = V->getType();
01151   llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::ptr_annotation,
01152                                     CGM.Int8PtrTy);
01153 
01154   for (specific_attr_iterator<AnnotateAttr>
01155        ai = D->specific_attr_begin<AnnotateAttr>(),
01156        ae = D->specific_attr_end<AnnotateAttr>(); ai != ae; ++ai) {
01157     // FIXME Always emit the cast inst so we can differentiate between
01158     // annotation on the first field of a struct and annotation on the struct
01159     // itself.
01160     if (VTy != CGM.Int8PtrTy)
01161       V = Builder.Insert(new llvm::BitCastInst(V, CGM.Int8PtrTy));
01162     V = EmitAnnotationCall(F, V, (*ai)->getAnnotation(), D->getLocation());
01163     V = Builder.CreateBitCast(V, VTy);
01164   }
01165 
01166   return V;
01167 }