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 14 #include "CodeGenFunction.h" 15 #include "CGCUDARuntime.h" 16 #include "CGCXXABI.h" 17 #include "CGDebugInfo.h" 18 #include "CodeGenModule.h" 19 #include "clang/AST/ASTContext.h" 20 #include "clang/AST/Decl.h" 21 #include "clang/AST/DeclCXX.h" 22 #include "clang/AST/StmtCXX.h" 23 #include "clang/Basic/OpenCL.h" 24 #include "clang/Basic/TargetInfo.h" 25 #include "clang/Frontend/CodeGenOptions.h" 26 #include "llvm/IR/DataLayout.h" 27 #include "llvm/IR/Intrinsics.h" 28 #include "llvm/IR/MDBuilder.h" 29 #include "llvm/IR/Operator.h" 30 using namespace clang; 31 using namespace CodeGen; 32 33 CodeGenFunction::CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext) 34 : CodeGenTypeCache(cgm), CGM(cgm), Target(cgm.getTarget()), 35 Builder(cgm.getModule().getContext()), CapturedStmtInfo(0), 36 SanitizePerformTypeCheck(CGM.getSanOpts().Null | 37 CGM.getSanOpts().Alignment | 38 CGM.getSanOpts().ObjectSize | 39 CGM.getSanOpts().Vptr), 40 SanOpts(&CGM.getSanOpts()), AutoreleaseResult(false), BlockInfo(0), 41 BlockPointer(0), LambdaThisCaptureField(0), NormalCleanupDest(0), 42 NextCleanupDestIndex(1), FirstBlockInfo(0), EHResumeBlock(0), 43 ExceptionSlot(0), EHSelectorSlot(0), DebugInfo(CGM.getModuleDebugInfo()), 44 DisableDebugInfo(false), DidCallStackSave(false), IndirectBranch(0), 45 SwitchInsn(0), CaseRangeBlock(0), UnreachableBlock(0), NumReturnExprs(0), 46 NumSimpleReturnExprs(0), CXXABIThisDecl(0), CXXABIThisValue(0), 47 CXXThisValue(0), CXXDefaultInitExprThis(0), 48 CXXStructorImplicitParamDecl(0), CXXStructorImplicitParamValue(0), 49 OutermostConditional(0), CurLexicalScope(0), TerminateLandingPad(0), 50 TerminateHandler(0), TrapBB(0) { 51 if (!suppressNewContext) 52 CGM.getCXXABI().getMangleContext().startNewFunction(); 53 54 llvm::FastMathFlags FMF; 55 if (CGM.getLangOpts().FastMath) 56 FMF.setUnsafeAlgebra(); 57 if (CGM.getLangOpts().FiniteMathOnly) { 58 FMF.setNoNaNs(); 59 FMF.setNoInfs(); 60 } 61 Builder.SetFastMathFlags(FMF); 62 } 63 64 CodeGenFunction::~CodeGenFunction() { 65 assert(LifetimeExtendedCleanupStack.empty() && "failed to emit a cleanup"); 66 67 // If there are any unclaimed block infos, go ahead and destroy them 68 // now. This can happen if IR-gen gets clever and skips evaluating 69 // something. 70 if (FirstBlockInfo) 71 destroyBlockInfos(FirstBlockInfo); 72 } 73 74 75 llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) { 76 return CGM.getTypes().ConvertTypeForMem(T); 77 } 78 79 llvm::Type *CodeGenFunction::ConvertType(QualType T) { 80 return CGM.getTypes().ConvertType(T); 81 } 82 83 TypeEvaluationKind CodeGenFunction::getEvaluationKind(QualType type) { 84 type = type.getCanonicalType(); 85 while (true) { 86 switch (type->getTypeClass()) { 87 #define TYPE(name, parent) 88 #define ABSTRACT_TYPE(name, parent) 89 #define NON_CANONICAL_TYPE(name, parent) case Type::name: 90 #define DEPENDENT_TYPE(name, parent) case Type::name: 91 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(name, parent) case Type::name: 92 #include "clang/AST/TypeNodes.def" 93 llvm_unreachable("non-canonical or dependent type in IR-generation"); 94 95 case Type::Auto: 96 llvm_unreachable("undeduced auto type in IR-generation"); 97 98 // Various scalar types. 99 case Type::Builtin: 100 case Type::Pointer: 101 case Type::BlockPointer: 102 case Type::LValueReference: 103 case Type::RValueReference: 104 case Type::MemberPointer: 105 case Type::Vector: 106 case Type::ExtVector: 107 case Type::FunctionProto: 108 case Type::FunctionNoProto: 109 case Type::Enum: 110 case Type::ObjCObjectPointer: 111 return TEK_Scalar; 112 113 // Complexes. 114 case Type::Complex: 115 return TEK_Complex; 116 117 // Arrays, records, and Objective-C objects. 118 case Type::ConstantArray: 119 case Type::IncompleteArray: 120 case Type::VariableArray: 121 case Type::Record: 122 case Type::ObjCObject: 123 case Type::ObjCInterface: 124 return TEK_Aggregate; 125 126 // We operate on atomic values according to their underlying type. 127 case Type::Atomic: 128 type = cast<AtomicType>(type)->getValueType(); 129 continue; 130 } 131 llvm_unreachable("unknown type kind!"); 132 } 133 } 134 135 void CodeGenFunction::EmitReturnBlock() { 136 // For cleanliness, we try to avoid emitting the return block for 137 // simple cases. 138 llvm::BasicBlock *CurBB = Builder.GetInsertBlock(); 139 140 if (CurBB) { 141 assert(!CurBB->getTerminator() && "Unexpected terminated block."); 142 143 // We have a valid insert point, reuse it if it is empty or there are no 144 // explicit jumps to the return block. 145 if (CurBB->empty() || ReturnBlock.getBlock()->use_empty()) { 146 ReturnBlock.getBlock()->replaceAllUsesWith(CurBB); 147 delete ReturnBlock.getBlock(); 148 } else 149 EmitBlock(ReturnBlock.getBlock()); 150 return; 151 } 152 153 // Otherwise, if the return block is the target of a single direct 154 // branch then we can just put the code in that block instead. This 155 // cleans up functions which started with a unified return block. 156 if (ReturnBlock.getBlock()->hasOneUse()) { 157 llvm::BranchInst *BI = 158 dyn_cast<llvm::BranchInst>(*ReturnBlock.getBlock()->use_begin()); 159 if (BI && BI->isUnconditional() && 160 BI->getSuccessor(0) == ReturnBlock.getBlock()) { 161 // Reset insertion point, including debug location, and delete the 162 // branch. This is really subtle and only works because the next change 163 // in location will hit the caching in CGDebugInfo::EmitLocation and not 164 // override this. 165 Builder.SetCurrentDebugLocation(BI->getDebugLoc()); 166 Builder.SetInsertPoint(BI->getParent()); 167 BI->eraseFromParent(); 168 delete ReturnBlock.getBlock(); 169 return; 170 } 171 } 172 173 // FIXME: We are at an unreachable point, there is no reason to emit the block 174 // unless it has uses. However, we still need a place to put the debug 175 // region.end for now. 176 177 EmitBlock(ReturnBlock.getBlock()); 178 } 179 180 static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB) { 181 if (!BB) return; 182 if (!BB->use_empty()) 183 return CGF.CurFn->getBasicBlockList().push_back(BB); 184 delete BB; 185 } 186 187 void CodeGenFunction::FinishFunction(SourceLocation EndLoc) { 188 assert(BreakContinueStack.empty() && 189 "mismatched push/pop in break/continue stack!"); 190 191 bool OnlySimpleReturnStmts = NumSimpleReturnExprs > 0 192 && NumSimpleReturnExprs == NumReturnExprs 193 && ReturnBlock.getBlock()->use_empty(); 194 // Usually the return expression is evaluated before the cleanup 195 // code. If the function contains only a simple return statement, 196 // such as a constant, the location before the cleanup code becomes 197 // the last useful breakpoint in the function, because the simple 198 // return expression will be evaluated after the cleanup code. To be 199 // safe, set the debug location for cleanup code to the location of 200 // the return statement. Otherwise the cleanup code should be at the 201 // end of the function's lexical scope. 202 // 203 // If there are multiple branches to the return block, the branch 204 // instructions will get the location of the return statements and 205 // all will be fine. 206 if (CGDebugInfo *DI = getDebugInfo()) { 207 if (OnlySimpleReturnStmts) 208 DI->EmitLocation(Builder, LastStopPoint); 209 else 210 DI->EmitLocation(Builder, EndLoc); 211 } 212 213 // Pop any cleanups that might have been associated with the 214 // parameters. Do this in whatever block we're currently in; it's 215 // important to do this before we enter the return block or return 216 // edges will be *really* confused. 217 bool EmitRetDbgLoc = true; 218 if (EHStack.stable_begin() != PrologueCleanupDepth) { 219 PopCleanupBlocks(PrologueCleanupDepth); 220 221 // Make sure the line table doesn't jump back into the body for 222 // the ret after it's been at EndLoc. 223 EmitRetDbgLoc = false; 224 225 if (CGDebugInfo *DI = getDebugInfo()) 226 if (OnlySimpleReturnStmts) 227 DI->EmitLocation(Builder, EndLoc); 228 } 229 230 // Emit function epilog (to return). 231 EmitReturnBlock(); 232 233 if (ShouldInstrumentFunction()) 234 EmitFunctionInstrumentation("__cyg_profile_func_exit"); 235 236 // Emit debug descriptor for function end. 237 if (CGDebugInfo *DI = getDebugInfo()) { 238 DI->EmitFunctionEnd(Builder); 239 } 240 241 EmitFunctionEpilog(*CurFnInfo, EmitRetDbgLoc, EndLoc); 242 EmitEndEHSpec(CurCodeDecl); 243 244 assert(EHStack.empty() && 245 "did not remove all scopes from cleanup stack!"); 246 247 // If someone did an indirect goto, emit the indirect goto block at the end of 248 // the function. 249 if (IndirectBranch) { 250 EmitBlock(IndirectBranch->getParent()); 251 Builder.ClearInsertionPoint(); 252 } 253 254 // Remove the AllocaInsertPt instruction, which is just a convenience for us. 255 llvm::Instruction *Ptr = AllocaInsertPt; 256 AllocaInsertPt = 0; 257 Ptr->eraseFromParent(); 258 259 // If someone took the address of a label but never did an indirect goto, we 260 // made a zero entry PHI node, which is illegal, zap it now. 261 if (IndirectBranch) { 262 llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress()); 263 if (PN->getNumIncomingValues() == 0) { 264 PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType())); 265 PN->eraseFromParent(); 266 } 267 } 268 269 EmitIfUsed(*this, EHResumeBlock); 270 EmitIfUsed(*this, TerminateLandingPad); 271 EmitIfUsed(*this, TerminateHandler); 272 EmitIfUsed(*this, UnreachableBlock); 273 274 if (CGM.getCodeGenOpts().EmitDeclMetadata) 275 EmitDeclMetadata(); 276 } 277 278 /// ShouldInstrumentFunction - Return true if the current function should be 279 /// instrumented with __cyg_profile_func_* calls 280 bool CodeGenFunction::ShouldInstrumentFunction() { 281 if (!CGM.getCodeGenOpts().InstrumentFunctions) 282 return false; 283 if (!CurFuncDecl || CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>()) 284 return false; 285 return true; 286 } 287 288 /// EmitFunctionInstrumentation - Emit LLVM code to call the specified 289 /// instrumentation function with the current function and the call site, if 290 /// function instrumentation is enabled. 291 void CodeGenFunction::EmitFunctionInstrumentation(const char *Fn) { 292 // void __cyg_profile_func_{enter,exit} (void *this_fn, void *call_site); 293 llvm::PointerType *PointerTy = Int8PtrTy; 294 llvm::Type *ProfileFuncArgs[] = { PointerTy, PointerTy }; 295 llvm::FunctionType *FunctionTy = 296 llvm::FunctionType::get(VoidTy, ProfileFuncArgs, false); 297 298 llvm::Constant *F = CGM.CreateRuntimeFunction(FunctionTy, Fn); 299 llvm::CallInst *CallSite = Builder.CreateCall( 300 CGM.getIntrinsic(llvm::Intrinsic::returnaddress), 301 llvm::ConstantInt::get(Int32Ty, 0), 302 "callsite"); 303 304 llvm::Value *args[] = { 305 llvm::ConstantExpr::getBitCast(CurFn, PointerTy), 306 CallSite 307 }; 308 309 EmitNounwindRuntimeCall(F, args); 310 } 311 312 void CodeGenFunction::EmitMCountInstrumentation() { 313 llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false); 314 315 llvm::Constant *MCountFn = 316 CGM.CreateRuntimeFunction(FTy, getTarget().getMCountName()); 317 EmitNounwindRuntimeCall(MCountFn); 318 } 319 320 // OpenCL v1.2 s5.6.4.6 allows the compiler to store kernel argument 321 // information in the program executable. The argument information stored 322 // includes the argument name, its type, the address and access qualifiers used. 323 static void GenOpenCLArgMetadata(const FunctionDecl *FD, llvm::Function *Fn, 324 CodeGenModule &CGM,llvm::LLVMContext &Context, 325 SmallVector <llvm::Value*, 5> &kernelMDArgs, 326 CGBuilderTy& Builder, ASTContext &ASTCtx) { 327 // Create MDNodes that represent the kernel arg metadata. 328 // Each MDNode is a list in the form of "key", N number of values which is 329 // the same number of values as their are kernel arguments. 330 331 // MDNode for the kernel argument address space qualifiers. 332 SmallVector<llvm::Value*, 8> addressQuals; 333 addressQuals.push_back(llvm::MDString::get(Context, "kernel_arg_addr_space")); 334 335 // MDNode for the kernel argument access qualifiers (images only). 336 SmallVector<llvm::Value*, 8> accessQuals; 337 accessQuals.push_back(llvm::MDString::get(Context, "kernel_arg_access_qual")); 338 339 // MDNode for the kernel argument type names. 340 SmallVector<llvm::Value*, 8> argTypeNames; 341 argTypeNames.push_back(llvm::MDString::get(Context, "kernel_arg_type")); 342 343 // MDNode for the kernel argument type qualifiers. 344 SmallVector<llvm::Value*, 8> argTypeQuals; 345 argTypeQuals.push_back(llvm::MDString::get(Context, "kernel_arg_type_qual")); 346 347 // MDNode for the kernel argument names. 348 SmallVector<llvm::Value*, 8> argNames; 349 argNames.push_back(llvm::MDString::get(Context, "kernel_arg_name")); 350 351 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) { 352 const ParmVarDecl *parm = FD->getParamDecl(i); 353 QualType ty = parm->getType(); 354 std::string typeQuals; 355 356 if (ty->isPointerType()) { 357 QualType pointeeTy = ty->getPointeeType(); 358 359 // Get address qualifier. 360 addressQuals.push_back(Builder.getInt32(ASTCtx.getTargetAddressSpace( 361 pointeeTy.getAddressSpace()))); 362 363 // Get argument type name. 364 std::string typeName = pointeeTy.getUnqualifiedType().getAsString() + "*"; 365 366 // Turn "unsigned type" to "utype" 367 std::string::size_type pos = typeName.find("unsigned"); 368 if (pos != std::string::npos) 369 typeName.erase(pos+1, 8); 370 371 argTypeNames.push_back(llvm::MDString::get(Context, typeName)); 372 373 // Get argument type qualifiers: 374 if (ty.isRestrictQualified()) 375 typeQuals = "restrict"; 376 if (pointeeTy.isConstQualified() || 377 (pointeeTy.getAddressSpace() == LangAS::opencl_constant)) 378 typeQuals += typeQuals.empty() ? "const" : " const"; 379 if (pointeeTy.isVolatileQualified()) 380 typeQuals += typeQuals.empty() ? "volatile" : " volatile"; 381 } else { 382 addressQuals.push_back(Builder.getInt32(0)); 383 384 // Get argument type name. 385 std::string typeName = ty.getUnqualifiedType().getAsString(); 386 387 // Turn "unsigned type" to "utype" 388 std::string::size_type pos = typeName.find("unsigned"); 389 if (pos != std::string::npos) 390 typeName.erase(pos+1, 8); 391 392 argTypeNames.push_back(llvm::MDString::get(Context, typeName)); 393 394 // Get argument type qualifiers: 395 if (ty.isConstQualified()) 396 typeQuals = "const"; 397 if (ty.isVolatileQualified()) 398 typeQuals += typeQuals.empty() ? "volatile" : " volatile"; 399 } 400 401 argTypeQuals.push_back(llvm::MDString::get(Context, typeQuals)); 402 403 // Get image access qualifier: 404 if (ty->isImageType()) { 405 if (parm->hasAttr<OpenCLImageAccessAttr>() && 406 parm->getAttr<OpenCLImageAccessAttr>()->getAccess() == CLIA_write_only) 407 accessQuals.push_back(llvm::MDString::get(Context, "write_only")); 408 else 409 accessQuals.push_back(llvm::MDString::get(Context, "read_only")); 410 } else 411 accessQuals.push_back(llvm::MDString::get(Context, "none")); 412 413 // Get argument name. 414 argNames.push_back(llvm::MDString::get(Context, parm->getName())); 415 } 416 417 kernelMDArgs.push_back(llvm::MDNode::get(Context, addressQuals)); 418 kernelMDArgs.push_back(llvm::MDNode::get(Context, accessQuals)); 419 kernelMDArgs.push_back(llvm::MDNode::get(Context, argTypeNames)); 420 kernelMDArgs.push_back(llvm::MDNode::get(Context, argTypeQuals)); 421 kernelMDArgs.push_back(llvm::MDNode::get(Context, argNames)); 422 } 423 424 void CodeGenFunction::EmitOpenCLKernelMetadata(const FunctionDecl *FD, 425 llvm::Function *Fn) 426 { 427 if (!FD->hasAttr<OpenCLKernelAttr>()) 428 return; 429 430 llvm::LLVMContext &Context = getLLVMContext(); 431 432 SmallVector <llvm::Value*, 5> kernelMDArgs; 433 kernelMDArgs.push_back(Fn); 434 435 if (CGM.getCodeGenOpts().EmitOpenCLArgMetadata) 436 GenOpenCLArgMetadata(FD, Fn, CGM, Context, kernelMDArgs, 437 Builder, getContext()); 438 439 if (FD->hasAttr<VecTypeHintAttr>()) { 440 VecTypeHintAttr *attr = FD->getAttr<VecTypeHintAttr>(); 441 QualType hintQTy = attr->getTypeHint(); 442 const ExtVectorType *hintEltQTy = hintQTy->getAs<ExtVectorType>(); 443 bool isSignedInteger = 444 hintQTy->isSignedIntegerType() || 445 (hintEltQTy && hintEltQTy->getElementType()->isSignedIntegerType()); 446 llvm::Value *attrMDArgs[] = { 447 llvm::MDString::get(Context, "vec_type_hint"), 448 llvm::UndefValue::get(CGM.getTypes().ConvertType(attr->getTypeHint())), 449 llvm::ConstantInt::get( 450 llvm::IntegerType::get(Context, 32), 451 llvm::APInt(32, (uint64_t)(isSignedInteger ? 1 : 0))) 452 }; 453 kernelMDArgs.push_back(llvm::MDNode::get(Context, attrMDArgs)); 454 } 455 456 if (FD->hasAttr<WorkGroupSizeHintAttr>()) { 457 WorkGroupSizeHintAttr *attr = FD->getAttr<WorkGroupSizeHintAttr>(); 458 llvm::Value *attrMDArgs[] = { 459 llvm::MDString::get(Context, "work_group_size_hint"), 460 Builder.getInt32(attr->getXDim()), 461 Builder.getInt32(attr->getYDim()), 462 Builder.getInt32(attr->getZDim()) 463 }; 464 kernelMDArgs.push_back(llvm::MDNode::get(Context, attrMDArgs)); 465 } 466 467 if (FD->hasAttr<ReqdWorkGroupSizeAttr>()) { 468 ReqdWorkGroupSizeAttr *attr = FD->getAttr<ReqdWorkGroupSizeAttr>(); 469 llvm::Value *attrMDArgs[] = { 470 llvm::MDString::get(Context, "reqd_work_group_size"), 471 Builder.getInt32(attr->getXDim()), 472 Builder.getInt32(attr->getYDim()), 473 Builder.getInt32(attr->getZDim()) 474 }; 475 kernelMDArgs.push_back(llvm::MDNode::get(Context, attrMDArgs)); 476 } 477 478 llvm::MDNode *kernelMDNode = llvm::MDNode::get(Context, kernelMDArgs); 479 llvm::NamedMDNode *OpenCLKernelMetadata = 480 CGM.getModule().getOrInsertNamedMetadata("opencl.kernels"); 481 OpenCLKernelMetadata->addOperand(kernelMDNode); 482 } 483 484 void CodeGenFunction::StartFunction(GlobalDecl GD, 485 QualType RetTy, 486 llvm::Function *Fn, 487 const CGFunctionInfo &FnInfo, 488 const FunctionArgList &Args, 489 SourceLocation StartLoc) { 490 const Decl *D = GD.getDecl(); 491 492 DidCallStackSave = false; 493 CurCodeDecl = D; 494 CurFuncDecl = (D ? D->getNonClosureContext() : 0); 495 FnRetTy = RetTy; 496 CurFn = Fn; 497 CurFnInfo = &FnInfo; 498 assert(CurFn->isDeclaration() && "Function already has body?"); 499 500 if (CGM.getSanitizerBlacklist().isIn(*Fn)) { 501 SanOpts = &SanitizerOptions::Disabled; 502 SanitizePerformTypeCheck = false; 503 } 504 505 // Pass inline keyword to optimizer if it appears explicitly on any 506 // declaration. 507 if (!CGM.getCodeGenOpts().NoInline) 508 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) 509 for (FunctionDecl::redecl_iterator RI = FD->redecls_begin(), 510 RE = FD->redecls_end(); RI != RE; ++RI) 511 if (RI->isInlineSpecified()) { 512 Fn->addFnAttr(llvm::Attribute::InlineHint); 513 break; 514 } 515 516 if (getLangOpts().OpenCL) { 517 // Add metadata for a kernel function. 518 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) 519 EmitOpenCLKernelMetadata(FD, Fn); 520 } 521 522 llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn); 523 524 // Create a marker to make it easy to insert allocas into the entryblock 525 // later. Don't create this with the builder, because we don't want it 526 // folded. 527 llvm::Value *Undef = llvm::UndefValue::get(Int32Ty); 528 AllocaInsertPt = new llvm::BitCastInst(Undef, Int32Ty, "", EntryBB); 529 if (Builder.isNamePreserving()) 530 AllocaInsertPt->setName("allocapt"); 531 532 ReturnBlock = getJumpDestInCurrentScope("return"); 533 534 Builder.SetInsertPoint(EntryBB); 535 536 // Emit subprogram debug descriptor. 537 if (CGDebugInfo *DI = getDebugInfo()) { 538 SmallVector<QualType, 16> ArgTypes; 539 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end(); 540 i != e; ++i) { 541 ArgTypes.push_back((*i)->getType()); 542 } 543 544 QualType FnType = 545 getContext().getFunctionType(RetTy, ArgTypes, 546 FunctionProtoType::ExtProtoInfo()); 547 548 DI->setLocation(StartLoc); 549 DI->EmitFunctionStart(GD, FnType, CurFn, Builder); 550 } 551 552 if (ShouldInstrumentFunction()) 553 EmitFunctionInstrumentation("__cyg_profile_func_enter"); 554 555 if (CGM.getCodeGenOpts().InstrumentForProfiling) 556 EmitMCountInstrumentation(); 557 558 if (RetTy->isVoidType()) { 559 // Void type; nothing to return. 560 ReturnValue = 0; 561 } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect && 562 !hasScalarEvaluationKind(CurFnInfo->getReturnType())) { 563 // Indirect aggregate return; emit returned value directly into sret slot. 564 // This reduces code size, and affects correctness in C++. 565 ReturnValue = CurFn->arg_begin(); 566 } else { 567 ReturnValue = CreateIRTemp(RetTy, "retval"); 568 569 // Tell the epilog emitter to autorelease the result. We do this 570 // now so that various specialized functions can suppress it 571 // during their IR-generation. 572 if (getLangOpts().ObjCAutoRefCount && 573 !CurFnInfo->isReturnsRetained() && 574 RetTy->isObjCRetainableType()) 575 AutoreleaseResult = true; 576 } 577 578 EmitStartEHSpec(CurCodeDecl); 579 580 PrologueCleanupDepth = EHStack.stable_begin(); 581 EmitFunctionProlog(*CurFnInfo, CurFn, Args); 582 583 if (D && isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance()) { 584 CGM.getCXXABI().EmitInstanceFunctionProlog(*this); 585 const CXXMethodDecl *MD = cast<CXXMethodDecl>(D); 586 if (MD->getParent()->isLambda() && 587 MD->getOverloadedOperator() == OO_Call) { 588 // We're in a lambda; figure out the captures. 589 MD->getParent()->getCaptureFields(LambdaCaptureFields, 590 LambdaThisCaptureField); 591 if (LambdaThisCaptureField) { 592 // If this lambda captures this, load it. 593 LValue ThisLValue = EmitLValueForLambdaField(LambdaThisCaptureField); 594 CXXThisValue = EmitLoadOfLValue(ThisLValue, 595 SourceLocation()).getScalarVal(); 596 } 597 } else { 598 // Not in a lambda; just use 'this' from the method. 599 // FIXME: Should we generate a new load for each use of 'this'? The 600 // fast register allocator would be happier... 601 CXXThisValue = CXXABIThisValue; 602 } 603 } 604 605 // If any of the arguments have a variably modified type, make sure to 606 // emit the type size. 607 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end(); 608 i != e; ++i) { 609 const VarDecl *VD = *i; 610 611 // Dig out the type as written from ParmVarDecls; it's unclear whether 612 // the standard (C99 6.9.1p10) requires this, but we're following the 613 // precedent set by gcc. 614 QualType Ty; 615 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) 616 Ty = PVD->getOriginalType(); 617 else 618 Ty = VD->getType(); 619 620 if (Ty->isVariablyModifiedType()) 621 EmitVariablyModifiedType(Ty); 622 } 623 // Emit a location at the end of the prologue. 624 if (CGDebugInfo *DI = getDebugInfo()) 625 DI->EmitLocation(Builder, StartLoc); 626 } 627 628 void CodeGenFunction::EmitFunctionBody(FunctionArgList &Args) { 629 const FunctionDecl *FD = cast<FunctionDecl>(CurGD.getDecl()); 630 assert(FD->getBody()); 631 if (const CompoundStmt *S = dyn_cast<CompoundStmt>(FD->getBody())) 632 EmitCompoundStmtWithoutScope(*S); 633 else 634 EmitStmt(FD->getBody()); 635 } 636 637 /// Tries to mark the given function nounwind based on the 638 /// non-existence of any throwing calls within it. We believe this is 639 /// lightweight enough to do at -O0. 640 static void TryMarkNoThrow(llvm::Function *F) { 641 // LLVM treats 'nounwind' on a function as part of the type, so we 642 // can't do this on functions that can be overwritten. 643 if (F->mayBeOverridden()) return; 644 645 for (llvm::Function::iterator FI = F->begin(), FE = F->end(); FI != FE; ++FI) 646 for (llvm::BasicBlock::iterator 647 BI = FI->begin(), BE = FI->end(); BI != BE; ++BI) 648 if (llvm::CallInst *Call = dyn_cast<llvm::CallInst>(&*BI)) { 649 if (!Call->doesNotThrow()) 650 return; 651 } else if (isa<llvm::ResumeInst>(&*BI)) { 652 return; 653 } 654 F->setDoesNotThrow(); 655 } 656 657 void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn, 658 const CGFunctionInfo &FnInfo) { 659 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 660 661 // Check if we should generate debug info for this function. 662 if (FD->hasAttr<NoDebugAttr>()) 663 DebugInfo = NULL; // disable debug info indefinitely for this function 664 665 FunctionArgList Args; 666 QualType ResTy = FD->getResultType(); 667 668 CurGD = GD; 669 const CXXMethodDecl *MD; 670 if ((MD = dyn_cast<CXXMethodDecl>(FD)) && MD->isInstance()) { 671 if (CGM.getCXXABI().HasThisReturn(GD)) 672 ResTy = MD->getThisType(getContext()); 673 CGM.getCXXABI().BuildInstanceFunctionParams(*this, ResTy, Args); 674 } 675 676 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) 677 Args.push_back(FD->getParamDecl(i)); 678 679 SourceRange BodyRange; 680 if (Stmt *Body = FD->getBody()) BodyRange = Body->getSourceRange(); 681 CurEHLocation = BodyRange.getEnd(); 682 683 // Emit the standard function prologue. 684 StartFunction(GD, ResTy, Fn, FnInfo, Args, BodyRange.getBegin()); 685 686 // Generate the body of the function. 687 if (isa<CXXDestructorDecl>(FD)) 688 EmitDestructorBody(Args); 689 else if (isa<CXXConstructorDecl>(FD)) 690 EmitConstructorBody(Args); 691 else if (getLangOpts().CUDA && 692 !CGM.getCodeGenOpts().CUDAIsDevice && 693 FD->hasAttr<CUDAGlobalAttr>()) 694 CGM.getCUDARuntime().EmitDeviceStubBody(*this, Args); 695 else if (isa<CXXConversionDecl>(FD) && 696 cast<CXXConversionDecl>(FD)->isLambdaToBlockPointerConversion()) { 697 // The lambda conversion to block pointer is special; the semantics can't be 698 // expressed in the AST, so IRGen needs to special-case it. 699 EmitLambdaToBlockPointerBody(Args); 700 } else if (isa<CXXMethodDecl>(FD) && 701 cast<CXXMethodDecl>(FD)->isLambdaStaticInvoker()) { 702 // The lambda static invoker function is special, because it forwards or 703 // clones the body of the function call operator (but is actually static). 704 EmitLambdaStaticInvokeFunction(cast<CXXMethodDecl>(FD)); 705 } else if (FD->isDefaulted() && isa<CXXMethodDecl>(FD) && 706 (cast<CXXMethodDecl>(FD)->isCopyAssignmentOperator() || 707 cast<CXXMethodDecl>(FD)->isMoveAssignmentOperator())) { 708 // Implicit copy-assignment gets the same special treatment as implicit 709 // copy-constructors. 710 emitImplicitAssignmentOperatorBody(Args); 711 } 712 else 713 EmitFunctionBody(Args); 714 715 // C++11 [stmt.return]p2: 716 // Flowing off the end of a function [...] results in undefined behavior in 717 // a value-returning function. 718 // C11 6.9.1p12: 719 // If the '}' that terminates a function is reached, and the value of the 720 // function call is used by the caller, the behavior is undefined. 721 if (getLangOpts().CPlusPlus && !FD->hasImplicitReturnZero() && 722 !FD->getResultType()->isVoidType() && Builder.GetInsertBlock()) { 723 if (SanOpts->Return) 724 EmitCheck(Builder.getFalse(), "missing_return", 725 EmitCheckSourceLocation(FD->getLocation()), 726 ArrayRef<llvm::Value *>(), CRK_Unrecoverable); 727 else if (CGM.getCodeGenOpts().OptimizationLevel == 0) 728 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::trap)); 729 Builder.CreateUnreachable(); 730 Builder.ClearInsertionPoint(); 731 } 732 733 // Emit the standard function epilogue. 734 FinishFunction(BodyRange.getEnd()); 735 736 // If we haven't marked the function nothrow through other means, do 737 // a quick pass now to see if we can. 738 if (!CurFn->doesNotThrow()) 739 TryMarkNoThrow(CurFn); 740 } 741 742 /// ContainsLabel - Return true if the statement contains a label in it. If 743 /// this statement is not executed normally, it not containing a label means 744 /// that we can just remove the code. 745 bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) { 746 // Null statement, not a label! 747 if (S == 0) return false; 748 749 // If this is a label, we have to emit the code, consider something like: 750 // if (0) { ... foo: bar(); } goto foo; 751 // 752 // TODO: If anyone cared, we could track __label__'s, since we know that you 753 // can't jump to one from outside their declared region. 754 if (isa<LabelStmt>(S)) 755 return true; 756 757 // If this is a case/default statement, and we haven't seen a switch, we have 758 // to emit the code. 759 if (isa<SwitchCase>(S) && !IgnoreCaseStmts) 760 return true; 761 762 // If this is a switch statement, we want to ignore cases below it. 763 if (isa<SwitchStmt>(S)) 764 IgnoreCaseStmts = true; 765 766 // Scan subexpressions for verboten labels. 767 for (Stmt::const_child_range I = S->children(); I; ++I) 768 if (ContainsLabel(*I, IgnoreCaseStmts)) 769 return true; 770 771 return false; 772 } 773 774 /// containsBreak - Return true if the statement contains a break out of it. 775 /// If the statement (recursively) contains a switch or loop with a break 776 /// inside of it, this is fine. 777 bool CodeGenFunction::containsBreak(const Stmt *S) { 778 // Null statement, not a label! 779 if (S == 0) return false; 780 781 // If this is a switch or loop that defines its own break scope, then we can 782 // include it and anything inside of it. 783 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S) || 784 isa<ForStmt>(S)) 785 return false; 786 787 if (isa<BreakStmt>(S)) 788 return true; 789 790 // Scan subexpressions for verboten breaks. 791 for (Stmt::const_child_range I = S->children(); I; ++I) 792 if (containsBreak(*I)) 793 return true; 794 795 return false; 796 } 797 798 799 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold 800 /// to a constant, or if it does but contains a label, return false. If it 801 /// constant folds return true and set the boolean result in Result. 802 bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond, 803 bool &ResultBool) { 804 llvm::APSInt ResultInt; 805 if (!ConstantFoldsToSimpleInteger(Cond, ResultInt)) 806 return false; 807 808 ResultBool = ResultInt.getBoolValue(); 809 return true; 810 } 811 812 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold 813 /// to a constant, or if it does but contains a label, return false. If it 814 /// constant folds return true and set the folded value. 815 bool CodeGenFunction:: 816 ConstantFoldsToSimpleInteger(const Expr *Cond, llvm::APSInt &ResultInt) { 817 // FIXME: Rename and handle conversion of other evaluatable things 818 // to bool. 819 llvm::APSInt Int; 820 if (!Cond->EvaluateAsInt(Int, getContext())) 821 return false; // Not foldable, not integer or not fully evaluatable. 822 823 if (CodeGenFunction::ContainsLabel(Cond)) 824 return false; // Contains a label. 825 826 ResultInt = Int; 827 return true; 828 } 829 830 831 832 /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if 833 /// statement) to the specified blocks. Based on the condition, this might try 834 /// to simplify the codegen of the conditional based on the branch. 835 /// 836 void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond, 837 llvm::BasicBlock *TrueBlock, 838 llvm::BasicBlock *FalseBlock) { 839 Cond = Cond->IgnoreParens(); 840 841 if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) { 842 // Handle X && Y in a condition. 843 if (CondBOp->getOpcode() == BO_LAnd) { 844 // If we have "1 && X", simplify the code. "0 && X" would have constant 845 // folded if the case was simple enough. 846 bool ConstantBool = false; 847 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) && 848 ConstantBool) { 849 // br(1 && X) -> br(X). 850 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock); 851 } 852 853 // If we have "X && 1", simplify the code to use an uncond branch. 854 // "X && 0" would have been constant folded to 0. 855 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) && 856 ConstantBool) { 857 // br(X && 1) -> br(X). 858 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock); 859 } 860 861 // Emit the LHS as a conditional. If the LHS conditional is false, we 862 // want to jump to the FalseBlock. 863 llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true"); 864 865 ConditionalEvaluation eval(*this); 866 EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock); 867 EmitBlock(LHSTrue); 868 869 // Any temporaries created here are conditional. 870 eval.begin(*this); 871 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock); 872 eval.end(*this); 873 874 return; 875 } 876 877 if (CondBOp->getOpcode() == BO_LOr) { 878 // If we have "0 || X", simplify the code. "1 || X" would have constant 879 // folded if the case was simple enough. 880 bool ConstantBool = false; 881 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) && 882 !ConstantBool) { 883 // br(0 || X) -> br(X). 884 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock); 885 } 886 887 // If we have "X || 0", simplify the code to use an uncond branch. 888 // "X || 1" would have been constant folded to 1. 889 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) && 890 !ConstantBool) { 891 // br(X || 0) -> br(X). 892 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock); 893 } 894 895 // Emit the LHS as a conditional. If the LHS conditional is true, we 896 // want to jump to the TrueBlock. 897 llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false"); 898 899 ConditionalEvaluation eval(*this); 900 EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse); 901 EmitBlock(LHSFalse); 902 903 // Any temporaries created here are conditional. 904 eval.begin(*this); 905 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock); 906 eval.end(*this); 907 908 return; 909 } 910 } 911 912 if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) { 913 // br(!x, t, f) -> br(x, f, t) 914 if (CondUOp->getOpcode() == UO_LNot) 915 return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock); 916 } 917 918 if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) { 919 // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f)) 920 llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true"); 921 llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false"); 922 923 ConditionalEvaluation cond(*this); 924 EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock); 925 926 cond.begin(*this); 927 EmitBlock(LHSBlock); 928 EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock); 929 cond.end(*this); 930 931 cond.begin(*this); 932 EmitBlock(RHSBlock); 933 EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock); 934 cond.end(*this); 935 936 return; 937 } 938 939 if (const CXXThrowExpr *Throw = dyn_cast<CXXThrowExpr>(Cond)) { 940 // Conditional operator handling can give us a throw expression as a 941 // condition for a case like: 942 // br(c ? throw x : y, t, f) -> br(c, br(throw x, t, f), br(y, t, f) 943 // Fold this to: 944 // br(c, throw x, br(y, t, f)) 945 EmitCXXThrowExpr(Throw, /*KeepInsertionPoint*/false); 946 return; 947 } 948 949 // Emit the code with the fully general case. 950 llvm::Value *CondV = EvaluateExprAsBool(Cond); 951 Builder.CreateCondBr(CondV, TrueBlock, FalseBlock); 952 } 953 954 /// ErrorUnsupported - Print out an error that codegen doesn't support the 955 /// specified stmt yet. 956 void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type) { 957 CGM.ErrorUnsupported(S, Type); 958 } 959 960 /// emitNonZeroVLAInit - Emit the "zero" initialization of a 961 /// variable-length array whose elements have a non-zero bit-pattern. 962 /// 963 /// \param baseType the inner-most element type of the array 964 /// \param src - a char* pointing to the bit-pattern for a single 965 /// base element of the array 966 /// \param sizeInChars - the total size of the VLA, in chars 967 static void emitNonZeroVLAInit(CodeGenFunction &CGF, QualType baseType, 968 llvm::Value *dest, llvm::Value *src, 969 llvm::Value *sizeInChars) { 970 std::pair<CharUnits,CharUnits> baseSizeAndAlign 971 = CGF.getContext().getTypeInfoInChars(baseType); 972 973 CGBuilderTy &Builder = CGF.Builder; 974 975 llvm::Value *baseSizeInChars 976 = llvm::ConstantInt::get(CGF.IntPtrTy, baseSizeAndAlign.first.getQuantity()); 977 978 llvm::Type *i8p = Builder.getInt8PtrTy(); 979 980 llvm::Value *begin = Builder.CreateBitCast(dest, i8p, "vla.begin"); 981 llvm::Value *end = Builder.CreateInBoundsGEP(dest, sizeInChars, "vla.end"); 982 983 llvm::BasicBlock *originBB = CGF.Builder.GetInsertBlock(); 984 llvm::BasicBlock *loopBB = CGF.createBasicBlock("vla-init.loop"); 985 llvm::BasicBlock *contBB = CGF.createBasicBlock("vla-init.cont"); 986 987 // Make a loop over the VLA. C99 guarantees that the VLA element 988 // count must be nonzero. 989 CGF.EmitBlock(loopBB); 990 991 llvm::PHINode *cur = Builder.CreatePHI(i8p, 2, "vla.cur"); 992 cur->addIncoming(begin, originBB); 993 994 // memcpy the individual element bit-pattern. 995 Builder.CreateMemCpy(cur, src, baseSizeInChars, 996 baseSizeAndAlign.second.getQuantity(), 997 /*volatile*/ false); 998 999 // Go to the next element. 1000 llvm::Value *next = Builder.CreateConstInBoundsGEP1_32(cur, 1, "vla.next"); 1001 1002 // Leave if that's the end of the VLA. 1003 llvm::Value *done = Builder.CreateICmpEQ(next, end, "vla-init.isdone"); 1004 Builder.CreateCondBr(done, contBB, loopBB); 1005 cur->addIncoming(next, loopBB); 1006 1007 CGF.EmitBlock(contBB); 1008 } 1009 1010 void 1011 CodeGenFunction::EmitNullInitialization(llvm::Value *DestPtr, QualType Ty) { 1012 // Ignore empty classes in C++. 1013 if (getLangOpts().CPlusPlus) { 1014 if (const RecordType *RT = Ty->getAs<RecordType>()) { 1015 if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty()) 1016 return; 1017 } 1018 } 1019 1020 // Cast the dest ptr to the appropriate i8 pointer type. 1021 unsigned DestAS = 1022 cast<llvm::PointerType>(DestPtr->getType())->getAddressSpace(); 1023 llvm::Type *BP = Builder.getInt8PtrTy(DestAS); 1024 if (DestPtr->getType() != BP) 1025 DestPtr = Builder.CreateBitCast(DestPtr, BP); 1026 1027 // Get size and alignment info for this aggregate. 1028 std::pair<CharUnits, CharUnits> TypeInfo = 1029 getContext().getTypeInfoInChars(Ty); 1030 CharUnits Size = TypeInfo.first; 1031 CharUnits Align = TypeInfo.second; 1032 1033 llvm::Value *SizeVal; 1034 const VariableArrayType *vla; 1035 1036 // Don't bother emitting a zero-byte memset. 1037 if (Size.isZero()) { 1038 // But note that getTypeInfo returns 0 for a VLA. 1039 if (const VariableArrayType *vlaType = 1040 dyn_cast_or_null<VariableArrayType>( 1041 getContext().getAsArrayType(Ty))) { 1042 QualType eltType; 1043 llvm::Value *numElts; 1044 llvm::tie(numElts, eltType) = getVLASize(vlaType); 1045 1046 SizeVal = numElts; 1047 CharUnits eltSize = getContext().getTypeSizeInChars(eltType); 1048 if (!eltSize.isOne()) 1049 SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(eltSize)); 1050 vla = vlaType; 1051 } else { 1052 return; 1053 } 1054 } else { 1055 SizeVal = CGM.getSize(Size); 1056 vla = 0; 1057 } 1058 1059 // If the type contains a pointer to data member we can't memset it to zero. 1060 // Instead, create a null constant and copy it to the destination. 1061 // TODO: there are other patterns besides zero that we can usefully memset, 1062 // like -1, which happens to be the pattern used by member-pointers. 1063 if (!CGM.getTypes().isZeroInitializable(Ty)) { 1064 // For a VLA, emit a single element, then splat that over the VLA. 1065 if (vla) Ty = getContext().getBaseElementType(vla); 1066 1067 llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty); 1068 1069 llvm::GlobalVariable *NullVariable = 1070 new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(), 1071 /*isConstant=*/true, 1072 llvm::GlobalVariable::PrivateLinkage, 1073 NullConstant, Twine()); 1074 llvm::Value *SrcPtr = 1075 Builder.CreateBitCast(NullVariable, Builder.getInt8PtrTy()); 1076 1077 if (vla) return emitNonZeroVLAInit(*this, Ty, DestPtr, SrcPtr, SizeVal); 1078 1079 // Get and call the appropriate llvm.memcpy overload. 1080 Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, Align.getQuantity(), false); 1081 return; 1082 } 1083 1084 // Otherwise, just memset the whole thing to zero. This is legal 1085 // because in LLVM, all default initializers (other than the ones we just 1086 // handled above) are guaranteed to have a bit pattern of all zeros. 1087 Builder.CreateMemSet(DestPtr, Builder.getInt8(0), SizeVal, 1088 Align.getQuantity(), false); 1089 } 1090 1091 llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelDecl *L) { 1092 // Make sure that there is a block for the indirect goto. 1093 if (IndirectBranch == 0) 1094 GetIndirectGotoBlock(); 1095 1096 llvm::BasicBlock *BB = getJumpDestForLabel(L).getBlock(); 1097 1098 // Make sure the indirect branch includes all of the address-taken blocks. 1099 IndirectBranch->addDestination(BB); 1100 return llvm::BlockAddress::get(CurFn, BB); 1101 } 1102 1103 llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() { 1104 // If we already made the indirect branch for indirect goto, return its block. 1105 if (IndirectBranch) return IndirectBranch->getParent(); 1106 1107 CGBuilderTy TmpBuilder(createBasicBlock("indirectgoto")); 1108 1109 // Create the PHI node that indirect gotos will add entries to. 1110 llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, 0, 1111 "indirect.goto.dest"); 1112 1113 // Create the indirect branch instruction. 1114 IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal); 1115 return IndirectBranch->getParent(); 1116 } 1117 1118 /// Computes the length of an array in elements, as well as the base 1119 /// element type and a properly-typed first element pointer. 1120 llvm::Value *CodeGenFunction::emitArrayLength(const ArrayType *origArrayType, 1121 QualType &baseType, 1122 llvm::Value *&addr) { 1123 const ArrayType *arrayType = origArrayType; 1124 1125 // If it's a VLA, we have to load the stored size. Note that 1126 // this is the size of the VLA in bytes, not its size in elements. 1127 llvm::Value *numVLAElements = 0; 1128 if (isa<VariableArrayType>(arrayType)) { 1129 numVLAElements = getVLASize(cast<VariableArrayType>(arrayType)).first; 1130 1131 // Walk into all VLAs. This doesn't require changes to addr, 1132 // which has type T* where T is the first non-VLA element type. 1133 do { 1134 QualType elementType = arrayType->getElementType(); 1135 arrayType = getContext().getAsArrayType(elementType); 1136 1137 // If we only have VLA components, 'addr' requires no adjustment. 1138 if (!arrayType) { 1139 baseType = elementType; 1140 return numVLAElements; 1141 } 1142 } while (isa<VariableArrayType>(arrayType)); 1143 1144 // We get out here only if we find a constant array type 1145 // inside the VLA. 1146 } 1147 1148 // We have some number of constant-length arrays, so addr should 1149 // have LLVM type [M x [N x [...]]]*. Build a GEP that walks 1150 // down to the first element of addr. 1151 SmallVector<llvm::Value*, 8> gepIndices; 1152 1153 // GEP down to the array type. 1154 llvm::ConstantInt *zero = Builder.getInt32(0); 1155 gepIndices.push_back(zero); 1156 1157 uint64_t countFromCLAs = 1; 1158 QualType eltType; 1159 1160 llvm::ArrayType *llvmArrayType = 1161 dyn_cast<llvm::ArrayType>( 1162 cast<llvm::PointerType>(addr->getType())->getElementType()); 1163 while (llvmArrayType) { 1164 assert(isa<ConstantArrayType>(arrayType)); 1165 assert(cast<ConstantArrayType>(arrayType)->getSize().getZExtValue() 1166 == llvmArrayType->getNumElements()); 1167 1168 gepIndices.push_back(zero); 1169 countFromCLAs *= llvmArrayType->getNumElements(); 1170 eltType = arrayType->getElementType(); 1171 1172 llvmArrayType = 1173 dyn_cast<llvm::ArrayType>(llvmArrayType->getElementType()); 1174 arrayType = getContext().getAsArrayType(arrayType->getElementType()); 1175 assert((!llvmArrayType || arrayType) && 1176 "LLVM and Clang types are out-of-synch"); 1177 } 1178 1179 if (arrayType) { 1180 // From this point onwards, the Clang array type has been emitted 1181 // as some other type (probably a packed struct). Compute the array 1182 // size, and just emit the 'begin' expression as a bitcast. 1183 while (arrayType) { 1184 countFromCLAs *= 1185 cast<ConstantArrayType>(arrayType)->getSize().getZExtValue(); 1186 eltType = arrayType->getElementType(); 1187 arrayType = getContext().getAsArrayType(eltType); 1188 } 1189 1190 unsigned AddressSpace = addr->getType()->getPointerAddressSpace(); 1191 llvm::Type *BaseType = ConvertType(eltType)->getPointerTo(AddressSpace); 1192 addr = Builder.CreateBitCast(addr, BaseType, "array.begin"); 1193 } else { 1194 // Create the actual GEP. 1195 addr = Builder.CreateInBoundsGEP(addr, gepIndices, "array.begin"); 1196 } 1197 1198 baseType = eltType; 1199 1200 llvm::Value *numElements 1201 = llvm::ConstantInt::get(SizeTy, countFromCLAs); 1202 1203 // If we had any VLA dimensions, factor them in. 1204 if (numVLAElements) 1205 numElements = Builder.CreateNUWMul(numVLAElements, numElements); 1206 1207 return numElements; 1208 } 1209 1210 std::pair<llvm::Value*, QualType> 1211 CodeGenFunction::getVLASize(QualType type) { 1212 const VariableArrayType *vla = getContext().getAsVariableArrayType(type); 1213 assert(vla && "type was not a variable array type!"); 1214 return getVLASize(vla); 1215 } 1216 1217 std::pair<llvm::Value*, QualType> 1218 CodeGenFunction::getVLASize(const VariableArrayType *type) { 1219 // The number of elements so far; always size_t. 1220 llvm::Value *numElements = 0; 1221 1222 QualType elementType; 1223 do { 1224 elementType = type->getElementType(); 1225 llvm::Value *vlaSize = VLASizeMap[type->getSizeExpr()]; 1226 assert(vlaSize && "no size for VLA!"); 1227 assert(vlaSize->getType() == SizeTy); 1228 1229 if (!numElements) { 1230 numElements = vlaSize; 1231 } else { 1232 // It's undefined behavior if this wraps around, so mark it that way. 1233 // FIXME: Teach -fcatch-undefined-behavior to trap this. 1234 numElements = Builder.CreateNUWMul(numElements, vlaSize); 1235 } 1236 } while ((type = getContext().getAsVariableArrayType(elementType))); 1237 1238 return std::pair<llvm::Value*,QualType>(numElements, elementType); 1239 } 1240 1241 void CodeGenFunction::EmitVariablyModifiedType(QualType type) { 1242 assert(type->isVariablyModifiedType() && 1243 "Must pass variably modified type to EmitVLASizes!"); 1244 1245 EnsureInsertPoint(); 1246 1247 // We're going to walk down into the type and look for VLA 1248 // expressions. 1249 do { 1250 assert(type->isVariablyModifiedType()); 1251 1252 const Type *ty = type.getTypePtr(); 1253 switch (ty->getTypeClass()) { 1254 1255 #define TYPE(Class, Base) 1256 #define ABSTRACT_TYPE(Class, Base) 1257 #define NON_CANONICAL_TYPE(Class, Base) 1258 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 1259 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 1260 #include "clang/AST/TypeNodes.def" 1261 llvm_unreachable("unexpected dependent type!"); 1262 1263 // These types are never variably-modified. 1264 case Type::Builtin: 1265 case Type::Complex: 1266 case Type::Vector: 1267 case Type::ExtVector: 1268 case Type::Record: 1269 case Type::Enum: 1270 case Type::Elaborated: 1271 case Type::TemplateSpecialization: 1272 case Type::ObjCObject: 1273 case Type::ObjCInterface: 1274 case Type::ObjCObjectPointer: 1275 llvm_unreachable("type class is never variably-modified!"); 1276 1277 case Type::Decayed: 1278 type = cast<DecayedType>(ty)->getPointeeType(); 1279 break; 1280 1281 case Type::Pointer: 1282 type = cast<PointerType>(ty)->getPointeeType(); 1283 break; 1284 1285 case Type::BlockPointer: 1286 type = cast<BlockPointerType>(ty)->getPointeeType(); 1287 break; 1288 1289 case Type::LValueReference: 1290 case Type::RValueReference: 1291 type = cast<ReferenceType>(ty)->getPointeeType(); 1292 break; 1293 1294 case Type::MemberPointer: 1295 type = cast<MemberPointerType>(ty)->getPointeeType(); 1296 break; 1297 1298 case Type::ConstantArray: 1299 case Type::IncompleteArray: 1300 // Losing element qualification here is fine. 1301 type = cast<ArrayType>(ty)->getElementType(); 1302 break; 1303 1304 case Type::VariableArray: { 1305 // Losing element qualification here is fine. 1306 const VariableArrayType *vat = cast<VariableArrayType>(ty); 1307 1308 // Unknown size indication requires no size computation. 1309 // Otherwise, evaluate and record it. 1310 if (const Expr *size = vat->getSizeExpr()) { 1311 // It's possible that we might have emitted this already, 1312 // e.g. with a typedef and a pointer to it. 1313 llvm::Value *&entry = VLASizeMap[size]; 1314 if (!entry) { 1315 llvm::Value *Size = EmitScalarExpr(size); 1316 1317 // C11 6.7.6.2p5: 1318 // If the size is an expression that is not an integer constant 1319 // expression [...] each time it is evaluated it shall have a value 1320 // greater than zero. 1321 if (SanOpts->VLABound && 1322 size->getType()->isSignedIntegerType()) { 1323 llvm::Value *Zero = llvm::Constant::getNullValue(Size->getType()); 1324 llvm::Constant *StaticArgs[] = { 1325 EmitCheckSourceLocation(size->getLocStart()), 1326 EmitCheckTypeDescriptor(size->getType()) 1327 }; 1328 EmitCheck(Builder.CreateICmpSGT(Size, Zero), 1329 "vla_bound_not_positive", StaticArgs, Size, 1330 CRK_Recoverable); 1331 } 1332 1333 // Always zexting here would be wrong if it weren't 1334 // undefined behavior to have a negative bound. 1335 entry = Builder.CreateIntCast(Size, SizeTy, /*signed*/ false); 1336 } 1337 } 1338 type = vat->getElementType(); 1339 break; 1340 } 1341 1342 case Type::FunctionProto: 1343 case Type::FunctionNoProto: 1344 type = cast<FunctionType>(ty)->getResultType(); 1345 break; 1346 1347 case Type::Paren: 1348 case Type::TypeOf: 1349 case Type::UnaryTransform: 1350 case Type::Attributed: 1351 case Type::SubstTemplateTypeParm: 1352 case Type::PackExpansion: 1353 // Keep walking after single level desugaring. 1354 type = type.getSingleStepDesugaredType(getContext()); 1355 break; 1356 1357 case Type::Typedef: 1358 case Type::Decltype: 1359 case Type::Auto: 1360 // Stop walking: nothing to do. 1361 return; 1362 1363 case Type::TypeOfExpr: 1364 // Stop walking: emit typeof expression. 1365 EmitIgnoredExpr(cast<TypeOfExprType>(ty)->getUnderlyingExpr()); 1366 return; 1367 1368 case Type::Atomic: 1369 type = cast<AtomicType>(ty)->getValueType(); 1370 break; 1371 } 1372 } while (type->isVariablyModifiedType()); 1373 } 1374 1375 llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) { 1376 if (getContext().getBuiltinVaListType()->isArrayType()) 1377 return EmitScalarExpr(E); 1378 return EmitLValue(E).getAddress(); 1379 } 1380 1381 void CodeGenFunction::EmitDeclRefExprDbgValue(const DeclRefExpr *E, 1382 llvm::Constant *Init) { 1383 assert (Init && "Invalid DeclRefExpr initializer!"); 1384 if (CGDebugInfo *Dbg = getDebugInfo()) 1385 if (CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) 1386 Dbg->EmitGlobalVariable(E->getDecl(), Init); 1387 } 1388 1389 CodeGenFunction::PeepholeProtection 1390 CodeGenFunction::protectFromPeepholes(RValue rvalue) { 1391 // At the moment, the only aggressive peephole we do in IR gen 1392 // is trunc(zext) folding, but if we add more, we can easily 1393 // extend this protection. 1394 1395 if (!rvalue.isScalar()) return PeepholeProtection(); 1396 llvm::Value *value = rvalue.getScalarVal(); 1397 if (!isa<llvm::ZExtInst>(value)) return PeepholeProtection(); 1398 1399 // Just make an extra bitcast. 1400 assert(HaveInsertPoint()); 1401 llvm::Instruction *inst = new llvm::BitCastInst(value, value->getType(), "", 1402 Builder.GetInsertBlock()); 1403 1404 PeepholeProtection protection; 1405 protection.Inst = inst; 1406 return protection; 1407 } 1408 1409 void CodeGenFunction::unprotectFromPeepholes(PeepholeProtection protection) { 1410 if (!protection.Inst) return; 1411 1412 // In theory, we could try to duplicate the peepholes now, but whatever. 1413 protection.Inst->eraseFromParent(); 1414 } 1415 1416 llvm::Value *CodeGenFunction::EmitAnnotationCall(llvm::Value *AnnotationFn, 1417 llvm::Value *AnnotatedVal, 1418 StringRef AnnotationStr, 1419 SourceLocation Location) { 1420 llvm::Value *Args[4] = { 1421 AnnotatedVal, 1422 Builder.CreateBitCast(CGM.EmitAnnotationString(AnnotationStr), Int8PtrTy), 1423 Builder.CreateBitCast(CGM.EmitAnnotationUnit(Location), Int8PtrTy), 1424 CGM.EmitAnnotationLineNo(Location) 1425 }; 1426 return Builder.CreateCall(AnnotationFn, Args); 1427 } 1428 1429 void CodeGenFunction::EmitVarAnnotations(const VarDecl *D, llvm::Value *V) { 1430 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute"); 1431 // FIXME We create a new bitcast for every annotation because that's what 1432 // llvm-gcc was doing. 1433 for (specific_attr_iterator<AnnotateAttr> 1434 ai = D->specific_attr_begin<AnnotateAttr>(), 1435 ae = D->specific_attr_end<AnnotateAttr>(); ai != ae; ++ai) 1436 EmitAnnotationCall(CGM.getIntrinsic(llvm::Intrinsic::var_annotation), 1437 Builder.CreateBitCast(V, CGM.Int8PtrTy, V->getName()), 1438 (*ai)->getAnnotation(), D->getLocation()); 1439 } 1440 1441 llvm::Value *CodeGenFunction::EmitFieldAnnotations(const FieldDecl *D, 1442 llvm::Value *V) { 1443 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute"); 1444 llvm::Type *VTy = V->getType(); 1445 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::ptr_annotation, 1446 CGM.Int8PtrTy); 1447 1448 for (specific_attr_iterator<AnnotateAttr> 1449 ai = D->specific_attr_begin<AnnotateAttr>(), 1450 ae = D->specific_attr_end<AnnotateAttr>(); ai != ae; ++ai) { 1451 // FIXME Always emit the cast inst so we can differentiate between 1452 // annotation on the first field of a struct and annotation on the struct 1453 // itself. 1454 if (VTy != CGM.Int8PtrTy) 1455 V = Builder.Insert(new llvm::BitCastInst(V, CGM.Int8PtrTy)); 1456 V = EmitAnnotationCall(F, V, (*ai)->getAnnotation(), D->getLocation()); 1457 V = Builder.CreateBitCast(V, VTy); 1458 } 1459 1460 return V; 1461 } 1462 1463 CodeGenFunction::CGCapturedStmtInfo::~CGCapturedStmtInfo() { } 1464